girt 0.14.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
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
//! Repository discovery, explicit opening, and creation.
//!
//! Start with [`Repository::open`] when the application already has a repository path. Use
//! [`Repository::discover`] for a user-selected directory that may be below the repository root.
//! Use [`RepositoryLocation::at_git_dir`] when a caller has selected the exact metadata directory
//! and needs to apply trust policy before opening it. None of these reads ambient Git environment
//! variables; supply inherited configuration explicitly through [`ConfigInputs`].
//! [`Repository::discover_with_config`] with [`ConfigInputs::git_default`] sees the configuration
//! `git` would.
//! For trusted local use with Git defaults, lazy loading, and default limits, start with
//! [`crate::Repo`] instead. `Repository` keeps limits, cancellation, and configuration under caller
//! control when handling untrusted input or implementing a custom policy.
//!
//! # Layout and lifetime
//!
//! An ordinary checkout has a working directory and `.git` metadata; a bare repository has only
//! metadata. Linked worktrees share a [`Repository::common_dir`] and object database while
//! retaining private [`Repository::git_dir`] metadata. Use these accessors instead of appending
//! `.git` to a path. [`Repository::worktree`] returns `None` for bare repositories.
//!
//! A handle retains metadata, configuration, and shallow roots read at opening. It is not a lock
//! or a complete validation of stored objects. Reopen to refresh metadata; open an
//! [`Objects`](crate::Objects) reader separately to retain a pack snapshot. Loose objects and
//! reference reads have their own visibility rules.
//!
//! # Find a repository from a nested directory
//!
//! ```
//! use girt::{InitKind, ObjectFormat, Repository};
//!
//! let directory = tempfile::tempdir()?;
//! let path = directory.path().join("project");
//! let created = Repository::init(ObjectFormat::Sha1, &path, InitKind::Worktree)?;
//! let nested = path.join("src");
//! std::fs::create_dir(&nested)?;
//! let found = Repository::discover_with_ceiling(&nested, &path)?;
//! assert_eq!(found.git_dir(), created.git_dir());
//! assert_eq!(found.object_format(), ObjectFormat::Sha1);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! Discovery follows physical ancestors after canonicalizing paths. A ceiling bounds where
//! candidates are searched, but indirections in metadata can point outside it. A recognized
//! malformed or unsupported candidate stops discovery so it cannot silently select an outer
//! repository. Use a ceiling to avoid searching unrelated ancestors, not as filesystem isolation.
//!
//! # Creating and diagnosing repositories
//!
//! [`Repository::init`] creates an unborn `main`; [`InitOptions`] allows a chosen branch, format,
//! and reference backend. `init_with_options` uses `master` unless the options select another
//! branch; this differs from the `main` chosen by the simpler `init` entry point. Initialization
//! refuses existing metadata. If a later write fails, partial newly created metadata can remain:
//! inspect it before retrying rather than treating initialization as rollback-safe.
//!
//! [`OpenError::NotFound`] means the selected path or discovery range has no usable candidate.
//! [`OpenError::Malformed`] identifies inconsistent metadata; inspect the reported path and reason.
//! [`OpenError::Unsupported`] requires choosing a supported feature or extending support, rather
//! than bypassing validation. Configuration errors retain their source; correct that source before
//! reopening. Opening writes nothing and does not repair a repository.
mod colocation;
mod command_layout;
mod discover;
mod init;
mod object_values;
mod operation;
mod reflog_policy;
mod shallow;
mod worktree_admin;
mod worktree_create;
mod worktree_repair;
mod worktrees;
use std::path::{Path, PathBuf};
use std::{fs, io};

pub use colocation::{ColocationEdit, ColocationError};
pub use init::{InitError, InitKind, InitOptions};
pub(crate) use init::{initial_branch, initial_config};
pub use operation::{OperationCleanupError, OperationError, OperationLimits, OperationState};
pub use reflog_policy::ReflogPolicyError;
pub use shallow::{ShallowError, ShallowRoots};
use thiserror::Error;
pub use worktree_admin::{WorktreeAdminError, WorktreeRetirement};
pub use worktree_create::{CreateWorktreeError, OrphanWorktreeOptions, WorktreeDurability};
pub use worktree_repair::WorktreeRepair;
pub use worktrees::{Worktree, WorktreeError, WorktreeState};

/// Link spelling for one worktree creation or repair operation.
///
/// An explicit choice affects only the links written by that operation. It does not edit
/// `extensions.relativeWorktrees` or change the default of later operations.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum WorktreeLinkStyle {
    /// Follow the repository's direct `extensions.relativeWorktrees` setting.
    #[default]
    Configured,
    /// Write relative forward and back links when both paths share a filesystem root.
    Relative,
    /// Write absolute forward and back links.
    Absolute,
}

impl WorktreeLinkStyle {
    fn uses_relative(self, configured: bool) -> bool {
        match self {
            Self::Configured => configured,
            Self::Relative => true,
            Self::Absolute => false,
        }
    }
}

use crate::config::{
    ConfigFile, ConfigInputs, ConfigScope, IncludePlacement, ResolveError,
    boolean as config_boolean, integer,
};
use crate::{Config, ConfigError, LooseObjects, ObjectFormat};

/// An explicitly selected Git metadata location before configuration or trust policy is applied.
///
/// Location resolves filesystem indirections only. It does not establish that the repository is
/// trusted or usable, and does not freeze filesystem identity against concurrent replacement.
/// Opening later reads current metadata at these paths, without selecting another repository.
///
/// Choose this phase when a caller must approve a selected filesystem location before configuration
/// is read. Resolving a location does not approve its owner or freeze path identity against
/// replacement.
///
/// ```
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("r.git");
/// let repo = Repository::init(ObjectFormat::Sha1, &path, InitKind::Bare)?;
/// let location = girt::RepositoryLocation::at_git_dir(repo.git_dir())?;
/// let metadata = location.read_metadata_with_config(&girt::config::ConfigInputs::default())?;
/// assert_eq!(metadata.git_dir(), location.git_dir());
/// assert!(metadata.is_bare());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RepositoryLocation {
    git_dir: PathBuf,
    common_dir: PathBuf,
    object_dir: Option<PathBuf>,
    common_dir_redirected: bool,
    logical_git_dir: Option<PathBuf>,
    inferred_worktree: Option<PathBuf>,
}

