girt 0.6.4

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
#![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, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use super::{RefName, packed};
use crate::{ObjectFormat, ObjectId, Repository};

/// A reference store using the opened [`Repository`]'s configured backend.
///
/// Reftable operations read owned bounded stack snapshots. Each public read takes a fresh
/// snapshot; separate reads or symbolic hops are not a shared snapshot. Use
/// [`super::reftable::Snapshot`] to retain a complete generation. Reads make one attempt and
/// report missing tables during concurrent compaction; callers decide whether to retry.
/// [`Self::with_reftable_limits`] selects per-stack budgets. Binary logs preserve arbitrary
/// fields through the codec; [`Self::reflog`] interprets signed timestamps and removes one trailing
/// message newline. [`Self::imported_reflog`] preserves files bytes and binary fields with bounded
/// retention, recoverable roots and wider numeric interpretation. Other uppercase pseudorefs are
/// preserved by the codec and compaction but remain outside [`RefName`]'s operation namespace.
///
/// Reftable writes hold common/private `tables.list.lock` files in path order, validate every
/// edit and result budget, and publish one immutable table per affected stack. Each stack's
/// references and logs become visible together. A linked-worktree edit can span two stacks:
/// publication follows path order and failures report completed per-reference/per-log effects.
/// No automatic compaction, expiry, fsync or retry occurs. Failed list publication may leave an
/// unlisted immutable table; readers ignore it. Explicit [`super::reftable::compact`] preserves
/// live logs and reports obsolete-file cleanup failures. Owned locks use best-effort cleanup;
/// termination can leave stale locks requiring caller-authorized recovery.
///
/// The following storage details describe the files backend.
///
/// Supports SHA-1 and SHA-256 references on Unix and Windows local filesystems. Repository
/// configuration selects the format; mixed-format targets and expectations fail before locks are
/// acquired. `HEAD`, `refs/bisect/`, `refs/rewritten/`, and `refs/worktree/` use the current
/// worktree's Git directory; other `refs/` names and packed refs use the common directory.
/// Cross-worktree aliases and other pseudorefs are not supported. Filesystem symlinks within these
/// paths are rejected, including legacy symlink HEADs.
///
/// Operations are synchronous. Reads are live, not a snapshot across multiple refs or symbolic
/// hops. Loose files take precedence, including malformed loose files (no fallback on errors).
/// Packed lookup validates the whole file and allocates proportional to its size; there is no
/// configurable byte limit or cache. Peel records are validated but never returned as resolution.
///
/// Writes require a trusted repository on a local filesystem with exclusive file creation and
/// atomic rename semantics. Cooperating writers must honor Git's `.lock` protocol; adversarial
/// path replacement, network filesystems, and changing repository configuration/layout while a
/// handle is in use are outside this contract. Windows uses UTF-8 names and rejects Win32 device
/// names, invalid filename characters, and trailing-dot components. Unix retains byte names.
/// Case and Unicode aliases inherit the volume's behavior; no portable alias mapping is promised.
/// On Windows lock handles exclude delete sharing until cleanup; publication uses a separate
/// same-directory temporary file. Cleanup closes the owned handle before removing its path.
/// Unix cleanup checks device/inode identity and leaves replacement locks untouched.
/// Permissions follow ordinary file creation and the process umask on Unix; Windows inherits
/// directory ACLs. Existing destination ACLs and crash durability are not preserved guarantees.
#[derive(Clone, Copy, Debug)]
pub struct References<'a> {
    pub(super) reftable_limits: super::reftable::StackLimits,
    pub(crate) git_dir: &'a Path,
    pub(crate) common_dir: &'a Path,
    pub(crate) object_format: ObjectFormat,
    pub(crate) reference_backend: Backend,
}

/// A stored reference value paired with metadata captured from the same effective record.
///
/// A peeled hint is storage metadata, not proof of an object's existence or type. It may be used
/// to recognize an already-known commit; otherwise callers must validate the object themselves.
/// Symbolic and loose references have no hint. Separate observations need not share a generation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReferenceObservation {
    /// Exact requested reference name, including supported pseudorefs such as HEAD.
    pub name: RefName,
    /// Effective stored value, without symbolic resolution.
    pub target: Target,
    /// Associated peeled identity, if the selected backend record supplies one.
    pub peeled_hint: Option<ObjectId>,
}

/// On-disk reference storage selected by repository configuration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Backend {
    /// Loose references, packed references and files reflogs.
    Files,
    /// Immutable reference/reflog tables and a stack ordering file.
    Reftable,
}

/// The stored value of one reference, before symbolic resolution.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Target {
    /// Repository-format object identity. Existence and object type are not checked.
    Direct(ObjectId),
    /// Another full reference name; it may be missing or form a cycle.
    Symbolic(RefName),
}

/// A precondition checked under locks against the destination's stored value.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Expected {
    /// Accept any valid current value or absence.
    Any,
    /// Require no effective stored value; deletion then succeeds without a change.
    Absent,
    /// Require this exact direct ID or symbolic name (without dereferencing it).
    Value(Target),
    /// Require a stored value, either direct or symbolic.
    Exists,
    /// Permit absence or this exact stored value; never overwrite a different value.
    AbsentOr(Target),
}

/// Formats a stored value as Git shows it: a hex ID, `ref: <name>`, or `nothing`.
struct DisplayTarget<'a>(Option<&'a Target>);

impl std::fmt::Display for DisplayTarget<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            None => f.write_str("nothing"),
            Some(Target::Direct(id)) => write!(f, "{id}"),
            Some(Target::Symbolic(name)) => {
                write!(f, "ref: {}", String::from_utf8_lossy(name.as_bytes()))
            }
        }
    }
}

/// The terminal name and optional object identity reached by symbolic resolution.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Resolution {
    /// Last name visited; also identifies the missing target of an unborn/dangling chain.
    pub name: RefName,
    /// `None` means the terminal reference is absent, not that its object is missing.
    pub id: Option<ObjectId>,
}

