use std::fs;
use std::path::Path;
use vpf::Need;
use crate::folder;
pub fn describe(need: &Need) -> String {
match need {
Need::Files { path, at_least } => match at_least {
Some(count) if *count > 1 => format!("at least {count} files matching `{path}`"),
_ => format!("`{path}`"),
},
Need::Folder { path } => format!("the folder `{path}`, with something in it"),
Need::Names { path, files } => {
format!("`{path}`, naming each file that matches `{files}`")
}
Need::Headings { path, headings } => format!(
"`{path}`, with words under the headings {}",
headings.join(", ")
),
Need::Repository { path, branch } => match branch {
Some(branch) => format!("the repository `{path}` on the branch {branch}"),
None => format!("the repository `{path}`"),
},
}
}
pub fn meets(base: &Path, need: &Need) -> Result<(), String> {
for path in paths(need) {
if !folder::inside(path) {
return Err(format!("`{path}` leaves the folder"));
}
}
match need {
Need::Files { path, at_least } => {
let wanted = at_least.unwrap_or(1).max(1);
let found = folder::files(base, path).len();
if found >= wanted as usize {
Ok(())
} else if found == 0 {
Err(format!("no file matches `{path}`"))
} else {
Err(format!("{found} of {wanted} files match `{path}`"))
}
}
Need::Folder { path } => {
let full = base.join(path);
let filled = fs::read_dir(&full).is_ok_and(|mut read| read.next().is_some());
if filled {
Ok(())
} else if full.is_dir() {
Err(format!("the folder `{path}` is empty"))
} else {
Err(format!("there is no folder `{path}`"))
}
}
Need::Names { path, files } => {
let text = fs::read_to_string(base.join(path))
.map_err(|_| format!("there is no file `{path}`"))?;
let missing: Vec<String> = folder::files(base, files)
.iter()
.filter_map(|file| file.file_name()?.to_str().map(str::to_owned))
.filter(|name| !text.contains(name.as_str()))
.collect();
if missing.is_empty() {
Ok(())
} else {
Err(format!("`{path}` does not name {}", missing.join(", ")))
}
}
Need::Headings { path, headings } => {
let text = fs::read_to_string(base.join(path))
.map_err(|_| format!("there is no file `{path}`"))?;
let sections = sections(&text);
let mut wrong = Vec::new();
for heading in headings {
let wanted = heading.trim().to_lowercase();
match sections.iter().find(|(title, _)| *title == wanted) {
None => wrong.push(format!("`{path}` has no heading {heading}")),
Some((_, false)) => {
wrong.push(format!("`{path}` has no words under the heading {heading}"));
}
Some((_, true)) => {}
}
}
if wrong.is_empty() {
Ok(())
} else {
Err(wrong.join("; "))
}
}
Need::Repository { path, branch } => {
let head = head(&base.join(path)).ok_or(format!("`{path}` is not a repository"))?;
match branch {
None => Ok(()),
Some(branch) => {
let on = head.strip_prefix("ref: refs/heads/").map(str::trim);
match on {
Some(on) if on == branch => Ok(()),
Some(on) => Err(format!("`{path}` is on the branch {on}, not {branch}")),
None => Err(format!("`{path}` is on no branch, not {branch}")),
}
}
}
}
}
}
fn paths(need: &Need) -> Vec<&str> {
match need {
Need::Names { path, files } => vec![path, files],
other => vec![other.path()],
}
}
fn head(repository: &Path) -> Option<String> {
let git = repository.join(".git");
if git.is_dir() {
return fs::read_to_string(git.join("HEAD")).ok();
}
let pointer = fs::read_to_string(&git).ok()?;
let target = pointer.strip_prefix("gitdir:")?.trim();
fs::read_to_string(repository.join(target).join("HEAD")).ok()
}
fn sections(text: &str) -> Vec<(String, bool)> {
let mut found: Vec<(usize, String, bool)> = Vec::new();
let mut fenced = false;
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
fenced = !fenced;
}
let level = trimmed.bytes().take_while(|byte| *byte == b'#').count();
let is_heading = !fenced && (1..=6).contains(&level) && trimmed[level..].starts_with(' ');
if is_heading {
let title = trimmed[level..].trim().trim_end_matches('#').trim();
found.push((level, title.to_lowercase(), false));
} else if !trimmed.is_empty() {
let mut deepest = usize::MAX;
for section in found.iter_mut().rev() {
if section.0 < deepest {
section.2 = true;
deepest = section.0;
}
}
}
}
found
.into_iter()
.map(|(_, title, words)| (title, words))
.collect()
}