impl RepositoryLocation {
    /// Resolves exactly the supplied Git directory or `gitdir:` file.
    ///
    /// Never searches ancestors or descends into `.git`. Reads only filesystem structure and
    /// gitfile/`commondir` indirections; configuration, HEAD, references, shallow roots and object
    /// storage are not read or validated. Relative paths use the process current directory.
    /// Canonical paths identify storage; logical aliases are retained for conditional includes.
    /// No environment variables or trust decisions are consulted.
    ///
    /// # Errors
    ///
    /// Returns [`OpenError`] for missing paths, malformed indirections, non-directory targets or
    /// I/O failures. Reads are synchronous and metadata path files have no caller-supplied bound.
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("r.git");
    /// let repo = Repository::init(ObjectFormat::Sha1, &path, InitKind::Bare)?;
    /// let selected = girt::RepositoryLocation::at_git_dir(repo.git_dir())?;
    /// let opened = selected.open_with_config(&girt::config::ConfigInputs::default())?;
    /// assert_eq!(opened.common_dir(), selected.common_dir());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn at_git_dir(path: impl AsRef<Path>) -> Result<Self, OpenError> {
        Self::resolve(path.as_ref(), true)
    }

    /// Canonical private Git directory selected by this location.
    pub fn git_dir(&self) -> &Path {
        &self.git_dir
    }

    /// Canonical common directory selected by this location.
    pub fn common_dir(&self) -> &Path {
        &self.common_dir
    }

    /// Opens the selected metadata with explicit configuration inputs.
    ///
    /// Uses the stored directories without repeating repository selection. Linked checkout
    /// backlinks may still be verified during opening. The
    /// caller must apply any trust policy before this call. Configuration and repository metadata
    /// are read now; no ambient environment is read. See [`Repository::open_with_config`].
    ///
    /// # Errors
    ///
    /// Returns the validation, configuration and I/O errors of [`Repository::open_with_config`].
    /// No files are written, and no fallback location is attempted.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::RepositoryLocation;
    /// use girt::config::ConfigInputs;
    /// let directory = tempfile::tempdir()?;
    /// let repo = girt::Repository::init(
    ///     girt::ObjectFormat::Sha1,
    ///     directory.path().join("project"),
    ///     girt::InitKind::Worktree,
    /// )?;
    /// let location = RepositoryLocation::at_git_dir(repo.git_dir())?;
    /// let repository = location.open_with_config(&ConfigInputs::default())?;
    /// assert_eq!(repository.git_dir(), location.git_dir());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_with_config(&self, inputs: &ConfigInputs) -> Result<Repository, OpenError> {
        Repository::open_location(self, inputs, crate::refs::reftable::StackLimits::default())
    }

    /// Reads layout, format and effective configuration without opening repository storage.
    ///
    /// Uses the selected directories and retained aliases. Validates HEAD and layout markers,
    /// direct repository format/extensions, worktree settings and configuration inputs using the
    /// same bootstrap as [`Self::open_with_config`]. Reftable HEAD is read with default stack
    /// limits to supply branch-conditional include context. Object directory existence is checked,
    /// but object contents, index and shallow metadata are not read.
    ///
    /// The caller supplies trust policy before this call. No ambient environment is read and no
    /// repository is reselected. The returned configuration is a snapshot, not a filesystem lock
    /// or a guarantee that all Git runtime settings are supported.
    ///
    /// # Errors
    ///
    /// Returns [`OpenError`] for bootstrap layout, format, HEAD, configuration or I/O failures.
    /// Configuration uses the supplied budgets; other metadata retains [`Repository::open`]'s
    /// allocation contract. No files are written. Shallow validation is deferred to full opening.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::RepositoryLocation;
    /// use girt::config::ConfigInputs;
    /// let directory = tempfile::tempdir()?;
    /// let repo = girt::Repository::init(
    ///     girt::ObjectFormat::Sha1,
    ///     directory.path().join("project"),
    ///     girt::InitKind::Worktree,
    /// )?;
    /// let location = RepositoryLocation::at_git_dir(repo.git_dir())?;
    /// let metadata = location.read_metadata_with_config(&ConfigInputs::default())?;
    /// assert_eq!(metadata.git_dir(), location.git_dir());
    /// println!("{}", metadata.object_format());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn read_metadata_with_config(
        &self,
        inputs: &ConfigInputs,
    ) -> Result<RepositoryMetadata, OpenError> {
        self.read_metadata_with_config_and_include_placement(inputs, IncludePlacement::InPlace)
    }

    /// Reads ordinary repository metadata with explicit effective include placement.
    ///
    /// Uses the layout, trust obligations and direct format validation of
    /// [`Self::read_metadata_with_config`]. Only effective configuration placement changes;
    /// direct bootstrap configuration and source selection do not. Full opening and command-layout
    /// reading retain their default in-place resolution. See
    /// [`Config::resolve_with_include_placement`](crate::Config::resolve_with_include_placement).
    ///
    /// # Errors
    ///
    /// Reports the same bootstrap, source and budget failures as
    /// [`Self::read_metadata_with_config`]. Includes are validated forward and depth-first
    /// regardless of placement. No files are written.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::RepositoryLocation;
    /// use girt::config::{ConfigInputs, IncludePlacement};
    /// let directory = tempfile::tempdir()?;
    /// let repo = girt::Repository::init(
    ///     girt::ObjectFormat::Sha1,
    ///     directory.path().join("project"),
    ///     girt::InitKind::Worktree,
    /// )?;
    /// let location = RepositoryLocation::at_git_dir(repo.git_dir())?;
    /// let metadata = location.read_metadata_with_config_and_include_placement(
    ///     &ConfigInputs::default(),
    ///     IncludePlacement::AfterSectionReverse,
    /// )?;
    /// assert_eq!(metadata.git_dir(), location.git_dir());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn read_metadata_with_config_and_include_placement(
        &self,
        inputs: &ConfigInputs,
        placement: IncludePlacement,
    ) -> Result<RepositoryMetadata, OpenError> {
        RepositoryMetadata::read_location(
            self,
            inputs,
            crate::refs::reftable::StackLimits::default(),
            None,
            placement,
        )
    }

    fn resolve(path: &Path, exact: bool) -> Result<Self, OpenError> {
        Self::resolve_storage(path, exact, None, None)
    }

    fn resolve_storage(
        path: &Path,
        exact: bool,
        common_override: Option<&Path>,
        object_override: Option<&Path>,
    ) -> Result<Self, OpenError> {
        let input = path;
        let metadata = match fs::metadata(input) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                return Err(OpenError::NotFound(input.into()));
            }
            Err(source) => return Err(io_error(input, source)),
        };
        let logical_input = if input.is_absolute() {
            input.to_path_buf()
        } else {
            std::path::absolute(input).map_err(|error| io_error(input, error))?
        };
        let logical_git_dir = if !exact && metadata.is_dir() && logical_input.join(".git").is_dir()
        {
            Some(logical_input.join(".git"))
        } else if metadata.is_dir() && (exact || !logical_input.join(".git").exists()) {
            Some(logical_input.clone())
        } else if metadata.is_file() {
            Some(gitfile_target(&logical_input)?)
        } else if metadata.is_dir() && logical_input.join(".git").is_file() {
            Some(gitfile_target(&logical_input.join(".git"))?)
        } else {
            None
        };
        let input = canonical(input)?;
        let (git_dir, inferred_worktree) = if metadata.is_file() {
            (
                read_gitfile(&logical_input)?,
                logical_input.parent().map(canonical).transpose()?,
            )
        } else if !exact && entry_exists(&input.join(".git"))? {
            let dotgit = input.join(".git");
            let git_dir = if dotgit.is_dir() {
                canonical(&dotgit)?
            } else {
                read_gitfile(&dotgit)?
            };
            (git_dir, Some(input.clone()))
        } else {
            let parent = logical_input.parent();
            let dotgit_identity = if exact {
                (logical_input.file_name() == Some(std::ffi::OsStr::new(".git")))
                    .then(|| input.clone())
            } else {
                parent.and_then(|parent| fs::canonicalize(parent.join(".git")).ok())
            };
            let inferred = parent
                .filter(|_| dotgit_identity.as_deref() == Some(input.as_path()))
                .map(canonical)
                .transpose()?;
            (input.clone(), inferred)
        };
        require_directory(&git_dir)?;
        if !exact {
            if !exists(&git_dir.join("HEAD"))? {
                if inferred_worktree.is_some() || exists(&git_dir.join("objects"))? {
                    return Err(malformed(&git_dir, "missing HEAD marker"));
                }
                return Err(OpenError::NotFound(input));
            }
            validate_head(&git_dir.join("HEAD"))?;
        }
        let common_file = git_dir.join("commondir");
        let (common_dir, common_dir_redirected) = if let Some(common) = common_override {
            (canonical(common)?, true)
        } else if exists(&common_file)? {
            let relative = metadata_path(&common_file, &read(&common_file)?)?;
            (canonical(&git_dir.join(relative))?, true)
        } else {
            (git_dir.clone(), false)
        };
        require_directory(&common_dir)?;
        Ok(Self {
            git_dir,
            common_dir,
            object_dir: object_override.map(Path::to_path_buf),
            common_dir_redirected,
            logical_git_dir,
            inferred_worktree,
        })
    }
}

