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
//! Parent traversal with an optional inclusive ceiling.
use std::path::Path;
use super::{OpenError, Repository, canonical, io_error, malformed};
impl Repository {
/// Finds the nearest repository at or above an existing directory.
///
/// Searches the canonical start and its parents through the filesystem root, crossing mount
/// points. Symlinks therefore follow physical ancestry. An explicit `.git` entry, or `HEAD`
/// together with both `objects` and `refs` (or linked `commondir`), marks a candidate.
/// Lone ordinary names and partial bare layouts allow ancestor search; recognized malformed
/// or unsupported candidates stop the search. Ordinary,
/// bare, separate-Git-directory and linked-worktree layouts use [`Self::open`]'s rules.
/// No environment variables, ownership checks, or Git discovery configuration are consulted.
/// Use [`Self::discover_with_ceiling`] to restrict the ancestor search.
///
/// # Errors
///
/// Returns [`OpenError::NotFound`] for an absent start or no candidate, and
/// [`OpenError::Malformed`] for a non-directory start. Candidate errors are propagated without
/// falling back to an outer repository. No files are changed. Reads are synchronous and have
/// the same unbounded metadata allocation and trusted-path assumptions as [`Self::open`].
///
/// ```
/// use girt::{InitKind, ObjectFormat, OpenError, Repository};
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("project");
/// Repository::init(ObjectFormat::Sha1, &path, InitKind::Worktree)?;
/// let nested = path.join("src");
/// std::fs::create_dir(&nested)?;
/// assert!(matches!(
/// Repository::open(&nested),
/// Err(OpenError::NotFound(_))
/// ));
/// // Explicit opening stays at the supplied location; discovery can select an ancestor.
/// assert_eq!(
/// Repository::discover(&nested)?.worktree(),
/// Some(path.canonicalize()?.as_path())
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn discover(start: impl AsRef<Path>) -> Result<Self, OpenError> {
discover(start.as_ref(), None)
}
/// Finds a repository between an existing directory and an inclusive ancestor ceiling.
///
/// Both paths are canonicalized before testing ancestry. The ceiling itself is searched, but
/// its parents are not. The ceiling limits candidate locations; gitfiles and linked-worktree
/// metadata may point outside it. All other rules are those of [`Self::discover`].
///
/// # Errors
///
/// In addition to [`Self::discover`]'s failures, returns [`OpenError::Malformed`] if the
/// ceiling is not an ancestor of the start (or the same directory), and I/O errors for
/// inaccessible paths. An absent ceiling returns [`OpenError::NotFound`]. No files are
/// changed.
///
/// ```
/// use girt::{InitKind, ObjectFormat, OpenError, Repository};
/// let directory = tempfile::tempdir()?;
/// Repository::init(ObjectFormat::Sha1, directory.path(), InitKind::Worktree)?;
/// let child = directory.path().join("unrelated");
/// std::fs::create_dir(&child)?;
/// // A ceiling at the child deliberately excludes the enclosing repository.
/// assert!(matches!(
/// Repository::discover_with_ceiling(&child, &child),
/// Err(OpenError::NotFound(_)),
/// ));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn discover_with_ceiling(
start: impl AsRef<Path>,
ceiling: impl AsRef<Path>,
) -> Result<Self, OpenError> {
discover(start.as_ref(), Some(ceiling.as_ref()))
}
}
fn discover(start: &Path, ceiling: Option<&Path>) -> Result<Repository, OpenError> {
let start = directory(start)?;
let ceiling = ceiling.map(directory).transpose()?;
if ceiling
.as_ref()
.is_some_and(|ceiling| !start.starts_with(ceiling))
{
return Err(malformed(
ceiling.as_deref().unwrap(),
"discovery ceiling is not an ancestor",
));
}
for candidate in start.ancestors() {
if is_candidate(candidate)? {
return Repository::open(candidate);
}
if ceiling.as_deref() == Some(candidate) {
break;
}
}
Err(OpenError::NotFound(start))
}
fn directory(path: &Path) -> Result<std::path::PathBuf, OpenError> {
match std::fs::metadata(path) {
Ok(metadata) if metadata.is_dir() => canonical(path),
Ok(_) => Err(malformed(path, "discovery requires a directory")),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
Err(OpenError::NotFound(path.into()))
}
Err(error) => Err(io_error(path, error)),
}
}
fn is_candidate(path: &Path) -> Result<bool, OpenError> {
Ok(marker_exists(path, ".git")?
|| (marker_exists(path, "HEAD")?
&& ((marker_exists(path, "objects")? && marker_exists(path, "refs")?)
|| marker_exists(path, "commondir")?)))
}
fn marker_exists(path: &Path, name: &str) -> Result<bool, OpenError> {
let marker = path.join(name);
match std::fs::symlink_metadata(&marker) {
Ok(_) => Ok(true),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(io_error(&marker, error)),
}
}
// Initialization deliberately refuses even ambiguous markers before writing anything.
pub(super) fn has_marker(path: &Path) -> Result<bool, OpenError> {
for name in [".git", "HEAD", "objects"] {
if marker_exists(path, name)? {
return Ok(true);
}
}
Ok(false)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::InitKind;
#[test]
fn ceiling_is_inclusive_and_stops_parent_search() {
let root = tempfile::tempdir().unwrap();
let outer =
Repository::init(crate::ObjectFormat::Sha1, root.path(), InitKind::Worktree).unwrap();
let child = root.path().join("child");
std::fs::create_dir(&child).unwrap();
assert!(matches!(
Repository::discover_with_ceiling(&child, &child),
Err(OpenError::NotFound(_))
));
assert_eq!(
Repository::discover_with_ceiling(&child, root.path())
.unwrap()
.git_dir(),
outer.git_dir()
);
}
#[test]
fn nearest_repository_wins() {
let root = tempfile::tempdir().unwrap();
Repository::init(crate::ObjectFormat::Sha1, root.path(), InitKind::Worktree).unwrap();
let inner = Repository::init(
crate::ObjectFormat::Sha1,
root.path().join("inner"),
InitKind::Worktree,
)
.unwrap();
assert_eq!(
Repository::discover(inner.worktree().unwrap())
.unwrap()
.git_dir(),
inner.git_dir()
);
}
#[test]
fn rejects_non_ancestor_ceiling() {
let root = tempfile::tempdir().unwrap();
let child = root.path().join("child");
std::fs::create_dir(&child).unwrap();
assert!(matches!(
Repository::discover_with_ceiling(root.path(), &child),
Err(OpenError::Malformed { .. })
));
}
#[test]
fn malformed_inner_marker_prevents_outer_fallback() {
let root = tempfile::tempdir().unwrap();
Repository::init(crate::ObjectFormat::Sha1, root.path(), InitKind::Worktree).unwrap();
let child = root.path().join("child");
std::fs::create_dir(&child).unwrap();
std::fs::write(child.join(".git"), b"invalid\n").unwrap();
assert!(matches!(
Repository::discover(&child),
Err(OpenError::Malformed { .. })
));
assert_eq!(std::fs::read(child.join(".git")).unwrap(), b"invalid\n");
}
#[test]
fn start_must_be_an_existing_directory() {
let root = tempfile::tempdir().unwrap();
let file = root.path().join("file");
std::fs::write(&file, b"keep").unwrap();
assert!(matches!(
Repository::discover(&file),
Err(OpenError::Malformed { .. })
));
assert!(matches!(
Repository::discover(root.path().join("missing")),
Err(OpenError::NotFound(_))
));
}
#[test]
fn empty_search_is_read_only() {
let root = tempfile::tempdir().unwrap();
assert!(matches!(
Repository::discover_with_ceiling(root.path(), root.path()),
Err(OpenError::NotFound(_))
));
assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0);
}
#[cfg(unix)]
#[test]
fn symlink_start_uses_physical_ancestry() {
let root = tempfile::tempdir().unwrap();
let repo = Repository::init(
crate::ObjectFormat::Sha1,
root.path().join("physical"),
InitKind::Worktree,
)
.unwrap();
let nested = root.path().join("physical/nested");
std::fs::create_dir(&nested).unwrap();
let alias = root.path().join("alias");
std::os::unix::fs::symlink(&nested, &alias).unwrap();
assert_eq!(
Repository::discover(&alias).unwrap().git_dir(),
repo.git_dir()
);
assert_eq!(
Repository::discover_with_ceiling(&alias, repo.worktree().unwrap())
.unwrap()
.git_dir(),
repo.git_dir()
);
}
#[cfg(unix)]
#[test]
fn dangling_gitfile_symlink_stops_search() {
let root = tempfile::tempdir().unwrap();
Repository::init(crate::ObjectFormat::Sha1, root.path(), InitKind::Worktree).unwrap();
let child = root.path().join("child");
std::fs::create_dir(&child).unwrap();
std::os::unix::fs::symlink("missing", child.join(".git")).unwrap();
assert!(Repository::discover(&child).is_err());
}
}