use std::{
collections::BTreeSet,
path::{Path, PathBuf},
};
use crate::{Error, RepoPath, RepoRoot, Result};
pub fn discover_root(cwd: &Path, given: Option<&Path>) -> Result<RepoRoot> {
if let Some(dir) = given {
let abs = std::path::absolute(dir).map_err(|e| Error::io(dir, e))?;
if !abs.is_dir() {
return Err(Error::io(
&abs,
std::io::Error::new(std::io::ErrorKind::NotFound, "no such directory"),
));
}
let canonical = dunce::canonicalize(&abs).map_err(|e| Error::io(&abs, e))?;
return Ok(RepoRoot::new(canonical));
}
let abs = std::path::absolute(cwd).map_err(|e| Error::io(cwd, e))?;
abs.ancestors()
.find(|dir| dir.join(".git").exists())
.map(|dir| RepoRoot::new(dir.to_path_buf()))
.ok_or(Error::NoRepository)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Scope {
pub files: BTreeSet<RepoPath>,
pub dirs: BTreeSet<RepoPath>,
}
impl Scope {
pub fn all() -> Self {
let mut s = Scope::default();
s.dirs.insert(RepoPath::root());
s
}
pub fn contains(&self, path: &RepoPath) -> bool {
self.files.contains(path) || self.dirs.iter().any(|d| path.starts_with(d))
}
pub fn add(&mut self, path: RepoPath) {
self.files.insert(path);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PathArg<'a>(pub &'a str);
impl PathArg<'_> {
pub fn resolve(&self, root: &RepoRoot, cwd: &Path) -> Option<RepoPath> {
let arg = self.0;
let dir_only = arg.len() > 1 && arg.ends_with('/');
let found = if arg.starts_with('/') {
let trimmed = if dir_only {
arg.trim_end_matches('/')
} else {
arg
};
match RepoPath::parse(trimmed) {
Some(spec) if spec.to_fs(root).exists() => Some(spec),
_ => Self::existing(root, Path::new(arg)),
}
} else {
Self::existing(root, &cwd.join(arg))
};
found.filter(|p| !dir_only || p.to_fs(root).is_dir())
}
pub fn resolve_new(&self, root: &RepoRoot, cwd: &Path) -> Option<RepoPath> {
if let Some(found) = self.resolve(root, cwd) {
return Some(found);
}
let arg = if self.0.len() > 1 {
self.0.trim_end_matches('/')
} else {
self.0
};
if !arg.starts_with('/') {
return RepoPath::from_fs(root, &cwd.join(arg));
}
let under_root = root.as_path().to_str().is_some_and(|r| {
arg == r
|| arg
.strip_prefix(r)
.is_some_and(|rest| rest.starts_with('/'))
});
if under_root {
RepoPath::from_fs(root, Path::new(arg))
} else {
RepoPath::parse(arg)
}
}
fn existing(root: &RepoRoot, fs: &Path) -> Option<RepoPath> {
RepoPath::from_fs(root, fs).filter(|p| p.to_fs(root).exists())
}
}
pub fn resolve_paths(root: &RepoRoot, cwd: &Path, paths: &[PathBuf]) -> Result<Scope> {
if paths.is_empty() {
return Ok(Scope::all());
}
let mut scope = Scope::default();
for path in paths {
let shown = path.display().to_string();
let repo_path = path
.to_str()
.and_then(|s| PathArg(s).resolve(root, cwd))
.ok_or(Error::Path(shown))?;
if repo_path.to_fs(root).is_dir() {
scope.dirs.insert(repo_path);
} else {
scope.files.insert(repo_path);
}
}
Ok(scope)
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
fn temp(name: &str) -> PathBuf {
let dir = crate::test_support::fresh_dir(&format!("root-{name}"));
fs::create_dir_all(dir.join("k/sub")).unwrap();
fs::write(dir.join("k/a.md"), "").unwrap();
dir
}
#[test]
fn discovers_the_git_ancestor_or_takes_the_given_root() {
let dir = temp("discover");
assert!(matches!(
discover_root(&dir.join("k/sub"), None),
Err(Error::NoRepository)
));
fs::write(dir.join(".git"), "gitdir: elsewhere").unwrap();
assert_eq!(
discover_root(&dir.join("k/sub"), None).unwrap().as_path(),
dir
);
assert_eq!(
discover_root(&dir.join("k/sub"), Some(&dir.join("k")))
.unwrap()
.as_path(),
dunce::canonicalize(dir.join("k")).unwrap()
);
assert!(discover_root(&dir, Some(&dir.join("nope"))).is_err());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn resolves_paths_into_files_and_dirs() {
let dir = temp("paths");
let root = RepoRoot::new(dir.clone());
let scope = resolve_paths(&root, &dir, &["k/a.md".into(), "k/sub".into()]).unwrap();
assert!(scope.files.contains(&RepoPath::parse("/k/a.md").unwrap()));
assert!(scope.dirs.contains(&RepoPath::parse("/k/sub").unwrap()));
assert!(scope.contains(&RepoPath::parse("/k/sub/x.md").unwrap()));
assert!(!scope.contains(&RepoPath::parse("/k/b.md").unwrap()));
let scope = resolve_paths(&root, &dir.join("k"), &["a.md".into()]).unwrap();
assert!(scope.contains(&RepoPath::parse("/k/a.md").unwrap()));
let scope = resolve_paths(&root, &dir, &[dir.join("k")]).unwrap();
assert!(scope.dirs.contains(&RepoPath::parse("/k").unwrap()));
assert!(matches!(
resolve_paths(&root, &dir, &["k/missing.md".into()]),
Err(Error::Path(_))
));
assert!(matches!(
resolve_paths(&root, &dir, &["../outside".into()]),
Err(Error::Path(_))
));
assert_eq!(resolve_paths(&root, &dir, &[]).unwrap(), Scope::all());
let scope = resolve_paths(&root, &dir.join("k/sub"), &["/k/a.md".into()]).unwrap();
assert!(scope.files.contains(&RepoPath::parse("/k/a.md").unwrap()));
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_path_argument_has_two_spellings() {
let dir = temp("patharg");
let root = RepoRoot::new(dir.clone());
let p = |s: &str| RepoPath::parse(s).unwrap();
assert_eq!(PathArg("/k/a.md").resolve(&root, &dir), Some(p("/k/a.md")));
assert_eq!(PathArg("/k/sub/").resolve(&root, &dir), Some(p("/k/sub")));
assert_eq!(PathArg("/k/a.md/").resolve(&root, &dir), None);
assert_eq!(PathArg("a.md/").resolve(&root, &dir.join("k")), None);
assert_eq!(PathArg("/").resolve(&root, &dir), Some(p("/")));
let abs = dir.join("k/a.md");
assert_eq!(
PathArg(abs.to_str().unwrap()).resolve(&root, &dir),
Some(p("/k/a.md"))
);
assert_eq!(
PathArg(dir.to_str().unwrap()).resolve(&root, &dir),
Some(p("/"))
);
assert_eq!(
PathArg("a.md").resolve(&root, &dir.join("k")),
Some(p("/k/a.md"))
);
assert_eq!(
PathArg("./a.md").resolve(&root, &dir.join("k")),
Some(p("/k/a.md"))
);
assert_eq!(
PathArg("sub/").resolve(&root, &dir.join("k")),
Some(p("/k/sub"))
);
assert_eq!(PathArg("..").resolve(&root, &dir.join("k")), Some(p("/")));
assert_eq!(PathArg("/k/missing.md").resolve(&root, &dir), None);
assert_eq!(PathArg("missing.md").resolve(&root, &dir), None);
assert_eq!(PathArg("../outside").resolve(&root, &dir), None);
assert_eq!(PathArg("/definitely/not/here").resolve(&root, &dir), None);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_new_path_resolves_in_every_spelling() {
let dir = temp("new");
let root = RepoRoot::new(dir.clone());
let p = |s: &str| RepoPath::parse(s).unwrap();
assert_eq!(PathArg("k/sub").resolve_new(&root, &dir), Some(p("/k/sub")));
assert_eq!(
PathArg("/k/a.md").resolve_new(&root, &dir),
Some(p("/k/a.md"))
);
assert_eq!(
PathArg("/docs/kb").resolve_new(&root, &dir),
Some(p("/docs/kb"))
);
assert_eq!(
PathArg("/docs/kb/").resolve_new(&root, &dir),
Some(p("/docs/kb"))
);
let abs = dir.join("docs/kb");
assert_eq!(
PathArg(abs.to_str().unwrap()).resolve_new(&root, &dir),
Some(p("/docs/kb"))
);
assert_eq!(
PathArg("/definitely/not/here").resolve_new(&root, &dir),
Some(p("/definitely/not/here"))
);
assert_eq!(
PathArg("kb").resolve_new(&root, &dir.join("k")),
Some(p("/k/kb"))
);
assert_eq!(
PathArg("new/dir/").resolve_new(&root, &dir),
Some(p("/new/dir"))
);
assert_eq!(PathArg("../outside").resolve_new(&root, &dir), None);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn scope_all_contains_everything_and_add_names_a_file() {
let all = Scope::all();
assert!(all.contains(&RepoPath::parse("/x/y.md").unwrap()));
let mut s = Scope::default();
assert!(!s.contains(&RepoPath::parse("/x.md").unwrap()));
s.add(RepoPath::parse("/x.md").unwrap());
assert!(s.contains(&RepoPath::parse("/x.md").unwrap()));
}
}