/// Immutable repository layout, format and effective configuration observed during bootstrap.
///
/// Created by [`RepositoryLocation::read_metadata_with_config`]. This value provides no object,
/// general reference, index or shallow-history operations. Its explicit orphan-worktree creation
/// method uses layout metadata without reading shallow history. Validation matches girt's opening
/// bootstrap; it does not establish trust, validate every Git runtime setting or freeze filesystem
/// identity. [`Self::open_storage`] reuses this snapshot and separately observes current shallow
/// roots.
///
/// Retain this value when layout/configuration inspection should precede storage work. Opening
/// storage reuses these decisions and separately reads shallow metadata; it does not re-resolve
/// configuration or lock the repository.
///
/// ```
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("r.git");
/// let repo = Repository::init(ObjectFormat::Sha1, &path, InitKind::Bare)?;
/// let location = girt::RepositoryLocation::at_git_dir(repo.git_dir())?;
/// let metadata = location.read_metadata_with_config(&girt::config::ConfigInputs::default())?;
/// let opened = metadata.open_storage()?;
/// assert_eq!(opened.object_format(), metadata.object_format());
/// assert_eq!(opened.object_dir(), metadata.object_dir());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct RepositoryMetadata {
    git_dir: PathBuf,
    common_dir: PathBuf,
    object_dir: PathBuf,
    worktree: Option<PathBuf>,
    bare: bool,
    config: Config,
    format_version: u32,
    object_format: ObjectFormat,
    reference_backend: crate::refs::Backend,
    worktree_config_conflict: bool,
}

impl RepositoryMetadata {
    /// Selected canonical private Git directory containing HEAD.
    pub fn git_dir(&self) -> &Path {
        &self.git_dir
    }
    /// Selected canonical common metadata directory.
    pub fn common_dir(&self) -> &Path {
        &self.common_dir
    }
    /// Shared object directory whose existence was checked, without reading its contents.
    pub fn object_dir(&self) -> &Path {
        &self.object_dir
    }
    /// Known checkout root; `None` means bare or unknown. See [`Repository::worktree`].
    pub fn worktree(&self) -> Option<&Path> {
        self.worktree.as_deref()
    }
    /// Whether layout bootstrap declares a bare repository, independently of checkout availability.
    pub fn is_bare(&self) -> bool {
        self.bare
    }
    /// Direct common configuration's accepted repository format version (0 or 1).
    pub fn format_version(&self) -> u32 {
        self.format_version
    }
    /// Object format selected from direct common configuration.
    pub fn object_format(&self) -> ObjectFormat {
        self.object_format
    }
    /// Reference storage selected from direct common configuration.
    pub fn reference_backend(&self) -> crate::refs::Backend {
        self.reference_backend
    }
    /// Resolved configuration snapshot, including source provenance and explicit caller inputs.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Opens storage from this captured layout and configuration, reading current shallow roots.
    ///
    /// Does not reselect paths, reread configuration or repeat bootstrap validation. The returned
    /// repository retains the captured object format and reference backend. Its shallow snapshot
    /// comes from the captured common directory, with the same 16 MiB limit as ordinary opening.
    /// Objects, indexes and references remain live storage and can fail when subsequently accessed.
    /// This operation neither establishes trust nor locks filesystem identities against
    /// replacement.
    ///
    /// The metadata remains reusable after success or failure. Each call observes shallow roots
    /// anew; repositories returned by earlier calls keep their own shallow snapshots.
    ///
    /// # Errors
    ///
    /// Returns [`OpenError::Shallow`] if current shallow metadata cannot be read or parsed. No
    /// repository files are changed, and callers can repair the shallow file and retry this
    /// snapshot.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::config::ConfigInputs;
    /// use girt::{InitKind, ObjectFormat, Repository, RepositoryLocation};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let initialized = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("repo"),
    ///     InitKind::Bare,
    /// )?;
    /// let location = RepositoryLocation::at_git_dir(initialized.git_dir())?;
    /// let metadata = location.read_metadata_with_config(&ConfigInputs::default())?;
    /// let repository = metadata.open_storage()?;
    /// assert_eq!(repository.git_dir(), metadata.git_dir());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_storage(&self) -> Result<Repository, OpenError> {
        let shallow = self.read_shallow()?;
        Ok(self.clone().into_storage(shallow))
    }

    fn read_shallow(&self) -> Result<ShallowRoots, OpenError> {
        Ok(ShallowRoots::read(
            self.common_dir.join("shallow"),
            self.object_format,
            16 * 1024 * 1024,
            &std::sync::atomic::AtomicBool::new(false),
        )?)
    }

    fn into_storage(self, shallow: ShallowRoots) -> Repository {
        Repository {
            git_dir: self.git_dir,
            common_dir: self.common_dir,
            object_dir: self.object_dir,
            worktree: self.worktree,
            bare: self.bare,
            config: self.config,
            format_version: self.format_version,
            object_format: self.object_format,
            shallow,
            reference_backend: self.reference_backend,
        }
    }

    fn read_location(
        location: &RepositoryLocation,
        inputs: &ConfigInputs,
        reference_limits: crate::refs::reftable::StackLimits,
        command: Option<command_layout::CommandWorktree<'_>>,
        placement: IncludePlacement,
    ) -> Result<Self, OpenError> {
        let RepositoryLocation {
            git_dir,
            common_dir,
            object_dir,
            common_dir_redirected,
            logical_git_dir,
            inferred_worktree,
        } = location.clone();
        if !exists(&git_dir.join("HEAD"))? {
            if inferred_worktree.is_some() || exists(&git_dir.join("objects"))? {
                return Err(malformed(&git_dir, "missing HEAD marker"));
            }
            return Err(OpenError::NotFound(git_dir.clone()));
        }
        validate_head(&git_dir.join("HEAD"))?;
        let object_dir = object_dir.unwrap_or_else(|| common_dir.join("objects"));
        require_directory(&object_dir)?;
        require_directory(&common_dir.join("refs"))?;
        let config_path = common_dir.join("config");
        let bytes = if exists(&config_path)? {
            read_config(&config_path, inputs.limits.bytes)?
        } else {
            Vec::new()
        };
        let config = Config::parse(&bytes).map_err(|source| OpenError::Config {
            path: config_path.clone(),
            source,
        })?;
        if command.is_some()
            && config
                .value("core", None, "repositoryformatversion")
                .is_none()
        {
            return Err(unsupported(
                &config_path,
                "command layout without repository format version",
            ));
        }
        let (format_version, object_format) = validate_config(&config, &config_path)?;
        let reference_backend = match config.value("extensions", None, "refstorage") {
            Some(Some(b"reftable")) => crate::refs::Backend::Reftable,
            _ => crate::refs::Backend::Files,
        };
        let mut inputs = inputs.clone();
        inputs.context.git_dirs.push(git_dir.clone());
        if let Some(logical_git_dir) = logical_git_dir {
            inputs.context.git_dirs.push(logical_git_dir);
        }
        let head = read(&git_dir.join("HEAD"))?;
        let head = head.strip_suffix(b"\n").unwrap_or(&head);
        let head = head.strip_suffix(b"\r").unwrap_or(head);
        inputs.context.branch = if reference_backend == crate::refs::Backend::Reftable {
            let snapshot = crate::refs::reftable::Snapshot::read(
                &git_dir.join("reftable"),
                object_format,
                reference_limits,
                &std::sync::atomic::AtomicBool::new(false),
            )?;
            snapshot
                .table
                .references
                .into_iter()
                .find(|record| record.name.as_bytes() == b"HEAD")
                .and_then(|record| match record.target {
                    Some(crate::refs::Target::Symbolic(name)) => name
                        .as_bytes()
                        .strip_prefix(b"refs/heads/")
                        .map(<[u8]>::to_vec),
                    _ => None,
                })
        } else {
            head.strip_prefix(b"ref: refs/heads/").map(<[u8]>::to_vec)
        };
        inputs.files.push(ConfigFile {
            path: config_path.clone(),
            scope: ConfigScope::Local,
            optional: true,
            skip_unreadable: false,
        });
        let worktree_config_enabled = extension_boolean(&config, &config_path, "worktreeconfig")?;
        let ignore_common_layout = if command.is_some() {
            common_dir_redirected
        } else {
            git_dir != common_dir && !worktree_config_enabled
        };
        let mut layout_config = if ignore_common_layout {
            Config::parse(b"").expect("empty configuration")
        } else {
            config.clone()
        };
        if worktree_config_enabled {
            let worktree_path = git_dir.join("config.worktree");
            if exists(&worktree_path)? {
                let worktree_config =
                    Config::parse(&read_config(&worktree_path, inputs.limits.bytes)?).map_err(
                        |source| OpenError::Config {
                            path: worktree_path.clone(),
                            source,
                        },
                    )?;
                layout_config.append(&worktree_config);
            }
            inputs.files.push(ConfigFile {
                path: worktree_path,
                scope: ConfigScope::Worktree,
                optional: true,
                skip_unreadable: false,
            });
        }
        let (worktree, bare, worktree_config_conflict) = if let Some(command) = command {
            command.resolve(&git_dir, &layout_config, &config_path)?
        } else {
            let worktree = resolve_worktree(
                &git_dir,
                &common_dir,
                inferred_worktree,
                &layout_config,
                &config_path,
            )?;
            let bare = boolean(&layout_config, &config_path, "bare")?.unwrap_or(worktree.is_none());
            (worktree, bare, false)
        };
        let config = Config::resolve_with_include_placement(&inputs, placement)?;
        Ok(Self {
            git_dir,
            common_dir,
            object_dir,
            worktree,
            bare,
            config,
            format_version,
            object_format,
            reference_backend,
            worktree_config_conflict,
        })
    }
}

