1use std::{
5 collections::BTreeSet,
6 path::{Path, PathBuf},
7};
8
9use crate::{Error, RepoPath, RepoRoot, Result};
10
11pub fn discover_root(cwd: &Path, given: Option<&Path>) -> Result<RepoRoot> {
24 if let Some(dir) = given {
25 let abs = std::path::absolute(dir).map_err(|e| Error::io(dir, e))?;
26 if !abs.is_dir() {
27 return Err(Error::io(
28 &abs,
29 std::io::Error::new(std::io::ErrorKind::NotFound, "no such directory"),
30 ));
31 }
32 let canonical = dunce::canonicalize(&abs).map_err(|e| Error::io(&abs, e))?;
33 return Ok(RepoRoot::new(canonical));
34 }
35 let abs = std::path::absolute(cwd).map_err(|e| Error::io(cwd, e))?;
36 abs.ancestors()
37 .find(|dir| holds_git(dir))
38 .map(|dir| RepoRoot::new(dir.to_path_buf()))
39 .ok_or(Error::NoRepository)
40}
41
42pub fn holds_git(dir: &Path) -> bool {
45 dir.join(".git").exists()
46}
47
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
52pub struct Scope {
53 pub files: BTreeSet<RepoPath>,
55 pub dirs: BTreeSet<RepoPath>,
57}
58
59impl Scope {
60 pub fn all() -> Self {
62 let mut s = Scope::default();
63 s.dirs.insert(RepoPath::root());
64 s
65 }
66
67 pub fn contains(&self, path: &RepoPath) -> bool {
70 self.files.contains(path) || self.dirs.iter().any(|d| path.starts_with(d))
71 }
72
73 pub fn add(&mut self, path: RepoPath) {
76 self.files.insert(path);
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct PathArg<'a>(pub &'a str);
84
85impl PathArg<'_> {
86 pub fn resolve(&self, root: &RepoRoot, cwd: &Path) -> Option<RepoPath> {
94 let arg = self.0;
95 let dir_only = arg.len() > 1 && arg.ends_with('/');
96 let found = if arg.starts_with('/') {
97 let trimmed = if dir_only {
98 arg.trim_end_matches('/')
99 } else {
100 arg
101 };
102 match RepoPath::parse(trimmed) {
103 Some(spec) if spec.to_fs(root).exists() => Some(spec),
104 _ => Self::existing(root, Path::new(arg)),
105 }
106 } else {
107 Self::existing(root, &cwd.join(arg))
108 };
109 found.filter(|p| !dir_only || p.to_fs(root).is_dir())
110 }
111
112 pub fn resolve_new(&self, root: &RepoRoot, cwd: &Path) -> Option<RepoPath> {
121 if let Some(found) = self.resolve(root, cwd) {
122 return Some(found);
123 }
124 let arg = if self.0.len() > 1 {
125 self.0.trim_end_matches('/')
126 } else {
127 self.0
128 };
129 if !arg.starts_with('/') {
130 return RepoPath::from_fs(root, &cwd.join(arg));
131 }
132 let under_root = root.as_path().to_str().is_some_and(|r| {
133 arg == r
134 || arg
135 .strip_prefix(r)
136 .is_some_and(|rest| rest.starts_with('/'))
137 });
138 if under_root {
139 RepoPath::from_fs(root, Path::new(arg))
140 } else {
141 RepoPath::parse(arg)
142 }
143 }
144
145 fn existing(root: &RepoRoot, fs: &Path) -> Option<RepoPath> {
146 RepoPath::from_fs(root, fs).filter(|p| p.to_fs(root).exists())
147 }
148}
149
150pub fn resolve_paths(root: &RepoRoot, cwd: &Path, paths: &[PathBuf]) -> Result<Scope> {
154 if paths.is_empty() {
155 return Ok(Scope::all());
156 }
157 let mut scope = Scope::default();
158 for path in paths {
159 let shown = path.display().to_string();
160 let repo_path = path
161 .to_str()
162 .and_then(|s| PathArg(s).resolve(root, cwd))
163 .ok_or(Error::Path(shown))?;
164 if repo_path.to_fs(root).is_dir() {
165 scope.dirs.insert(repo_path);
166 } else {
167 scope.files.insert(repo_path);
168 }
169 }
170 Ok(scope)
171}
172
173#[cfg(test)]
174mod tests {
175 use std::fs;
176
177 use super::*;
178
179 fn temp(name: &str) -> PathBuf {
180 let dir = crate::test_support::fresh_dir(&format!("root-{name}"));
181 fs::create_dir_all(dir.join("k/sub")).unwrap();
182 fs::write(dir.join("k/a.md"), "").unwrap();
183 dir
184 }
185
186 #[test]
188 fn discovers_the_git_ancestor_or_takes_the_given_root() {
189 let dir = temp("discover");
190 assert!(matches!(
191 discover_root(&dir.join("k/sub"), None),
192 Err(Error::NoRepository)
193 ));
194 fs::write(dir.join(".git"), "gitdir: elsewhere").unwrap();
195 assert_eq!(
196 discover_root(&dir.join("k/sub"), None).unwrap().as_path(),
197 dir
198 );
199 assert_eq!(
200 discover_root(&dir.join("k/sub"), Some(&dir.join("k")))
201 .unwrap()
202 .as_path(),
203 dunce::canonicalize(dir.join("k")).unwrap()
204 );
205 assert!(discover_root(&dir, Some(&dir.join("nope"))).is_err());
206 fs::remove_dir_all(&dir).unwrap();
207 }
208
209 #[test]
210 fn resolves_paths_into_files_and_dirs() {
211 let dir = temp("paths");
212 let root = RepoRoot::new(dir.clone());
213 let scope = resolve_paths(&root, &dir, &["k/a.md".into(), "k/sub".into()]).unwrap();
214 assert!(scope.files.contains(&RepoPath::parse("/k/a.md").unwrap()));
215 assert!(scope.dirs.contains(&RepoPath::parse("/k/sub").unwrap()));
216 assert!(scope.contains(&RepoPath::parse("/k/sub/x.md").unwrap()));
217 assert!(!scope.contains(&RepoPath::parse("/k/b.md").unwrap()));
218 let scope = resolve_paths(&root, &dir.join("k"), &["a.md".into()]).unwrap();
220 assert!(scope.contains(&RepoPath::parse("/k/a.md").unwrap()));
221 let scope = resolve_paths(&root, &dir, &[dir.join("k")]).unwrap();
223 assert!(scope.dirs.contains(&RepoPath::parse("/k").unwrap()));
224 assert!(matches!(
225 resolve_paths(&root, &dir, &["k/missing.md".into()]),
226 Err(Error::Path(_))
227 ));
228 assert!(matches!(
229 resolve_paths(&root, &dir, &["../outside".into()]),
230 Err(Error::Path(_))
231 ));
232 assert_eq!(resolve_paths(&root, &dir, &[]).unwrap(), Scope::all());
233 let scope = resolve_paths(&root, &dir.join("k/sub"), &["/k/a.md".into()]).unwrap();
235 assert!(scope.files.contains(&RepoPath::parse("/k/a.md").unwrap()));
236 fs::remove_dir_all(&dir).unwrap();
237 }
238
239 #[test]
242 fn a_path_argument_has_two_spellings() {
243 let dir = temp("patharg");
244 let root = RepoRoot::new(dir.clone());
245 let p = |s: &str| RepoPath::parse(s).unwrap();
246 assert_eq!(PathArg("/k/a.md").resolve(&root, &dir), Some(p("/k/a.md")));
248 assert_eq!(PathArg("/k/sub/").resolve(&root, &dir), Some(p("/k/sub")));
249 assert_eq!(PathArg("/k/a.md/").resolve(&root, &dir), None);
251 assert_eq!(PathArg("a.md/").resolve(&root, &dir.join("k")), None);
252 assert_eq!(PathArg("/").resolve(&root, &dir), Some(p("/")));
253 let abs = dir.join("k/a.md");
256 assert_eq!(
257 PathArg(abs.to_str().unwrap()).resolve(&root, &dir),
258 Some(p("/k/a.md"))
259 );
260 assert_eq!(
261 PathArg(dir.to_str().unwrap()).resolve(&root, &dir),
262 Some(p("/"))
263 );
264 assert_eq!(
266 PathArg("a.md").resolve(&root, &dir.join("k")),
267 Some(p("/k/a.md"))
268 );
269 assert_eq!(
270 PathArg("./a.md").resolve(&root, &dir.join("k")),
271 Some(p("/k/a.md"))
272 );
273 assert_eq!(
274 PathArg("sub/").resolve(&root, &dir.join("k")),
275 Some(p("/k/sub"))
276 );
277 assert_eq!(PathArg("..").resolve(&root, &dir.join("k")), Some(p("/")));
278 assert_eq!(PathArg("/k/missing.md").resolve(&root, &dir), None);
281 assert_eq!(PathArg("missing.md").resolve(&root, &dir), None);
282 assert_eq!(PathArg("../outside").resolve(&root, &dir), None);
283 assert_eq!(PathArg("/definitely/not/here").resolve(&root, &dir), None);
284 fs::remove_dir_all(&dir).unwrap();
285 }
286
287 #[test]
290 fn a_new_path_resolves_in_every_spelling() {
291 let dir = temp("new");
292 let root = RepoRoot::new(dir.clone());
293 let p = |s: &str| RepoPath::parse(s).unwrap();
294 assert_eq!(PathArg("k/sub").resolve_new(&root, &dir), Some(p("/k/sub")));
296 assert_eq!(
297 PathArg("/k/a.md").resolve_new(&root, &dir),
298 Some(p("/k/a.md"))
299 );
300 assert_eq!(
302 PathArg("/docs/kb").resolve_new(&root, &dir),
303 Some(p("/docs/kb"))
304 );
305 assert_eq!(
306 PathArg("/docs/kb/").resolve_new(&root, &dir),
307 Some(p("/docs/kb"))
308 );
309 let abs = dir.join("docs/kb");
311 assert_eq!(
312 PathArg(abs.to_str().unwrap()).resolve_new(&root, &dir),
313 Some(p("/docs/kb"))
314 );
315 assert_eq!(
317 PathArg("/definitely/not/here").resolve_new(&root, &dir),
318 Some(p("/definitely/not/here"))
319 );
320 assert_eq!(
323 PathArg("kb").resolve_new(&root, &dir.join("k")),
324 Some(p("/k/kb"))
325 );
326 assert_eq!(
327 PathArg("new/dir/").resolve_new(&root, &dir),
328 Some(p("/new/dir"))
329 );
330 assert_eq!(PathArg("../outside").resolve_new(&root, &dir), None);
331 fs::remove_dir_all(&dir).unwrap();
332 }
333
334 #[test]
335 fn scope_all_contains_everything_and_add_names_a_file() {
336 let all = Scope::all();
337 assert!(all.contains(&RepoPath::parse("/x/y.md").unwrap()));
338 let mut s = Scope::default();
339 assert!(!s.contains(&RepoPath::parse("/x.md").unwrap()));
340 s.add(RepoPath::parse("/x.md").unwrap());
341 assert!(s.contains(&RepoPath::parse("/x.md").unwrap()));
342 }
343}