/// Reference validation, storage, resolution, or update failure.
#[derive(Debug, thiserror::Error)]
pub enum ReferenceError {
    /// Reftable codec or resource failure.
    #[error(transparent)]
    Reftable(#[from] super::reftable::Error),
    /// Cooperative cancellation before the next publication boundary.
    #[error("reference operation cancelled")]
    Cancelled,
    /// A supplied identity differs from the repository format.
    #[error(transparent)]
    ObjectFormat(#[from] crate::ObjectFormatError),
    /// Filesystem failure, with its original cause and path.
    #[error("reference I/O at {path}")]
    Io {
        /// Affected file or directory.
        path: PathBuf,
        /// Underlying filesystem error.
        #[source]
        source: io::Error,
    },
    /// Packed deletion succeeded, but removing the loose file failed. Packed bytes are not
    /// restored.
    #[error("packed reference removed, but loose deletion failed at {path}")]
    PackedDeleted {
        /// Loose reference that could not be removed.
        path: PathBuf,
        /// Underlying unlink failure. The current loose value remains under the writer contract.
        #[source]
        source: io::Error,
    },
    /// Invalid on-disk data; a broken loose ref never falls back to a packed value.
    #[error("malformed reference at {path}: {reason}")]
    Malformed {
        /// File containing invalid data.
        path: PathBuf,
        /// Violated format rule.
        reason: &'static str,
    },
    /// Recognized feature outside this implementation's supported boundary.
    #[error("unsupported reference feature: {0}")]
    Unsupported(&'static str),
    /// A caller-supplied bound stopped a reference or history inventory.
    #[error("reference resource limit: {0}")]
    Limit(&'static str),
    /// Another writer owns a lock. No waiting, lock stealing, or automatic retry is performed.
    #[error("reference lock already exists: {0}")]
    Locked(PathBuf),
    /// The destination did not satisfy the caller's precondition.
    #[error("reference value did not match the expected value (found {})", DisplayTarget(actual.as_ref()))]
    Mismatch {
        /// Actual stored value under the lock, or absence.
        actual: Option<Target>,
    },
    /// A symbolic chain revisited a name.
    #[error("symbolic reference cycle at {0:?}")]
    Cycle(RefName),
    /// Resolution would follow more symbolic links than allowed.
    #[error("symbolic reference depth exceeds {0}")]
    Depth(usize),
    /// A reference occupies an ancestor or descendant of the requested name.
    #[error("reference namespace conflict at {0}")]
    Conflict(PathBuf),
    /// Symbolic HEAD must point into `refs/`, not back to the pseudoref HEAD.
    #[error("symbolic HEAD must point into refs/")]
    InvalidHeadTarget,
    /// Zero IDs cannot be stored; use an explicit deletion method instead.
    #[error("zero reference IDs are not supported")]
    ZeroId,
}

impl<'a> References<'a> {
    pub(crate) fn new(repository: &'a Repository) -> Result<Self, ReferenceError> {
        Self::from_layout(
            repository.git_dir(),
            repository.common_dir(),
            repository.object_format(),
            repository.reference_backend(),
        )
    }

    pub(crate) fn from_layout(
        git_dir: &'a Path,
        common_dir: &'a Path,
        object_format: ObjectFormat,
        reference_backend: Backend,
    ) -> Result<Self, ReferenceError> {
        if !cfg!(any(unix, windows)) {
            return Err(ReferenceError::Unsupported(
                "reference storage on this platform",
            ));
        }
        Ok(Self {
            git_dir,
            common_dir,
            object_format,
            reference_backend,
            reftable_limits: super::reftable::StackLimits::default(),
        })
    }

    /// Reads a stored direct or symbolic target without following symbolic links.
    ///
    /// Reftable uses the snapshot/publication contract on [`References`]. The files-backend
    /// storage details below do not apply to reftable.
    ///
    /// Returns `None` for an absent name. Packed records are consulted only when the loose file
    /// is absent; per-worktree names never use packed fallback. A directory at the exact name
    /// denotes a namespace conflict, not absence.
    ///
    /// # Errors
    ///
    /// Reports I/O, malformed loose/packed data, unsupported packed traits, and filesystem
    /// symlinks.
    pub fn read(&self, name: &RefName) -> Result<Option<Target>, ReferenceError> {
        Ok(self
            .read_observation(name)?
            .map(|observation| observation.target))
    }

    /// Captures a stored target and its associated storage-provided peeled hint in one read.
    ///
    /// Loose values take precedence and always have no hint, even when they equal a packed
    /// target. Packed target and hint come from the same parsed file record; reftable uses one
    /// winning record from a merged stack snapshot. No symbolic resolution or object read occurs.
    /// The owned result remains unchanged after publication, but is not a lock or a guarantee
    /// about current storage. Use its target as a transaction expectation before acting on it.
    ///
    /// # Errors
    ///
    /// Reports the same errors and preserves loose-before-packed precedence as [`Self::read`].
    ///
    /// ```
    /// use girt::refs::RefName;
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("repo"),
    ///     InitKind::Bare,
    /// )?;
    /// let refs = repo.references()?;
    /// let observation = refs.read_observation(&RefName::new("HEAD")?)?.unwrap();
    /// assert_eq!(observation.peeled_hint, None);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn read_observation(
        &self,
        name: &RefName,
    ) -> Result<Option<ReferenceObservation>, ReferenceError> {
        if self.reference_backend == Backend::Reftable {
            return super::reftable::backend::read_observation(self, name);
        }
        let path = self.path(name)?;
        if let Some(bytes) = read_optional(&path)? {
            let target = parse_loose(self.object_format, &bytes, &path)?;
            return Ok(Some(ReferenceObservation {
                name: name.clone(),
                target,
                peeled_hint: None,
            }));
        }
        if name.per_worktree() {
            return Ok(None);
        }
        Ok(self.packed()?.get(name).map(|record| ReferenceObservation {
            name: name.clone(),
            target: Target::Direct(record.target),
            peeled_hint: record.peeled_hint,
        }))
    }

    /// Follows at most `max_depth` symbolic links and returns the terminal name and identity.
    ///
    /// A missing initial name or dangling/unborn target returns `id: None`; a missing object is
    /// not detected. Zero depth permits a direct or missing ref but no symbolic hop. Reads across
    /// hops are not atomic. This does not peel tags or open objects.
    ///
    /// # Errors
    ///
    /// Reports [`ReferenceError::Cycle`], [`ReferenceError::Depth`], or a [`Self::read`] failure.
    pub fn resolve(&self, name: &RefName, max_depth: usize) -> Result<Resolution, ReferenceError> {
        let mut current = name.clone();
        let mut seen = Vec::new();
        loop {
            if seen.contains(&current) {
                return Err(ReferenceError::Cycle(current));
            }
            seen.push(current.clone());
            match self.read(&current)? {
                Some(Target::Symbolic(next)) => {
                    if seen.len() > max_depth {
                        return Err(ReferenceError::Depth(max_depth));
                    }
                    current = next;
                }
                target => {
                    return Ok(Resolution {
                        name: current,
                        id: direct_id(target),
                    });
                }
            }
        }
    }

    /// Replaces the named reference itself, without dereferencing it or writing reflogs.
    ///
    /// Reftable uses the snapshot/publication contract on [`References`]. The files-backend
    /// storage details below do not apply to reftable.
    ///
    /// `expected` compares its stored target, including any packed value. The new loose file
    /// shadows packed data; packed-refs is never rewritten. Symbolic targets may be dangling or
    /// cyclic, except HEAD itself must point into `refs/`. IDs must be nonzero, but object
    /// existence, type, and fast-forward rules are not
    /// checked. Use [`Self::update_resolved_without_reflog`] to advance a symbolic ref's target.
    ///
    /// This is a low-level publication primitive, **not full `git update-ref` equivalence**.
    /// It ignores `core.logAllRefUpdates`, leaves existing reflogs unchanged, and runs no hooks.
    /// Prior tips gain no new reflog retention or recovery entry; reflog selectors may be stale,
    /// and old objects can become eligible for pruning. Callers must deliberately accept that
    /// behavior. See [`Self::transaction`] for conditional batches with explicit reflog policy.
    ///
    /// Locks `packed-refs.lock`, then `<name>.lock`, using exclusive creation. Checks the
    /// precondition and packed namespace while locked, writes an owned temporary file, and
    /// atomically replaces the destination while retaining the lock. Existing locks are never
    /// overwritten or removed. A failure before rename preserves existing reference bytes;
    /// newly created empty parent directories may remain. Owned lock cleanup is best effort on
    /// errors/unwind; process termination or cleanup I/O failure may leave stale locks. No
    /// file/directory fsync is performed: successful visibility does not promise survival of a
    /// crash or power loss, or durability of objects.
    ///
    /// # Errors
    ///
    /// Reports lock contention, expectation mismatch, namespace conflict (including empty
    /// directories), malformed existing data, unsupported paths, zero IDs, and I/O failures.
    /// No retry is performed. See [`References`] for filesystem/concurrent-writer assumptions.
    pub fn update_without_reflog(
        &self,
        name: &RefName,
        target: Target,
        expected: Expected,
    ) -> Result<(), ReferenceError> {
        let _lock_operation = crate::locks::operation();
        if self.reference_backend == Backend::Reftable {
            return super::reftable::backend::single(self, name, Some(target), expected, false)
                .map(|_| ());
        }
        validate_expected(self.object_format, &expected)?;
        if name.as_bytes() == b"HEAD"
            && matches!(&target, Target::Symbolic(next) if next.as_bytes() == b"HEAD")
        {
            return Err(ReferenceError::InvalidHeadTarget);
        }
        validate_target(self.object_format, &target)?;
        let _packed_lock = Lock::acquire(self.common_dir.join("packed-refs"))?;
        let packed = self.packed()?;
        self.check_packed_namespace(name, &packed)?;
        let mut lock = Lock::acquire(self.path(name)?)?;
        check_expected(self.read_locked(name, &packed)?, expected)?;
        lock.publish(&target)
    }

    /// Advances a terminal direct/missing reference while keeping the symbolic chain unchanged.
    ///
    /// Reftable uses the snapshot/publication contract on [`References`]. The files-backend
    /// storage details below do not apply to reftable.
    ///
    /// Holds `packed-refs.lock` and every visited name's lock through publication, with the same
    /// no-reflog, namespace, cleanup, concurrency and durability contracts as
    /// [`Self::update_without_reflog`]. `expected` applies to the terminal name, so `Absent` can
    /// publish an unborn branch through HEAD. Returns the name that was updated. At most 32
    /// symbolic hops are allowed. Changing a symbolic reference itself requires the other method.
    ///
    /// # Errors
    ///
    /// Reports cycle/depth failures or any error from [`Self::update_without_reflog`]. Acquired
    /// locks are released on failure; no reference is published until the whole chain is locked.
    pub fn update_resolved_without_reflog(
        &self,
        name: &RefName,
        id: ObjectId,
        expected: Expected,
    ) -> Result<RefName, ReferenceError> {
        let _lock_operation = crate::locks::operation();
        if self.reference_backend == Backend::Reftable {
            return super::reftable::backend::single(
                self,
                name,
                Some(Target::Direct(id)),
                expected,
                true,
            )
            .map(|outcome| outcome.name);
        }
        validate_expected(self.object_format, &expected)?;
        let target = Target::Direct(id);
        validate_target(self.object_format, &target)?;
        let _packed_lock = Lock::acquire(self.common_dir.join("packed-refs"))?;
        let packed = self.packed()?;
        let (current, actual, mut locks) = self.lock_resolution(name, &packed)?;
        check_expected(actual, expected)?;
        #[expect(
            clippy::unwrap_used,
            reason = "lock_resolution locks at least the named reference"
        )]
        locks.last_mut().unwrap().publish(&target)?;
        Ok(current)
    }

    /// Deletes the named reference itself, without dereferencing it or changing reflogs.
    ///
    /// Compares `expected` with the stored loose-over-packed target under `packed-refs.lock`
    /// and the name's lock. `Any` and `Absent` permit an already absent name. A symbolic value
    /// is compared and removed as a name; its target is untouched. Use
    /// [`Self::delete_resolved_without_reflog`] to delete the terminal ref instead.
    ///
    /// Removes the packed record and its peel line before unlinking the loose file, so deletion
    /// cannot uncover an older packed value. Unrelated packed bytes (including header traits,
    /// order and peel records) are preserved. A separate temporary file publishes packed data
    /// while the packed lock remains held through loose deletion. Both locks are held until
    /// completion. Empty parent directories and existing reflogs remain; hooks are not run.
    /// The no-reflog and filesystem assumptions of [`Self::update_without_reflog`] apply.
    ///
    /// Reads remain live: a reader with previously read packed data can observe a stale value.
    /// This is not a snapshot, multi-ref transaction, or crash-durable operation. A subsequent
    /// writer can recreate the name after locks are released.
    ///
    /// # Errors
    ///
    /// Lock, namespace, malformed-data and expectation failures preserve reference bytes.
    /// Lock acquisition may leave empty parent directories. Packed publication failure preserves
    /// both values. If packed publication succeeds but loose removal fails, returns
    /// [`ReferenceError::PackedDeleted`]: the loose value remains, with no rollback of packed
    /// storage. Other I/O failures use [`ReferenceError::Io`]. Lock/temporary cleanup is best
    /// effort, including after success; cleanup failure or termination can leave stale files.
    /// No fsync, retries, reflog cleanup, or object deletion is performed.
    pub fn delete_without_reflog(
        &self,
        name: &RefName,
        expected: Expected,
    ) -> Result<(), ReferenceError> {
        let _lock_operation = crate::locks::operation();
        if self.reference_backend == Backend::Reftable {
            return super::reftable::backend::single(self, name, None, expected, false).map(|_| ());
        }
        validate_expected(self.object_format, &expected)?;
        let packed_lock = Lock::acquire(self.common_dir.join("packed-refs"))?;
        let bytes = read_optional(&packed_lock.destination)?.unwrap_or_default();
        let packed = packed::parse(self.object_format, &bytes, &packed_lock.destination)?;
        self.check_packed_namespace(name, &packed)?;
        let lock = Lock::acquire(self.path(name)?)?;
        check_expected(self.read_locked(name, &packed)?, expected)?;
        delete_locked(
            self.object_format,
            &packed_lock,
            &lock,
            name,
            &bytes,
            &packed,
        )
    }

    /// Deletes the terminal direct/missing ref while preserving every symbolic name in its chain.
    ///
    /// `expected` applies to the terminal stored value. Holds the packed lock and every visited
    /// name's lock through deletion; at most 32 symbolic hops are allowed. Returns the terminal
    /// name, including when already absent. Deleting a branch through HEAD leaves HEAD unborn;
    /// deleting through an alias leaves the alias dangling.
    ///
    /// # Errors
    ///
    /// Reports cycle/depth failures or errors from [`Self::delete_without_reflog`], with the same
    /// packed-first ordering, partial-failure, cleanup, live-reader and no-reflog contracts.
    pub fn delete_resolved_without_reflog(
        &self,
        name: &RefName,
        expected: Expected,
    ) -> Result<RefName, ReferenceError> {
        let _lock_operation = crate::locks::operation();
        if self.reference_backend == Backend::Reftable {
            return super::reftable::backend::single(self, name, None, expected, true)
                .map(|outcome| outcome.name);
        }
        validate_expected(self.object_format, &expected)?;
        let packed_lock = Lock::acquire(self.common_dir.join("packed-refs"))?;
        let bytes = read_optional(&packed_lock.destination)?.unwrap_or_default();
        let packed = packed::parse(self.object_format, &bytes, &packed_lock.destination)?;
        let (current, actual, locks) = self.lock_resolution(name, &packed)?;
        check_expected(actual, expected)?;
        #[expect(
            clippy::unwrap_used,
            reason = "lock_resolution locks at least the named reference"
        )]
        delete_locked(
            self.object_format,
            &packed_lock,
            locks.last().unwrap(),
            &current,
            &bytes,
            &packed,
        )?;
        Ok(current)
    }

    fn lock_resolution(
        &self,
        name: &RefName,
        packed: &packed::Packed,
    ) -> Result<(RefName, Option<Target>, Vec<Lock>), ReferenceError> {
        let mut current = name.clone();
        let mut seen = Vec::new();
        let mut locks = Vec::new();
        loop {
            if seen.contains(&current) {
                return Err(ReferenceError::Cycle(current));
            }
            seen.push(current.clone());
            self.check_packed_namespace(&current, packed)?;
            locks.push(Lock::acquire(self.path(&current)?)?);
            match self.read_locked(&current, packed)? {
                Some(Target::Symbolic(next)) => {
                    if seen.len() > 32 {
                        return Err(ReferenceError::Depth(32));
                    }
                    current = next;
                }
                actual => return Ok((current, actual, locks)),
            }
        }
    }

    pub(super) fn read_locked(
        &self,
        name: &RefName,
        packed: &packed::Packed,
    ) -> Result<Option<Target>, ReferenceError> {
        let path = self.path(name)?;
        if let Some(bytes) = read_optional(&path)? {
            return parse_loose(self.object_format, &bytes, &path).map(Some);
        }
        Ok(packed
            .get(name)
            .filter(|_| !name.per_worktree())
            .map(|record| Target::Direct(record.target)))
    }

    pub(super) fn packed(&self) -> Result<packed::Packed, ReferenceError> {
        let path = self.common_dir.join("packed-refs");
        let bytes = read_optional(&path)?.unwrap_or_default();
        packed::parse(self.object_format, &bytes, &path)
    }

    pub(super) fn path(&self, name: &RefName) -> Result<PathBuf, ReferenceError> {
        let base = if name.per_worktree() {
            self.git_dir
        } else {
            self.common_dir
        };
        #[cfg(unix)]
        let relative = {
            use std::os::unix::ffi::OsStrExt;
            std::ffi::OsStr::from_bytes(name.as_bytes())
        };
        #[cfg(not(unix))]
        let relative = std::ffi::OsStr::new(
            std::str::from_utf8(name.as_bytes())
                .map_err(|_| ReferenceError::Unsupported("non-UTF-8 filesystem name"))?,
        );
        #[cfg(windows)]
        for part in name.as_bytes().split(|b| *b == b'/') {
            let stem = part
                .split(|b| *b == b'.')
                .next()
                .unwrap_or_default()
                .to_ascii_uppercase();
            if part.ends_with(b".")
                || part.iter().any(|b| b"<>\"|".contains(b))
                || matches!(
                    stem.as_slice(),
                    b"CON"
                        | b"PRN"
                        | b"AUX"
                        | b"NUL"
                        | [b'C', b'O', b'M', b'1'..=b'9']
                        | [b'L', b'P', b'T', b'1'..=b'9']
                )
            {
                return Err(ReferenceError::Unsupported("Windows reference filename"));
            }
        }
        Ok(base.join(relative))
    }

    pub(super) fn check_packed_namespace(
        &self,
        name: &RefName,
        packed: &packed::Packed,
    ) -> Result<(), ReferenceError> {
        if !name.per_worktree()
            && packed
                .keys()
                .any(|other| conflicts(name.as_bytes(), other.as_bytes()))
        {
            return Err(ReferenceError::Conflict(self.path(name)?));
        }
        Ok(())
    }
}