/// An opened repository's metadata paths, checkout location and resolved snapshots.
///
/// Use this interface for explicit configuration, limits, cancellation, and untrusted input.
/// [`crate::Repo`] composes repository operations for trusted local use with Git defaults, lazy
/// loading, and default limits. Wrap this value with [`crate::Repo::new`] to use those
/// conveniences.
///
/// # Common entry points
///
/// - [`Self::open`] opens an explicit path; [`Self::discover`] searches ancestors, and
///   [`Self::init`] creates a repository at a chosen path.
/// - [`Self::loose_objects`] writes and reads loose objects; [`Self::objects`] opens a bounded
///   loose/packed reader. [`Self::references`] accesses the selected reference backend.
/// - [`Self::read_index`] observes per-worktree index storage; [`Self::edit_index`] locks and
///   publishes an explicit edit. Fetch, push, status, and checkout have separate module contracts.
///
/// Opening accepts a worktree root, Git directory, or `gitdir:` file. It never searches parents,
/// initializes files, runs Git, or reads environment overrides or system/global configuration.
/// Relative input paths resolve against the process current directory. Symlinks are resolved;
/// opening is not a security boundary against concurrent filesystem changes or untrusted paths.
///
/// Ordinary, bare, separate-Git-directory and linked-worktree layouts are supported. Repository
/// format versions 0 and 1 with SHA-1 objects, and version 1 with SHA-256 objects are
/// supported, including shallow roots and relative linked-worktree paths. Includes and enabled
/// worktree configuration are resolved. Local alternates, `noop`, `preciousObjects`, and
/// `partialClone` are recognized. Unknown extensions remain explicit errors. Precious-object
/// metadata is retained in [`Self::config`]; no pruning or lazy fetching is performed.
/// Object access uses [`Self::loose_objects`] for loose reads/writes or [`Self::objects`] for
/// bounded loose/packed reads. Opening repository metadata alone does not validate object storage.
///
/// Paths preserve OS bytes on Unix. On other platforms metadata paths must be UTF-8. No tilde,
/// environment-variable or prefix interpolation is performed. Tilde and `%(...)` prefixes in
/// core.worktree are rejected; dollar signs are literal path bytes.
///
/// Open a repository by path, store a blob, and read it back through the loose/packed reader.
/// Writing an object neither moves a reference nor touches the working tree:
///
/// ```
/// use girt::{InitKind, ObjectFormat, ObjectKind, PackLimits, ReadLimits, Repository};
///
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("project");
/// Repository::init(ObjectFormat::Sha1, &path, InitKind::Worktree)?;
///
/// let repository = Repository::open(&path)?;
/// assert_eq!(repository.worktree(), Some(path.canonicalize()?.as_path()));
///
/// let id = repository.loose_objects().write_blob(b"hello\n")?;
/// let objects = repository.objects_with(PackLimits::default())?;
/// let object = objects
///     .read_with(id, ReadLimits::default())?
///     .expect("blob was just written");
/// assert_eq!(
///     (object.kind(), object.data()),
///     (ObjectKind::Blob, &b"hello\n"[..])
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone)]
pub struct Repository {
    git_dir: PathBuf,
    common_dir: PathBuf,
    object_dir: PathBuf,
    worktree: Option<PathBuf>,
    bare: bool,
    config: Config,
    format_version: u32,
    object_format: ObjectFormat,
    shallow: ShallowRoots,
    reference_backend: crate::refs::Backend,
}

/// Repository location, metadata, configuration or supported-format failure.
/// Summarizes the layout; configuration values are omitted because they can contain secrets.
impl std::fmt::Debug for Repository {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Repository")
            .field("git_dir", &self.git_dir)
            .field("common_dir", &self.common_dir)
            .field("worktree", &self.worktree)
            .field("bare", &self.bare)
            .field("object_format", &self.object_format)
            .field("reference_backend", &self.reference_backend)
            .finish_non_exhaustive()
    }
}

