1use std::fs;
4use std::path::Path;
5
6use vpf::Need;
7
8use crate::folder;
9
10pub fn describe(need: &Need) -> String {
12 match need {
13 Need::Files { path, at_least } => match at_least {
14 Some(count) if *count > 1 => format!("at least {count} files matching `{path}`"),
15 _ => format!("`{path}`"),
16 },
17 Need::Folder { path } => format!("the folder `{path}`, with something in it"),
18 Need::Names { path, files } => {
19 format!("`{path}`, naming each file that matches `{files}`")
20 }
21 Need::Headings { path, headings } => format!(
22 "`{path}`, with words under the headings {}",
23 headings.join(", ")
24 ),
25 Need::Repository { path, branch } => match branch {
26 Some(branch) => format!("the repository `{path}` on the branch {branch}"),
27 None => format!("the repository `{path}`"),
28 },
29 }
30}
31
32pub fn meets(base: &Path, need: &Need) -> Result<(), String> {
38 for path in paths(need) {
39 if !folder::inside(path) {
40 return Err(format!("`{path}` leaves the folder"));
41 }
42 }
43 match need {
44 Need::Files { path, at_least } => {
45 let wanted = at_least.unwrap_or(1).max(1);
46 let found = folder::files(base, path).len();
47 if found >= wanted as usize {
48 Ok(())
49 } else if found == 0 {
50 Err(format!("no file matches `{path}`"))
51 } else {
52 Err(format!("{found} of {wanted} files match `{path}`"))
53 }
54 }
55 Need::Folder { path } => {
56 let full = base.join(path);
57 let filled = fs::read_dir(&full).is_ok_and(|mut read| read.next().is_some());
58 if filled {
59 Ok(())
60 } else if full.is_dir() {
61 Err(format!("the folder `{path}` is empty"))
62 } else {
63 Err(format!("there is no folder `{path}`"))
64 }
65 }
66 Need::Names { path, files } => {
67 let text = fs::read_to_string(base.join(path))
68 .map_err(|_| format!("there is no file `{path}`"))?;
69 let missing: Vec<String> = folder::files(base, files)
70 .iter()
71 .filter_map(|file| file.file_name()?.to_str().map(str::to_owned))
72 .filter(|name| !text.contains(name.as_str()))
73 .collect();
74 if missing.is_empty() {
75 Ok(())
76 } else {
77 Err(format!("`{path}` does not name {}", missing.join(", ")))
78 }
79 }
80 Need::Headings { path, headings } => {
81 let text = fs::read_to_string(base.join(path))
82 .map_err(|_| format!("there is no file `{path}`"))?;
83 let sections = sections(&text);
84 let mut wrong = Vec::new();
85 for heading in headings {
86 let wanted = heading.trim().to_lowercase();
87 match sections.iter().find(|(title, _)| *title == wanted) {
88 None => wrong.push(format!("`{path}` has no heading {heading}")),
89 Some((_, false)) => {
90 wrong.push(format!("`{path}` has no words under the heading {heading}"));
91 }
92 Some((_, true)) => {}
93 }
94 }
95 if wrong.is_empty() {
96 Ok(())
97 } else {
98 Err(wrong.join("; "))
99 }
100 }
101 Need::Repository { path, branch } => {
102 let head = head(&base.join(path)).ok_or(format!("`{path}` is not a repository"))?;
103 match branch {
104 None => Ok(()),
105 Some(branch) => {
106 let on = head.strip_prefix("ref: refs/heads/").map(str::trim);
107 match on {
108 Some(on) if on == branch => Ok(()),
109 Some(on) => Err(format!("`{path}` is on the branch {on}, not {branch}")),
110 None => Err(format!("`{path}` is on no branch, not {branch}")),
111 }
112 }
113 }
114 }
115 }
116}
117
118fn paths(need: &Need) -> Vec<&str> {
119 match need {
120 Need::Names { path, files } => vec![path, files],
121 other => vec![other.path()],
122 }
123}
124
125fn head(repository: &Path) -> Option<String> {
127 let git = repository.join(".git");
128 if git.is_dir() {
129 return fs::read_to_string(git.join("HEAD")).ok();
130 }
131 let pointer = fs::read_to_string(&git).ok()?;
132 let target = pointer.strip_prefix("gitdir:")?.trim();
133 fs::read_to_string(repository.join(target).join("HEAD")).ok()
134}
135
136fn sections(text: &str) -> Vec<(String, bool)> {
138 let mut found: Vec<(usize, String, bool)> = Vec::new();
139 let mut fenced = false;
140 for line in text.lines() {
141 let trimmed = line.trim();
142 if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
143 fenced = !fenced;
144 }
145 let level = trimmed.bytes().take_while(|byte| *byte == b'#').count();
146 let is_heading = !fenced && (1..=6).contains(&level) && trimmed[level..].starts_with(' ');
147 if is_heading {
148 let title = trimmed[level..].trim().trim_end_matches('#').trim();
149 found.push((level, title.to_lowercase(), false));
150 } else if !trimmed.is_empty() {
151 let mut deepest = usize::MAX;
153 for section in found.iter_mut().rev() {
154 if section.0 < deepest {
155 section.2 = true;
156 deepest = section.0;
157 }
158 }
159 }
160 }
161 found
162 .into_iter()
163 .map(|(_, title, words)| (title, words))
164 .collect()
165}