// Publish packed removal while the loose value still masks the old packed value. Keeping the
// packed lock separate from the replacement file excludes packed writers through both steps.
fn delete_locked(
    format: crate::ObjectFormat,
    packed_lock: &Lock,
    loose_lock: &Lock,
    name: &RefName,
    bytes: &[u8],
    packed: &packed::Packed,
) -> Result<(), ReferenceError> {
    let packed_changed = packed.contains_key(name);
    if packed_changed {
        let replacement = packed::without_ref(format, bytes, name);
        packed_lock.publish_retaining_lock(&replacement)?;
    }
    remove_loose(&loose_lock.destination, packed_changed)
}

pub(super) fn remove_loose(path: &Path, packed_changed: bool) -> Result<(), ReferenceError> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(source) if packed_changed => Err(ReferenceError::PackedDeleted {
            path: path.into(),
            source,
        }),
        Err(source) => Err(io_error(path, source)),
    }
}

pub(super) fn conflicts(a: &[u8], b: &[u8]) -> bool {
    a.strip_prefix(b).is_some_and(|rest| rest.starts_with(b"/"))
        || b.strip_prefix(a).is_some_and(|rest| rest.starts_with(b"/"))
}
fn direct_id(target: Option<Target>) -> Option<ObjectId> {
    match target {
        Some(Target::Direct(id)) => Some(id),
        _ => None,
    }
}
pub(super) fn validate_target(
    format: crate::ObjectFormat,
    target: &Target,
) -> Result<(), ReferenceError> {
    if let Target::Direct(id) = target {
        id.require_format(format)?;
    }
    if matches!(target, Target::Direct(id) if id.is_null()) {
        return Err(ReferenceError::ZeroId);
    }
    Ok(())
}
pub(super) fn validate_expected(
    format: crate::ObjectFormat,
    expected: &Expected,
) -> Result<(), ReferenceError> {
    if let Expected::Value(Target::Direct(id)) | Expected::AbsentOr(Target::Direct(id)) = expected {
        id.require_format(format)?;
    }
    Ok(())
}
pub(super) fn check_expected(
    actual: Option<Target>,
    expected: Expected,
) -> Result<(), ReferenceError> {
    let matches = match expected {
        Expected::Any => true,
        Expected::Absent => actual.is_none(),
        Expected::Value(value) => actual.as_ref() == Some(&value),
        Expected::Exists => actual.is_some(),
        Expected::AbsentOr(value) => actual.is_none() || actual.as_ref() == Some(&value),
    };
    if !matches {
        return Err(ReferenceError::Mismatch { actual });
    }
    Ok(())
}