/// Failure to open a repository from a path or discovered location.
///
/// Opening is read-only. Treat [`Self::NotFound`] as a selection problem, [`Self::Malformed`] as
/// inconsistent metadata, and [`Self::Unsupported`] as a capability boundary. Do not retry an
/// unsupported repository as if it used default settings. Inspect nested configuration and I/O
/// sources for the path and original cause; see the [module overview](self) for recovery guidance.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenError {
    /// Reftable HEAD metadata could not be read for branch-conditional configuration.
    /// Inspect the reftable HEAD-reading source and selected stack budgets.
    #[error(transparent)]
    References(#[from] crate::refs::ReferenceError),
    /// The opened checkout belongs to a different common repository.
    /// Select a checkout belonging to the intended common repository.
    #[error("unrelated common repository: {0}")]
    Unrelated(PathBuf),
    /// Shallow-root metadata could not be read.
    /// Inspect the shallow metadata source and preserve the existing handle if a refresh failed.
    #[error(transparent)]
    Shallow(#[from] ShallowError),
    /// The explicit path does not identify a repository.
    /// Check the selected path or discovery ceiling; initialization is a separate operation.
    #[error("no repository at {0}")]
    NotFound(PathBuf),
    /// Filesystem access failed; the path and original cause are retained.
    /// Inspect the original filesystem failure and path, then correct access or storage before
    /// retrying.
    #[error("cannot read {path}")]
    Io {
        /// Failed path.
        path: PathBuf,
        /// Original operating-system error.
        #[source]
        source: io::Error,
    },
    /// Repository metadata contradicts the supported layout or has invalid content.
    /// Inspect the reported metadata and reason; do not bypass it by opening an enclosing
    /// repository.
    #[error("malformed repository metadata at {path}: {reason}")]
    Malformed {
        /// Metadata path.
        path: PathBuf,
        /// Failure explanation.
        reason: String,
    },
    /// Configuration syntax is invalid or unsupported.
    /// Correct syntax at the retained configuration source and line.
    #[error("invalid configuration at {path}")]
    Config {
        /// Configuration source path.
        path: PathBuf,
        /// Parser failure including physical line.
        #[source]
        source: ConfigError,
    },
    /// Effective configuration could not be resolved.
    /// Correct source selection, include context, topology or budgets identified by the nested
    /// resolution error.
    #[error(transparent)]
    Resolve(#[from] ResolveError),
    /// A recognized feature cannot be interpreted by this implementation.
    /// Choose a supported representation or extend support; silently treating it as a default
    /// repository is unsafe.
    #[error("unsupported repository feature at {path}: {feature}")]
    Unsupported {
        /// Source of the unsupported feature.
        path: PathBuf,
        /// Feature or setting requiring support.
        feature: String,
    },
}

impl Repository {
    /// Internal receive storage shares metadata but owns a separate object directory.
    pub(crate) fn with_private_object_directory(&self, directory: &Path) -> Self {
        let mut repository = self.clone();
        repository.object_dir = directory.to_owned();
        repository
    }

    /// Returns the on-disk reference backend selected by local repository configuration.
    pub fn reference_backend(&self) -> crate::refs::Backend {
        self.reference_backend
    }

    /// Borrows this repository's reference store.
    ///
    /// Uses the detected common/worktree directories. See [`crate::refs::References`] for the
    /// byte-name, platform, read and explicit no-reflog update boundaries.
    ///
    /// # Errors
    ///
    /// Reference storage supports Unix and Windows local filesystems. Repository
    /// unknown backends are rejected by [`Self::open`] before a handle can be constructed.
    pub fn references(&self) -> Result<crate::refs::References<'_>, crate::refs::ReferenceError> {
        crate::refs::References::new(self)
    }

    /// Resolves `HEAD` to the reference it ends at and that reference's object ID.
    ///
    /// On a branch, the resolution names the branch. A detached `HEAD` names `HEAD` itself. An
    /// unborn branch, one with no commits yet, resolves with `id: None`; the resolution still
    /// names the branch. Follows symbolic references as far as Git does; see
    /// [`crate::refs::References::resolve`]. Use [`crate::refs::References::resolve_with`] to
    /// choose a different limit.
    ///
    /// This reads references only. It doesn't check that the object exists or is a commit; use
    /// [`crate::Objects::read_commit`] for that.
    ///
    /// ```
    /// use girt::refs::RefName;
    /// use girt::{InitKind, ObjectFormat, Repository};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("repo.git");
    /// let repository = Repository::init(ObjectFormat::Sha1, path, InitKind::Bare)?;
    /// let head = repository.head()?;
    /// assert_eq!(head.name, RefName::new("refs/heads/main")?);
    /// assert_eq!(head.id, None);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns the failures of [`Self::references`] and [`crate::refs::References::resolve`].
    pub fn head(&self) -> Result<crate::refs::Resolution, crate::refs::ReferenceError> {
        self.references()?.resolve(&crate::refs::RefName::HEAD)
    }

    /// Opens only the supplied location, without changing files.
    ///
    /// Reads `config` from the common directory; repeated scalar settings use the last value.
    /// Missing config uses version 0, SHA-1, and layout-based worktree inference. `core.bare` and
    /// `core.worktree` override ordinary layout inference; relative core.worktree is relative to
    /// the Git directory. A linked worktree uses its `gitdir` backlink, verified against its
    /// `.git` file when opening through a checkout. Opening private metadata does not require an
    /// accessible checkout; use [`Self::worktrees`] to inspect backlink availability. Backlinks
    /// may be absolute or relative to the private Git directory. Without worktreeConfig, linked
    /// layouts ignore shared core.bare/worktree. With it, direct common settings followed by
    /// direct private settings determine the checkout. Includes participate only in the
    /// effective snapshot. Unknown extension keys are rejected even in version 0.
    ///
    /// # Errors
    ///
    /// Distinguishes missing locations, malformed metadata, I/O failures, configuration failures,
    /// and unsupported configuration or storage features. No files are written
    /// on success or failure. Filesystem reads and allocation are synchronous and unbounded by a
    /// caller-supplied resource limit except configuration and shallow metadata. The default
    /// shallow snapshot is limited to 16 MiB.
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("archive.git");
    /// Repository::init(ObjectFormat::Sha256, &path, InitKind::Bare)?;
    /// let repository = Repository::open(&path)?;
    /// assert!(repository.is_bare());
    /// assert_eq!(repository.object_format(), ObjectFormat::Sha256);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open(path: impl AsRef<Path>) -> Result<Self, OpenError> {
        Self::open_with_config(path, &ConfigInputs::default())
    }

    /// Opens a repository with explicit inherited sources, environment pairs and caller overrides.
    ///
    /// Adds common-directory local configuration and, when enabled in that file, per-worktree
    /// configuration to the supplied inputs. Repository paths and HEAD provide include context;
    /// caller Git-directory aliases are retained. No ambient environment is read.
    /// Format bootstrap uses only the direct common configuration; enabled direct worktree settings
    /// also participate in layout bootstrap. Includes, worktree format settings and overrides
    /// cannot change the opened object format. Reopen to refresh both
    /// metadata and effective configuration; existing handles remain snapshots.
    ///
    /// # Errors
    ///
    /// Returns the layout/format errors of [`Self::open`] or contextual configuration resolution
    /// failures. All operations are read-only. Config resolution obeys the supplied budgets;
    /// repository metadata bootstrap retains [`Self::open`]'s allocation contract.
    ///
    /// ```
    /// use girt::config::{ConfigFile, ConfigInputs, ConfigScope};
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("project");
    /// let repo = Repository::init(ObjectFormat::Sha1, &path, InitKind::Worktree)?;
    /// let global = directory.path().join("global");
    /// std::fs::write(&global, b"[core]\neditor = user-editor\n")?;
    /// let mut edit = repo.edit_config(4096)?;
    /// edit.document_mut()
    ///     .append("core", None, "editor", b"project-editor")?;
    /// edit.commit()?;
    /// let inputs =
    ///     ConfigInputs::default().with_files(vec![ConfigFile::new(global, ConfigScope::Global)]);
    /// let opened = Repository::open_with_config(&path, &inputs)?;
    /// assert_eq!(
    ///     opened.config().string("core", None, "editor"),
    ///     Some(&b"project-editor"[..])
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_with_config(
        path: impl AsRef<Path>,
        inputs: &ConfigInputs,
    ) -> Result<Self, OpenError> {
        Self::open_with_config_and_reference_limits(
            path,
            inputs,
            crate::refs::reftable::StackLimits::default(),
        )
    }

    /// Opens configured metadata with explicit reftable HEAD-reading budgets.
    ///
    /// Reftable HEAD supplies branch-conditional include context. These bounds apply to that
    /// bootstrap stack read; reference operations select their own budgets with
    /// [`crate::refs::References::with_reftable_limits`]. Files repositories ignore these bounds.
    ///
    /// # Errors
    ///
    /// Returns [`Self::open_with_config`]'s errors, including bounded reftable decoding failures.
    /// The operation does not mutate the repository or retry a raced stack read.
    ///
    /// ```
    /// use girt::config::ConfigInputs;
    /// use girt::refs::Backend;
    /// use girt::refs::reftable::StackLimits;
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init_with_backend(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r.git"),
    ///     InitKind::Bare,
    ///     Backend::Reftable,
    /// )?;
    /// let opened = Repository::open_with_config_and_reference_limits(
    ///     repo.git_dir(),
    ///     &ConfigInputs::default(),
    ///     StackLimits::default().with_tables(8),
    /// )?;
    /// assert_eq!(opened.reference_backend(), Backend::Reftable);
    /// assert!(matches!(
    ///     Repository::open_with_config_and_reference_limits(
    ///         repo.git_dir(),
    ///         &ConfigInputs::default(),
    ///         StackLimits::default().with_tables(0),
    ///     ),
    ///     Err(girt::OpenError::References(_))
    /// ));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_with_config_and_reference_limits(
        path: impl AsRef<Path>,
        inputs: &ConfigInputs,
        reference_limits: crate::refs::reftable::StackLimits,
    ) -> Result<Self, OpenError> {
        let location = RepositoryLocation::resolve(path.as_ref(), false)?;
        Self::open_location(&location, inputs, reference_limits)
    }

    fn open_location(
        location: &RepositoryLocation,
        inputs: &ConfigInputs,
        reference_limits: crate::refs::reftable::StackLimits,
    ) -> Result<Self, OpenError> {
        let metadata = RepositoryMetadata::read_location(
            location,
            inputs,
            reference_limits,
            None,
            IncludePlacement::InPlace,
        )?;
        let shallow = metadata.read_shallow()?;
        Ok(metadata.into_storage(shallow))
    }

    /// Immutable shallow boundaries captured when this handle was opened or refreshed.
    pub fn shallow_roots(&self) -> &ShallowRoots {
        &self.shallow
    }

    /// Atomically replaces this handle's shallow snapshot after a successful bounded read.
    ///
    /// Existing object readers retain their old boundaries. Reopen object readers after Git
    /// deepening to refresh both packs and boundaries. On failure this handle remains unchanged.
    ///
    /// # Errors
    ///
    /// Returns [`ShallowError`] for malformed metadata, I/O, cancellation or the byte limit.
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("r.git");
    /// let repo = Repository::init(ObjectFormat::Sha1, &path, InitKind::Bare)?;
    /// let mut repo = repo;
    /// let objects = repo.objects_with(girt::PackLimits::default())?;
    /// let boundary = girt::ObjectId::Sha1([1; 20]); // Declaration only; not checked against objects here.
    /// std::fs::write(repo.common_dir().join("shallow"), format!("{boundary}\n"))?;
    /// repo.refresh_shallow(4096, &std::sync::atomic::AtomicBool::new(false))?;
    /// assert!(repo.shallow_roots().contains(boundary));
    /// assert!(objects.shallow_roots().is_empty()); // Existing reader retains the old snapshot.
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn refresh_shallow(
        &mut self,
        max_bytes: usize,
        cancel: &std::sync::atomic::AtomicBool,
    ) -> Result<(), ShallowError> {
        let roots = ShallowRoots::read(
            self.common_dir.join("shallow"),
            self.object_format,
            max_bytes,
            cancel,
        )?;
        self.shallow = roots;
        Ok(())
    }

    /// Per-worktree Git directory, containing HEAD; canonical absolute path.
    pub fn git_dir(&self) -> &Path {
        &self.git_dir
    }
    /// Shared directory containing configuration, refs and objects; canonical absolute path.
    pub fn common_dir(&self) -> &Path {
        &self.common_dir
    }
    /// Shared loose/packed object directory. Use [`Self::objects`] to open packed reads.
    pub fn object_dir(&self) -> &Path {
        &self.object_dir
    }
    /// Known worktree root. `None` means bare or an unknown checkout location; [`Self::is_bare`]
    /// distinguishes them. Opening separate metadata alone cannot infer a checkout elsewhere.
    /// Existing accessible paths are canonical; missing/inaccessible paths retain an absolute OS
    /// spelling, possibly containing `..`.
    pub fn worktree(&self) -> Option<&Path> {
        self.worktree.as_deref()
    }
    /// Whether layout bootstrap declares a bare repository, independently of checkout availability.
    ///
    /// A nonbare separate Git directory can have an unknown [`Self::worktree`] when opened without
    /// its gitfile. Metadata and object operations remain available; checkout operations require a
    /// known root. Open through the checkout or gitfile to establish that relationship.
    pub fn is_bare(&self) -> bool {
        self.bare
    }

    /// Resolved configuration snapshot, including provenance and explicit inherited sources.
    pub fn config(&self) -> &Config {
        &self.config
    }
    /// Accepted core.repositoryformatversion (0 or 1).
    pub fn format_version(&self) -> u32 {
        self.format_version
    }
    /// Object format verified from common repository configuration while opening.
    pub fn object_format(&self) -> ObjectFormat {
        self.object_format
    }
    /// Opens a bounded snapshot of pack/index pairs alongside live loose-object reads.
    ///
    /// See [`crate::Objects`] for supported versions, validation timing, snapshot lifetime,
    /// external-base policy, and filesystem assumptions. Does not create files or directories.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ObjectReadError`] for malformed or unsupported packed storage, I/O
    /// failures, or exhausted snapshot limits. If a concurrent publisher left an incomplete pair,
    /// retry opening after publication finishes; retained readers keep their earlier pinned packs.
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("r.git");
    /// let repo = Repository::init(ObjectFormat::Sha1, &path, InitKind::Bare)?;
    /// let id = repo.loose_objects().write_blob(b"retained reader")?;
    /// let objects = repo.objects_with(girt::PackLimits::default())?;
    /// let limits = girt::ReadLimits::default();
    /// assert_eq!(
    ///     objects.read_with(id, limits)?.ok_or("blob absent")?.data(),
    ///     b"retained reader"
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn objects_with(
        &self,
        limits: crate::PackLimits,
    ) -> Result<crate::Objects, crate::ObjectReadError> {
        self.objects_with_alternates(limits, crate::AlternateLimits::default())
    }

    /// Opens object storage with [`crate::PackLimits::default`] and default alternate bounds.
    ///
    /// Equivalent to `self.objects_with(PackLimits::default())`; see [`Self::objects_with`]. Pass
    /// limits to [`Self::objects_with`] for repositories with more than 256 packs or 64 MiB of
    /// pack indexes.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`Self::objects_with`].
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r.git"),
    ///     InitKind::Bare,
    /// )?;
    /// let id = repo.loose_objects().write_blob(b"defaults")?;
    /// assert_eq!(repo.objects()?.read_blob(id)?, b"defaults");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn objects(&self) -> Result<crate::Objects, crate::ObjectReadError> {
        self.objects_with(crate::PackLimits::default())
    }

    /// Opens object storage with aggregate pack and alternate-discovery bounds.
    ///
    /// Uses primary-first, depth-first alternates-file order; each store searches loose objects
    /// before filename-ordered packs. Canonical aliases/cycles are visited once. Missing alternate
    /// directories are skipped. Metadata and packs form a fixed snapshot; loose files remain live.
    /// Call [`crate::Objects::refresh`] to observe topology changes. Concurrent edits can yield an
    /// I/O or metadata error; callers needing a consistent graph must exclude writers. No
    /// borrowed store is modified. `GIT_ALTERNATE_OBJECT_DIRECTORIES` and
    /// `GIT_OBJECT_DIRECTORY` are ignored, as with opening. HTTP alternates metadata is inert.
    /// Missing promised objects return absence without fetching.
    ///
    /// # Errors
    ///
    /// Returns storage errors for malformed paths, inaccessible directories, corrupt packs or
    /// exceeded aggregate limits. A corrupt duplicate fails at the first searched candidate.
    pub fn objects_with_alternates(
        &self,
        packs: crate::PackLimits,
        alternates: crate::AlternateLimits,
    ) -> Result<crate::Objects, crate::ObjectReadError> {
        let mut objects =
            crate::Objects::open(self.object_format, &self.object_dir, packs, alternates)?;
        objects.shallow = self.shallow.clone();
        Ok(objects)
    }

    /// Opens bounded file-backed storage with cooperative cancellation.
    ///
    /// Checks cancellation around alternate discovery and bounded index parsing, between directory
    /// entries and after pack header/trailer checks. Pack bodies are not read during opening.
    /// Individual filesystem calls cannot be interrupted. Run the whole operation on a caller-owned
    /// blocking worker when needed. On failure all opened artifacts are closed and no files are
    /// changed.
    ///
    /// # Errors
    ///
    /// Returns the errors from [`Self::objects_with_alternates`] or
    /// [`crate::ObjectReadError::Cancelled`].
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("r.git");
    /// let repo = Repository::init(ObjectFormat::Sha1, &path, InitKind::Bare)?;
    /// let cancelled = std::sync::atomic::AtomicBool::new(true);
    /// assert!(matches!(
    ///     repo.objects_controlled(
    ///         girt::PackLimits::default(),
    ///         girt::AlternateLimits::default(),
    ///         &cancelled
    ///     ),
    ///     Err(girt::ObjectReadError::Cancelled)
    /// ));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn objects_controlled(
        &self,
        packs: crate::PackLimits,
        alternates: crate::AlternateLimits,
        cancelled: &std::sync::atomic::AtomicBool,
    ) -> Result<crate::Objects, crate::ObjectReadError> {
        let mut objects = crate::Objects::open_controlled(
            self.object_format,
            &self.object_dir,
            packs,
            alternates,
            cancelled,
        )?;
        objects.shallow = self.shallow.clone();
        Ok(objects)
    }

    /// Connects to the existing loose-object API without creating directories or files.
    ///
    /// Both openable formats support loose storage. Subsequent reads/writes retain
    /// [`LooseObjects`]' format checks and storage contracts.
    pub fn loose_objects(&self) -> LooseObjects {
        LooseObjects::new(&self.object_dir, self.object_format())
    }
}

