use crate::tokens::Error;
use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
const EMPTY: &str = "holds no git-tracked file -- name a file inside it, \
or track what is there";
pub(crate) fn select(
root: &Path,
paths: &[String],
) -> Result<Vec<PathBuf>, Error> {
rooted(root, paths.is_empty())?;
if paths.is_empty() {
return Ok(tracked(root));
}
let mut seen = BTreeSet::new();
let mut chosen = Vec::new();
for shown in paths {
for full in named(root, shown)? {
if seen.insert(lexical(&full)) {
chosen.push(full);
}
}
}
Ok(chosen)
}
fn rooted(root: &Path, bare: bool) -> Result<(), Error> {
let refused = |reason: &str| Error {
path: root.to_owned(),
reason: reason.to_owned(),
};
if !root.is_dir() {
return Err(refused(NOT_A_DIR));
}
if bare && !in_work_tree(root) {
return Err(refused(NO_GIT));
}
Ok(())
}
const NOT_A_DIR: &str = "is not a directory";
const NO_GIT: &str = "is not inside a git work tree, so there is no \
tracked fileset -- name the files to check";
fn in_work_tree(root: &Path) -> bool {
let full = root.canonicalize().unwrap_or_else(|_| root.to_owned());
full.ancestors().any(|dir| dir.join(".git").exists())
}
fn tracked(root: &Path) -> Vec<PathBuf> {
itok::walk::tracked(root)
.iter()
.map(|f| root.join(f))
.filter(|full| !is_link(full) && full.exists())
.collect()
}
fn is_link(full: &Path) -> bool {
std::fs::symlink_metadata(full).is_ok_and(|m| m.file_type().is_symlink())
}
fn named(root: &Path, shown: &str) -> Result<Vec<PathBuf>, Error> {
let full = root.join(shown);
let meta = std::fs::metadata(&full).map_err(|e| Error {
path: full.clone(),
reason: e.to_string(),
})?;
if meta.is_dir() {
return under(root, full);
}
Ok(vec![full])
}
fn under(root: &Path, full: PathBuf) -> Result<Vec<PathBuf>, Error> {
let dir = within(root, &full)?;
let inside: Vec<PathBuf> = tracked(root)
.into_iter()
.filter(|path| lexical(path).starts_with(&dir))
.collect();
if inside.is_empty() {
return Err(Error {
path: full,
reason: EMPTY.to_owned(),
});
}
Ok(inside)
}
fn within(root: &Path, full: &Path) -> Result<PathBuf, Error> {
let refused = |reason: String| Error {
path: full.to_owned(),
reason,
};
let base = root.canonicalize().map_err(|e| refused(e.to_string()))?;
let real = full.canonicalize().map_err(|e| refused(e.to_string()))?;
let rel = real
.strip_prefix(&base)
.map_err(|_| refused(OUTSIDE.to_owned()))?;
Ok(lexical(&root.join(rel)))
}
const OUTSIDE: &str = "resolves outside the run root, where nothing is \
git-tracked -- name the files inside it";
#[must_use]
pub(crate) fn lexical(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for part in path.components() {
let named =
matches!(out.components().next_back(), Some(Component::Normal(_)));
match part {
Component::CurDir => {}
Component::ParentDir if named => {
out.pop();
}
other => out.push(other),
}
}
out
}
#[cfg(test)]
#[path = "fileset_test.rs"]
mod tests;