pub(super) fn parse_loose(
    format: crate::ObjectFormat,
    bytes: &[u8],
    path: &Path,
) -> Result<Target, ReferenceError> {
    // Git accepts trailing ASCII whitespace, including no final newline.
    let bytes = bytes.trim_ascii_end();
    if let Some(name) = bytes.strip_prefix(b"ref: ") {
        let name = RefName::new(name).map_err(|_| malformed(path, "invalid symbolic target"))?;
        return Ok(Target::Symbolic(name));
    }
    packed::parse_id(format, bytes, path).map(Target::Direct)
}

pub(super) fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, ReferenceError> {
    check_path(path)?;
    match fs::read(path) {
        Ok(bytes) => Ok(Some(bytes)),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(source) => Err(io_error(path, source)),
    }
}

// The opened roots are canonical. Refuse symlink traversal below them, and symlink files.
// This is a trusted-directory check, not a race-proof sandbox against malicious path swaps.
pub(super) fn check_path(path: &Path) -> Result<(), ReferenceError> {
    for ancestor in path.ancestors() {
        match fs::symlink_metadata(ancestor) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(ReferenceError::Unsupported(
                    "filesystem symlink in reference path",
                ));
            }
            Ok(metadata) if ancestor != path && !metadata.is_dir() => {
                return Err(ReferenceError::Conflict(ancestor.into()));
            }
            Ok(metadata) if ancestor == path && metadata.is_dir() => {
                return Err(ReferenceError::Conflict(path.into()));
            }
            Ok(metadata) if ancestor == path && !metadata.is_file() => {
                return Err(ReferenceError::Unsupported("non-regular reference file"));
            }
            Ok(_) => (),
            Err(error)
                if error.kind() == io::ErrorKind::NotFound
                    || error.kind() == io::ErrorKind::NotADirectory => {}
            Err(source) => return Err(io_error(ancestor, source)),
        }
    }
    Ok(())
}