fn read_config(path: &Path, max_bytes: usize) -> Result<Vec<u8>, OpenError> {
    use std::io::Read;
    let file = fs::File::open(path).map_err(|error| io_error(path, error))?;
    let mut bytes = Vec::new();
    file.take(max_bytes.saturating_add(1) as u64)
        .read_to_end(&mut bytes)
        .map_err(|error| io_error(path, error))?;
    if bytes.len() > max_bytes {
        return Err(ResolveError {
            location: crate::config::SourceLocation {
                path: Some(path.into()),
                line: 1,
            },
            included_from: Vec::new(),
            source: crate::config::ResolveFailure::Limit("bootstrap configuration bytes"),
        }
        .into());
    }
    Ok(bytes)
}

fn validate_config(config: &Config, path: &Path) -> Result<(u32, ObjectFormat), OpenError> {
    for entry in config.entries() {
        if entry.section.eq_ignore_ascii_case(b"extensions")
            && (entry.subsection.is_some()
                || !entry.name.eq_ignore_ascii_case(b"objectformat")
                    && !entry.name.eq_ignore_ascii_case(b"worktreeconfig")
                    && !entry.name.eq_ignore_ascii_case(b"relativeworktrees")
                    && !entry.name.eq_ignore_ascii_case(b"noop")
                    && !entry.name.eq_ignore_ascii_case(b"preciousobjects")
                    && !entry.name.eq_ignore_ascii_case(b"partialclone")
                    && !entry.name.eq_ignore_ascii_case(b"refstorage"))
        {
            return Err(unsupported(
                path,
                &format!(
                    "extensions.{}",
                    String::from_utf8_lossy(&entry.name.to_ascii_lowercase())
                ),
            ));
        }
    }
    let version = match config.value("core", None, "repositoryformatversion") {
        None => 0,
        Some(Some(value)) => parse_version(value)
            .ok_or_else(|| malformed(path, "invalid core.repositoryformatversion"))?,
        Some(None) => return Err(malformed(path, "implicit core.repositoryformatversion")),
    };
    if version > 1 {
        return Err(unsupported(
            path,
            &format!("repository format version {version}"),
        ));
    }
    extension_boolean(config, path, "relativeworktrees")?;
    extension_boolean(config, path, "preciousobjects")?;
    if config.value("extensions", None, "partialclone") == Some(None) {
        return Err(malformed(path, "implicit extensions.partialClone"));
    }
    if let Some(value) = config.value("extensions", None, "refstorage")
        && (version != 1 || !matches!(value, Some(b"files" | b"reftable")))
    {
        return Err(unsupported(
            path,
            "unknown or version-zero extensions.refStorage",
        ));
    }
    let mut object_format = ObjectFormat::Sha1;
    if let Some(value) = config.value("extensions", None, "objectformat") {
        if version == 0 {
            return Err(unsupported(
                path,
                "extensions.objectFormat requires repository version 1",
            ));
        }
        match value {
            Some(b"sha1") => (),
            Some(b"sha256") => object_format = ObjectFormat::Sha256,
            _ => return Err(unsupported(path, "unknown extensions.objectFormat")),
        }
    }
    Ok((version, object_format))
}