pub(super) struct Lock {
    pub(super) destination: PathBuf,
    path: PathBuf,
    file: Option<crate::locks::SharedFile>,
    identity: fs::Metadata,
    cleanup: crate::locks::Guard,
}
impl Lock {
    pub(super) fn acquire(destination: PathBuf) -> Result<Self, ReferenceError> {
        let _lock_operation = crate::locks::operation();
        let destination =
            std::path::absolute(&destination).map_err(|source| io_error(&destination, source))?;
        check_path(&destination)?;
        #[expect(
            clippy::unwrap_used,
            reason = "callers join validated names or fixed file names onto repository roots"
        )]
        let parent = destination.parent().unwrap();
        fs::create_dir_all(parent).map_err(|source| io_error(parent, source))?;
        let mut path = destination.as_os_str().to_os_string();
        path.push(".lock");
        let path = PathBuf::from(path);
        let mut options = OpenOptions::new();
        options.write(true).create_new(true);
        // Keep the owned Windows lock unreplaceable while its handle is open. Publication
        // uses a separate temporary file, so no delete sharing is needed on this handle.
        #[cfg(windows)]
        {
            use std::os::windows::fs::OpenOptionsExt;
            options.share_mode(3); // FILE_SHARE_READ | FILE_SHARE_WRITE, excluding DELETE.
        }
        let file = options.open(&path).map_err(|source| {
            if is_held(&source) {
                ReferenceError::Locked(path.clone())
            } else {
                io_error(&path, source)
            }
        })?;
        let identity = crate::locks::capture_identity(&path, &file)
            .map_err(|source| io_error(&path, source))?;
        let file = crate::locks::SharedFile::from(file);
        let cleanup = crate::locks::Guard::new(&path, &file, identity.clone());
        Ok(Self {
            destination,
            cleanup,
            path: path.clone(),
            identity,
            file: Some(file),
        })
    }
    pub(super) fn check_owned(&self) -> Result<(), ReferenceError> {
        self.cleanup
            .check()
            .map_err(|source| io_error(&self.path, source))?;
        let current =
            fs::symlink_metadata(&self.path).map_err(|source| io_error(&self.path, source))?;
        if !current.is_file() || current.file_type().is_symlink() {
            return Err(ReferenceError::Locked(self.path.clone()));
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            if current.dev() != self.identity.dev() || current.ino() != self.identity.ino() {
                return Err(ReferenceError::Locked(self.path.clone()));
            }
        }
        Ok(())
    }

    pub(super) fn publish_retaining_lock(&self, bytes: &[u8]) -> Result<(), ReferenceError> {
        self.publish_replacement(bytes, false)
    }

    /// Publishes like [`Self::publish_retaining_lock`], syncing the file before the rename.
    ///
    /// The rename itself is durable only after [`sync_directory`] on the destination's parent.
    pub(super) fn publish_synced(&self, bytes: &[u8]) -> Result<(), ReferenceError> {
        self.publish_replacement(bytes, true)
    }

    fn publish_replacement(&self, bytes: &[u8], sync: bool) -> Result<(), ReferenceError> {
        let _lock_operation = crate::locks::operation();
        self.check_owned()?;
        #[expect(clippy::unwrap_used, reason = "lock destinations lie below a root")]
        let parent = self.destination.parent().unwrap();
        let mut temporary = tempfile::Builder::new()
            .prefix(".girt-packed-")
            .tempfile_in(parent)
            .map_err(|source| io_error(parent, source))?;
        // Match ordinary lock creation permissions, including the process umask.
        let permissions = self.identity.permissions();
        temporary
            .as_file()
            .set_permissions(permissions)
            .map_err(|source| io_error(temporary.path(), source))?;
        temporary
            .write_all(bytes)
            .map_err(|source| io_error(temporary.path(), source))?;
        if sync {
            temporary
                .as_file()
                .sync_all()
                .map_err(|source| io_error(temporary.path(), source))?;
        }
        self.check_owned()?;
        temporary
            .persist(&self.destination)
            .map_err(|error| io_error(&self.destination, error.error))?;
        Ok(())
    }

    fn publish(&mut self, target: &Target) -> Result<(), ReferenceError> {
        let mut bytes = match target {
            Target::Direct(id) => id.to_string().into_bytes(),
            Target::Symbolic(name) => {
                let mut bytes = b"ref: ".to_vec();
                bytes.extend_from_slice(name.as_bytes());
                bytes
            }
        };
        bytes.push(b'\n');
        #[expect(clippy::unwrap_used, reason = "an unpublished lock holds its file")]
        self.file
            .as_mut()
            .unwrap()
            .write_all(&bytes)
            .map_err(|source| io_error(&self.path, source))?;
        self.publish_retaining_lock(&bytes)
    }
}
impl Drop for Lock {
    fn drop(&mut self) {
        let _lock_operation = crate::locks::operation();
        if self.check_owned().is_ok() {
            drop(self.file.take());
            let _ = fs::remove_file(&self.path);
        }
    }
}
/// Makes completed renames in `directory` durable. Unix only: other platforms have no
/// established directory barrier here, so callers must not retire data that depends on one.
#[cfg(unix)]
pub(super) fn sync_directory(directory: &Path) -> Result<(), ReferenceError> {
    fs::File::open(directory)
        .and_then(|directory| directory.sync_all())
        .map_err(|source| io_error(directory, source))
}

pub(super) fn io_error(path: &Path, source: io::Error) -> ReferenceError {
    ReferenceError::Io {
        path: path.into(),
        source,
    }
}
pub(super) fn malformed(path: &Path, reason: &'static str) -> ReferenceError {
    ReferenceError::Malformed {
        path: path.into(),
        reason,
    }
}

/// Whether creating a lock file failed because another writer holds or is releasing it.
///
/// Windows reports a lock file that is still being deleted as access denied rather than as
/// existing, so a writer that just released its lock can't be told apart from a held one.
fn is_held(error: &io::Error) -> bool {
    error.kind() == io::ErrorKind::AlreadyExists
        || (cfg!(windows) && error.kind() == io::ErrorKind::PermissionDenied)
}

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

    use super::*;

    fn fixture() -> (tempfile::TempDir, Repository) {
        let temp = tempfile::tempdir().unwrap();
        fs::create_dir(temp.path().join("objects")).unwrap();
        fs::create_dir(temp.path().join("refs")).unwrap();
        fs::write(temp.path().join("HEAD"), b"ref: refs/heads/main\n").unwrap();
        let repository = Repository::open(temp.path()).unwrap();
        (temp, repository)
    }
    fn name(value: &[u8]) -> RefName {
        RefName::new(value).unwrap()
    }
    fn id() -> ObjectId {
        ObjectId::Sha1([1; 20])
    }

    #[rstest]
    #[case::no_newline(b"1111111111111111111111111111111111111111")]
    #[case::trailing_space(b"1111111111111111111111111111111111111111 \r\n\t")]
    fn parses_loose_ids(#[case] bytes: &[u8]) {
        assert_eq!(
            parse_loose(crate::ObjectFormat::Sha1, bytes, Path::new("ref")).unwrap(),
            Target::Direct(ObjectId::Sha1([0x11; 20]))
        );
    }

    #[rstest]
    #[case::empty(b"")]
    #[case::garbage(b"garbage\n")]
    #[case::zero(b"0000000000000000000000000000000000000000\n")]
    #[case::sha256(b"1111111111111111111111111111111111111111111111111111111111111111\n")]
    #[case::bad_symbol(b"ref: refs/../main\n")]
    #[case::extra_line(b"1111111111111111111111111111111111111111\nextra\n")]
    fn rejects_loose_data(#[case] bytes: &[u8]) {
        assert!(matches!(
            parse_loose(crate::ObjectFormat::Sha1, bytes, Path::new("ref")),
            Err(ReferenceError::Malformed { .. })
        ));
    }

    #[test]
    fn unborn_resolution_identifies_missing_terminal() {
        let (_temp, repo) = fixture();
        let refs = repo.references().unwrap();
        assert_eq!(
            refs.resolve(&name(b"HEAD"), 1).unwrap(),
            Resolution {
                name: name(b"refs/heads/main"),
                id: None
            }
        );
        assert!(matches!(
            refs.resolve(&name(b"HEAD"), 0),
            Err(ReferenceError::Depth(0))
        ));
        assert_eq!(refs.resolve(&name(b"refs/absent"), 0).unwrap().id, None);
    }

    #[test]
    fn cycle_failure_cleans_all_owned_locks() {
        let (_temp, repo) = fixture();
        let refs = repo.references().unwrap();
        refs.update_without_reflog(
            &name(b"refs/heads/main"),
            Target::Symbolic(name(b"HEAD")),
            Expected::Absent,
        )
        .unwrap();
        assert!(matches!(
            refs.resolve(&name(b"HEAD"), 32),
            Err(ReferenceError::Cycle(_))
        ));
        assert!(matches!(
            refs.update_resolved_without_reflog(&name(b"HEAD"), id(), Expected::Any),
            Err(ReferenceError::Cycle(_))
        ));
        assert!(!repo.git_dir().join("HEAD.lock").exists());
        assert!(!repo.git_dir().join("refs/heads/main.lock").exists());
        assert!(!repo.common_dir().join("packed-refs.lock").exists());
    }

    #[test]
    fn mismatch_preserves_bytes_and_cleans_locks() {
        let (_temp, repo) = fixture();
        let refs = repo.references().unwrap();
        let before = fs::read(repo.git_dir().join("HEAD")).unwrap();
        assert!(matches!(
            refs.update_without_reflog(&name(b"HEAD"), Target::Direct(id()), Expected::Absent),
            Err(ReferenceError::Mismatch { .. })
        ));
        assert_eq!(fs::read(repo.git_dir().join("HEAD")).unwrap(), before);
        assert!(!repo.git_dir().join("HEAD.lock").exists());
        assert!(!repo.common_dir().join("packed-refs.lock").exists());
    }

    #[rstest]
    #[case::reference("HEAD.lock")]
    #[case::packed("packed-refs.lock")]
    fn never_steals_existing_lock(#[case] lock_name: &str) {
        let (_temp, repo) = fixture();
        let lock_path = repo.git_dir().join(lock_name);
        fs::write(&lock_path, b"another writer").unwrap();
        assert!(matches!(
            repo.references().unwrap().update_without_reflog(
                &name(b"HEAD"),
                Target::Direct(id()),
                Expected::Any
            ),
            Err(ReferenceError::Locked(_))
        ));
        assert_eq!(fs::read(lock_path).unwrap(), b"another writer");
        assert_eq!(
            fs::read(repo.git_dir().join("HEAD")).unwrap(),
            b"ref: refs/heads/main\n"
        );
    }

    #[test]
    fn write_failure_preserves_destination_and_releases_lock() {
        let (_temp, repo) = fixture();
        let path = repo.git_dir().join("HEAD");
        let mut lock = Lock::acquire(path.clone()).unwrap();
        // A read-only handle injects a deterministic write failure without chmod/root assumptions.
        lock.file = Some(fs::File::open(&lock.path).unwrap().into());
        assert!(lock.publish(&Target::Direct(id())).is_err());
        drop(lock);
        assert_eq!(fs::read(path).unwrap(), b"ref: refs/heads/main\n");
        assert!(!repo.git_dir().join("HEAD.lock").exists());
    }

    #[test]
    fn failed_rename_preserves_unrelated_data() {
        let (_temp, repo) = fixture();
        let path = repo.git_dir().join("refs/new");
        let mut lock = Lock::acquire(path.clone()).unwrap();
        fs::create_dir(&path).unwrap();
        fs::write(path.join("unrelated"), b"keep").unwrap();
        assert!(lock.publish(&Target::Direct(id())).is_err());
        drop(lock);
        assert_eq!(fs::read(path.join("unrelated")).unwrap(), b"keep");
        assert!(!repo.git_dir().join("refs/new.lock").exists());
    }

    #[test]
    fn zero_id_has_no_side_effects() {
        let (_temp, repo) = fixture();
        assert!(matches!(
            repo.references().unwrap().update_without_reflog(
                &name(b"refs/new/deep"),
                Target::Direct(ObjectId::Sha1([0; 20])),
                Expected::Any
            ),
            Err(ReferenceError::ZeroId)
        ));
        assert!(!repo.git_dir().join("refs/new").exists());
        assert!(!repo.common_dir().join("packed-refs.lock").exists());
    }

    #[cfg(unix)]
    #[rstest]
    #[case::directory("refs/link", "refs/link/a")]
    #[case::file("refs/link", "refs/link")]
    fn rejects_symlinks_without_touching_target(#[case] link: &str, #[case] reference: &str) {
        let (temp, repo) = fixture();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("a"), b"keep").unwrap();
        std::os::unix::fs::symlink(outside.path(), temp.path().join(link)).unwrap();
        let refs = repo.references().unwrap();
        assert!(matches!(
            refs.read(&name(reference.as_bytes())),
            Err(ReferenceError::Unsupported(_))
        ));
        assert!(matches!(
            refs.update_without_reflog(
                &name(reference.as_bytes()),
                Target::Direct(id()),
                Expected::Any
            ),
            Err(ReferenceError::Unsupported(_))
        ));
        assert_eq!(fs::read(outside.path().join("a")).unwrap(), b"keep");
    }
}

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

    // Independently encode a chain to exercise the update depth limit and every owned lock.
    fn chain(root: &Path, hops: usize) {
        fs::create_dir_all(root.join("objects")).unwrap();
        fs::create_dir_all(root.join("refs/heads")).unwrap();
        fs::write(root.join("HEAD"), b"ref: refs/heads/0\n").unwrap();
        for index in 0..hops {
            fs::write(
                root.join(format!("refs/heads/{index}")),
                format!("ref: refs/heads/{}\n", index + 1),
            )
            .unwrap();
        }
    }

    #[test]
    fn depth_failure_releases_chain_locks() {
        let root = tempfile::tempdir().unwrap();
        chain(root.path(), 33);
        let repo = Repository::open(root.path()).unwrap();
        let refs = repo.references().unwrap();
        let head = RefName::new(b"HEAD").unwrap();
        assert!(matches!(
            refs.update_resolved_without_reflog(&head, ObjectId::Sha1([1; 20]), Expected::Absent),
            Err(ReferenceError::Depth(32))
        ));
        assert_eq!(refs.resolve(&head, 34).unwrap().id, None);
        assert_eq!(
            fs::read_dir(root.path().join("refs/heads"))
                .unwrap()
                .count(),
            33
        );
        assert!(!root.path().join("HEAD.lock").exists());
        assert!(!root.path().join("packed-refs.lock").exists());
    }

    #[test]
    fn deletion_depth_failure_preserves_chain() {
        let root = tempfile::tempdir().unwrap();
        chain(root.path(), 33);
        let repo = Repository::open(root.path()).unwrap();
        assert!(matches!(
            repo.references()
                .unwrap()
                .delete_resolved_without_reflog(&RefName::new(b"HEAD").unwrap(), Expected::Any),
            Err(ReferenceError::Depth(32))
        ));
        assert_eq!(
            fs::read_dir(root.path().join("refs/heads"))
                .unwrap()
                .count(),
            33
        );
        assert!(!root.path().join("HEAD.lock").exists());
        assert!(!root.path().join("packed-refs.lock").exists());
    }

    #[test]
    fn locked_terminal_preserves_symbolic_chain() {
        let root = tempfile::tempdir().unwrap();
        chain(root.path(), 1);
        fs::write(root.path().join("refs/heads/1.lock"), b"owner").unwrap();
        let repo = Repository::open(root.path()).unwrap();
        let head = RefName::new(b"HEAD").unwrap();
        assert!(matches!(
            repo.references().unwrap().update_resolved_without_reflog(
                &head,
                ObjectId::Sha1([1; 20]),
                Expected::Absent
            ),
            Err(ReferenceError::Locked(_))
        ));
        assert_eq!(
            fs::read(root.path().join("refs/heads/0")).unwrap(),
            b"ref: refs/heads/1\n"
        );
        assert_eq!(
            fs::read(root.path().join("refs/heads/1.lock")).unwrap(),
            b"owner"
        );
        assert!(!root.path().join("HEAD.lock").exists());
        assert!(!root.path().join("refs/heads/0.lock").exists());
        assert!(!root.path().join("packed-refs.lock").exists());
    }
}