fn extension_boolean(config: &Config, path: &Path, name: &str) -> Result<bool, OpenError> {
    match config.value("extensions", None, name) {
        None => Ok(false),
        Some(value) => {
            config_boolean(value).ok_or_else(|| malformed(path, "invalid extension boolean"))
        }
    }
}

fn parse_version(value: &[u8]) -> Option<u32> {
    u32::try_from(integer(value)?).ok()
}

fn boolean(config: &Config, path: &Path, name: &str) -> Result<Option<bool>, OpenError> {
    match config.value("core", None, name) {
        None => Ok(None),
        Some(value) => config_boolean(value)
            .map(Some)
            .ok_or_else(|| malformed(path, &format!("invalid core.{name} boolean"))),
    }
}

fn resolve_worktree(
    git_dir: &Path,
    common_dir: &Path,
    inferred: Option<PathBuf>,
    config: &Config,
    source: &Path,
) -> Result<Option<PathBuf>, OpenError> {
    let bare = boolean(config, source, "bare")?;
    let configured = config.value("core", None, "worktree");
    if git_dir != common_dir && configured.is_none() && bare != Some(true) {
        let backlink = git_dir.join("gitdir");
        let target = git_dir.join(metadata_path(&backlink, &read(&backlink)?)?);
        let root = target
            .parent()
            .ok_or_else(|| malformed(&backlink, "backlink has no parent"))?;
        // Metadata remains useful when a registered checkout has disappeared. Validate a live
        // backlink separately; enumeration retains its failure without losing this Git directory.
        if let Some(inferred) = inferred {
            if canonical(root)? != inferred || read_gitfile(&target)? != git_dir {
                return Err(malformed(&backlink, "worktree and backlink disagree"));
            }
            return Ok(Some(inferred));
        }
        return Ok(Some(available_path(root)?));
    }
    if let Some(value) = configured {
        if bare == Some(true) {
            return Err(malformed(source, "core.bare and core.worktree conflict"));
        }
        let value = value
            .filter(|value| !value.is_empty())
            .ok_or_else(|| malformed(source, "empty core.worktree"))?;
        if value.starts_with(b"~") || value.starts_with(b"%(") {
            return Err(unsupported(source, "core.worktree path interpolation"));
        }
        return Ok(Some(available_path(
            &git_dir.join(path_bytes(source, value)?),
        )?));
    }
    if bare == Some(true) {
        return Ok(None);
    }
    if let Some(root) = inferred {
        return Ok(Some(root));
    }
    Ok(None)
}