#[cfg(test)]
#[path = "delete_tests.rs"]
mod delete_tests;

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

    #[cfg(unix)]
    #[test]
    fn replaced_lock_is_neither_published_nor_removed() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().canonicalize().unwrap().join("ref");
        fs::write(&path, b"old").unwrap();
        let lock = Lock::acquire(path.clone()).unwrap();
        fs::remove_file(&lock.path).unwrap();
        fs::write(&lock.path, b"replacement owner").unwrap();
        assert!(matches!(
            lock.publish_retaining_lock(b"new"),
            Err(ReferenceError::Locked(_))
        ));
        let lock_path = lock.path.clone();
        drop(lock);
        assert_eq!(fs::read(path).unwrap(), b"old");
        assert_eq!(fs::read(lock_path).unwrap(), b"replacement owner");
    }

    #[cfg(windows)]
    #[test]
    fn windows_lock_disallows_replacement_until_release() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().canonicalize().unwrap().join("ref");
        let lock = Lock::acquire(path.clone()).unwrap();
        assert!(fs::remove_file(&lock.path).is_err());
        let replacement = root.path().join("replacement");
        fs::write(&replacement, b"foreign").unwrap();
        assert!(fs::rename(&replacement, &lock.path).is_err());
        lock.publish_retaining_lock(b"new").unwrap();
        let lock_path = lock.path.clone();
        drop(lock);
        assert!(!lock_path.exists());
        assert_eq!(fs::read(path).unwrap(), b"new");
        assert_eq!(fs::read(replacement).unwrap(), b"foreign");
    }
}

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

    // Invoked in a child test process so exit bypasses guard destructors without terminating
    // the test runner. No signal handler or other process-global policy is installed.
    #[test]
    fn child_exits_with_owned_lock() {
        let Some(root) = std::env::var_os("GIRT_R11_EXIT_LOCK_ROOT") else {
            return;
        };
        let _lock = Lock::acquire(PathBuf::from(root).join("ref")).unwrap();
        std::process::exit(0);
    }

    #[test]
    fn termination_leaves_a_stale_lock_for_explicit_recovery() {
        let root = tempfile::tempdir().unwrap();
        let directory = root.path().canonicalize().unwrap();
        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "refs::store::termination_tests::child_exits_with_owned_lock",
            ])
            .env("GIRT_R11_EXIT_LOCK_ROOT", &directory)
            .status()
            .unwrap();
        assert!(status.success());
        assert!(directory.join("ref.lock").exists());
        assert!(matches!(
            Lock::acquire(directory.join("ref")),
            Err(ReferenceError::Locked(_))
        ));
        // The caller now knows this specific child has exited. Only it can authorize removing
        // that stale lock; the storage API never steals it speculatively.
        fs::remove_file(directory.join("ref.lock")).unwrap();
        let lock = Lock::acquire(directory.join("ref")).unwrap();
        lock.publish_retaining_lock(b"recovered").unwrap();
        drop(lock);
        assert_eq!(fs::read(directory.join("ref")).unwrap(), b"recovered");
        assert!(!directory.join("ref.lock").exists());
    }
}

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

    #[test]
    fn cleanup_covers_reference_lock_topologies_without_changing_destinations() {
        let root = tempfile::tempdir().unwrap();
        let directory = root.path().canonicalize().unwrap();
        for name in [
            "refs/heads/main",
            "logs/refs/heads/main",
            "packed-refs",
            "reftable/tables.list",
        ] {
            let destination = directory.join(name);
            fs::create_dir_all(destination.parent().unwrap()).unwrap();
            fs::write(&destination, b"published bytes").unwrap();
            let lock = Lock::acquire(destination.clone()).unwrap();
            let report = crate::locks::cleanup_under(&directory).unwrap();
            #[cfg(unix)]
            assert_eq!(report.removed.len(), 1);
            #[cfg(not(unix))]
            assert_eq!(report.failures.len(), 1);
            #[cfg(unix)]
            assert!(lock.publish_retaining_lock(b"unsafe replacement").is_err());
            #[cfg(not(unix))]
            assert!(lock.check_owned().is_ok());
            assert_eq!(fs::read(destination).unwrap(), b"published bytes");
            #[cfg(not(unix))]
            {
                let path = lock.path.clone();
                drop(lock);
                assert!(
                    !path.exists(),
                    "unsupported cleanup must preserve ordinary Drop"
                );
            }
        }
    }
}