fn validate_head(path: &Path) -> Result<(), OpenError> {
    let bytes = read(path)?;
    let bytes = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
    let bytes = bytes.strip_suffix(b"\r").unwrap_or(bytes);
    let symbolic = bytes.strip_prefix(b"ref: ").is_some_and(|name| {
        name.starts_with(b"refs/") && !name.iter().any(|b| b.is_ascii_whitespace() || *b == 0)
    });
    let detached = matches!(bytes.len(), 40 | 64) && bytes.iter().all(u8::is_ascii_hexdigit);
    if !symbolic && !detached {
        return Err(malformed(
            path,
            "invalid HEAD marker (reference resolution is not performed)",
        ));
    }
    Ok(())
}

fn read_gitfile(path: &Path) -> Result<PathBuf, OpenError> {
    canonical(&gitfile_target(path)?)
}
fn gitfile_target(path: &Path) -> Result<PathBuf, OpenError> {
    let bytes = read(path)?;
    let value = bytes
        .strip_prefix(b"gitdir: ")
        .ok_or_else(|| malformed(path, "expected gitdir: indirection"))?;
    let target = metadata_path(path, value)?;
    Ok(path.parent().unwrap_or(Path::new(".")).join(target))
}
fn metadata_path(source: &Path, bytes: &[u8]) -> Result<PathBuf, OpenError> {
    let end = bytes
        .iter()
        .rposition(|byte| !matches!(byte, b'\r' | b'\n'));
    let bytes = &bytes[..end.map_or(0, |index| index + 1)];
    if bytes.is_empty() || bytes.contains(&0) {
        return Err(malformed(source, "empty path or NUL in path"));
    }
    path_bytes(source, bytes)
}
fn path_bytes(source: &Path, bytes: &[u8]) -> Result<PathBuf, OpenError> {
    if bytes.contains(&0) {
        return Err(malformed(source, "NUL in path"));
    }
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        Ok(PathBuf::from(std::ffi::OsStr::from_bytes(bytes)))
    }
    #[cfg(not(unix))]
    {
        std::str::from_utf8(bytes)
            .map(PathBuf::from)
            .map_err(|_| unsupported(source, "non-UTF-8 path"))
    }
}
fn entry_exists(path: &Path) -> Result<bool, OpenError> {
    match fs::symlink_metadata(path) {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(source) => Err(io_error(path, source)),
    }
}
fn exists(path: &Path) -> Result<bool, OpenError> {
    match fs::metadata(path) {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(source) => Err(io_error(path, source)),
    }
}
fn read(path: &Path) -> Result<Vec<u8>, OpenError> {
    fs::read(path).map_err(|source| {
        if source.kind() == io::ErrorKind::NotFound {
            malformed(path, "missing required metadata")
        } else {
            io_error(path, source)
        }
    })
}
fn canonical(path: &Path) -> Result<PathBuf, OpenError> {
    fs::canonicalize(path).map_err(|source| {
        if source.kind() == io::ErrorKind::NotFound {
            malformed(path, "metadata path does not exist")
        } else {
            io_error(path, source)
        }
    })
}
fn io_error(path: &Path, source: io::Error) -> OpenError {
    OpenError::Io {
        path: path.into(),
        source,
    }
}
fn malformed(path: &Path, reason: &str) -> OpenError {
    OpenError::Malformed {
        path: path.into(),
        reason: reason.into(),
    }
}
fn unsupported(path: &Path, feature: &str) -> OpenError {
    OpenError::Unsupported {
        path: path.into(),
        feature: feature.into(),
    }
}

// Preserve an absolute OS path for missing/inaccessible checkouts; metadata opening is independent
// of checkout availability. Canonicalize live paths to compare aliases without lexical guesses.
fn available_path(path: &Path) -> Result<PathBuf, OpenError> {
    match fs::canonicalize(path) {
        Ok(path) => Ok(path),
        Err(error)
            if matches!(
                error.kind(),
                io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
            ) =>
        {
            std::path::absolute(path).map_err(|error| io_error(path, error))
        }
        Err(error) => Err(io_error(path, error)),
    }
}

fn require_directory(path: &Path) -> Result<(), OpenError> {
    match fs::metadata(path) {
        Ok(metadata) if metadata.is_dir() => Ok(()),
        Ok(_) => Err(malformed(path, "expected directory")),
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            Err(malformed(path, "missing required directory"))
        }
        Err(error) => Err(io_error(path, error)),
    }
}

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

    use super::*;
    #[test]
    fn exact_location_accepts_structure_without_repository_contents() {
        let root = tempfile::tempdir().unwrap();
        let location = RepositoryLocation::at_git_dir(root.path()).unwrap();
        assert_eq!(location.git_dir(), canonical(root.path()).unwrap());
        assert_eq!(location.common_dir(), location.git_dir());
        assert!(matches!(
            location.open_with_config(&ConfigInputs::default()),
            Err(OpenError::NotFound(_))
        ));
    }

    #[rstest]
    #[case::zero(b"0", Some(0))]
    #[case::plus(b"+1", Some(1))]
    #[case::suffix(b"1k", Some(1024))]
    #[case::invalid(b"no", None)]
    fn versions(#[case] bytes: &[u8], #[case] expected: Option<u32>) {
        assert_eq!(parse_version(bytes), expected);
    }
    #[rstest]
    #[case::octal(b"010", Some(8))]
    #[case::hex(b"0x1", Some(1))]
    #[case::negative(b"-1", Some(-1))]
    #[case::invalid_octal(b"08", None)]
    #[case::overflow(b"99999999999999999999", None)]
    fn git_integers(#[case] bytes: &[u8], #[case] expected: Option<i64>) {
        assert_eq!(integer(bytes), expected);
    }

    #[rstest]
    #[case::false_value(b"[core]\nbare=off\n", Some(false))]
    #[case::implicit(b"[core]\nbare\n", Some(true))]
    #[case::absent(b"[core]\n", None)]
    fn bare_values(#[case] bytes: &[u8], #[case] expected: Option<bool>) {
        let config = Config::parse(bytes).unwrap();
        assert_eq!(
            boolean(&config, Path::new("config"), "bare").unwrap(),
            expected
        );
    }

    #[cfg(unix)]
    #[test]
    fn metadata_paths_preserve_bytes() {
        use std::os::unix::ffi::OsStrExt;
        let path = path_bytes(Path::new("config"), b"work-\xff").unwrap();
        assert_eq!(path.as_os_str().as_bytes(), b"work-\xff");
    }

    #[test]
    fn missing_path_is_not_created() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("absent");
        assert!(matches!(
            Repository::open(&path),
            Err(OpenError::NotFound(_))
        ));
        assert!(!path.exists());
    }
}

// Compile the website's complete program as part of the ordinary doctest suite.
#[cfg(doctest)]
#[doc = include_str!("../site/src/content/docs/guides/open-a-repository.md")]
mod website_repository_guide {}