1use std::collections::{HashMap, VecDeque};
7use std::path::{Path, PathBuf};
8
9use crate::error::{Error, Issue, Result, code};
10use crate::ignore::IgnoreSet;
11use crate::meta::{Meta, MetaLoad, load};
12use crate::util::{self, META_FILE};
13
14pub const HARD_MAX_DEPTH: usize = 128;
16
17pub struct Visit {
19 pub dir: PathBuf,
21 pub rel: String,
23 pub depth: usize,
25 pub meta: Option<Box<Meta>>,
27 pub parent: Option<usize>,
29 pub readable: bool,
31 pub hard_link_to: Option<String>,
36}
37
38pub struct Scan {
40 pub root: PathBuf,
42 pub visits: Vec<Visit>,
44 pub issues: Vec<Issue>,
46 pub by_id: HashMap<String, Vec<usize>>,
48 pub root_index: Option<usize>,
50 pub max_depth: usize,
52 pub ignore: IgnoreSet,
54}
55
56impl Scan {
57 pub fn resolve(&self, id: &str) -> Option<usize> {
59 self.by_id.get(id).and_then(|v| v.first().copied())
60 }
61
62 pub fn ancestors(&self, mut idx: usize) -> Vec<usize> {
64 let mut out = vec![idx];
65 while let Some(p) = self.visits[idx].parent {
66 out.push(p);
67 idx = p;
68 }
69 out.reverse();
70 out
71 }
72}
73
74#[derive(Debug, Clone)]
76pub struct Bundle {
77 pub root: PathBuf,
79}
80
81impl Bundle {
82 pub fn new(root: impl Into<PathBuf>) -> Result<Self> {
84 let root = root.into();
85 if !root.exists() {
86 return Err(Error::NotFound(root.display().to_string()));
87 }
88 if !root.is_dir() {
89 return Err(Error::BadArg(format!(
90 "{} 不是目录(`.str` 是目录 bundle)",
91 root.display()
92 )));
93 }
94 let root = std::fs::canonicalize(&root).map_err(|e| Error::io(&root, e))?;
97 Ok(Self { root })
98 }
99
100 pub fn name(&self) -> String {
102 self.root
103 .file_name()
104 .map(|s| s.to_string_lossy().to_string())
105 .unwrap_or_else(|| self.root.display().to_string())
106 }
107
108 pub fn meta_path(&self, dir: &Path) -> PathBuf {
110 dir.join(META_FILE)
111 }
112
113 pub fn has_meta(&self, dir: &Path) -> bool {
115 self.meta_path(dir).is_file()
116 }
117
118 pub fn rel(&self, path: &Path) -> String {
120 util::rel_display(&self.root, path)
121 }
122
123 pub fn read_meta(&self, dir: &Path) -> Result<MetaLoad> {
125 let p = self.meta_path(dir);
126 let rel = self.rel(&p);
127 load(&p, &rel)
128 }
129
130 pub fn list_names(&self, dir: &Path) -> Result<Vec<(String, bool)>> {
132 let mut out = Vec::new();
133 let rd = std::fs::read_dir(dir).map_err(|e| Error::io(dir, e))?;
134 for ent in rd {
135 let ent = ent.map_err(|e| Error::io(dir, e))?;
136 let name = ent.file_name().to_string_lossy().to_string();
137 let is_dir = ent
138 .file_type()
139 .map(|t| t.is_dir())
140 .unwrap_or(false);
141 out.push((name, is_dir));
142 }
143 out.sort();
144 Ok(out)
145 }
146
147 pub fn child_dirs(&self, dir: &Path) -> Result<Vec<PathBuf>> {
149 Ok(self
150 .list_names(dir)?
151 .into_iter()
152 .filter(|(_, is_dir)| *is_dir)
153 .map(|(n, _)| dir.join(n))
154 .collect())
155 }
156
157 fn contains_meta_deeper(&self, dir: &Path, rel_prefix: &str, ignore: &IgnoreSet) -> bool {
162 for entry in walkdir::WalkDir::new(dir)
163 .max_depth(8)
164 .into_iter()
165 .filter_entry(|e| {
166 if e.depth() == 0 {
167 return true;
168 }
169 let name = e.file_name().to_string_lossy().to_string();
170 if util::is_os_noise(&name) || util::is_sub_bundle(&name) {
172 return false;
173 }
174 if ignore.is_empty() {
175 return true;
176 }
177 let rel = match util::rel_display(dir, e.path()) {
178 s if s == "." => rel_prefix.to_string(),
179 s if rel_prefix.is_empty() => s,
180 s => format!("{rel_prefix}/{s}"),
181 };
182 let is_dir = e.file_type().is_dir();
183 !ignore.is_ignored(&rel, is_dir)
184 })
185 .flatten()
186 {
187 if entry.depth() == 0 || !entry.file_type().is_dir() {
188 continue;
189 }
190 if entry.path().join(META_FILE).is_file() {
191 return true;
192 }
193 }
194 false
195 }
196
197 fn build_ignore(&self, root_meta: Option<&Meta>) -> IgnoreSet {
205 let mut set = IgnoreSet::default();
206 let policies = root_meta.map(|m| &m.policies);
207 let auto = policies.map(|p| p.gitignore).unwrap_or(true);
208 if auto {
209 let mut chain: Vec<PathBuf> = Vec::new();
212 let mut cur = self.root.parent();
213 while let Some(d) = cur {
214 chain.push(d.to_path_buf());
215 if d.join(".git").exists() || chain.len() >= 32 {
216 break;
217 }
218 cur = d.parent();
219 }
220 for d in chain.into_iter().rev() {
221 if let Ok(text) = std::fs::read_to_string(d.join(".gitignore")) {
222 let prefix = self
224 .root
225 .strip_prefix(d)
226 .map(|p| p.to_string_lossy().to_string())
227 .unwrap_or_default();
228 set.push_outer(&prefix, &text);
229 }
230 }
231 if let Ok(text) = std::fs::read_to_string(self.root.join(".gitignore")) {
232 set.push_layer("", &text);
233 }
234 }
235 if let Some(p) = policies {
236 if !p.ignore.is_empty() {
237 set.push_layer("", &p.ignore.join("\n"));
238 }
239 }
240 set.push_system_layer();
243 set
244 }
245
246 pub fn scan(&self) -> Result<Scan> {
248 let mut visits: Vec<Visit> = Vec::new();
249 let mut issues: Vec<Issue> = Vec::new();
250 let mut by_id: HashMap<String, Vec<usize>> = HashMap::new();
251
252 let root_meta = self.meta_path(&self.root);
253 if !root_meta.is_file() {
254 issues.push(Issue::error(
255 code::META_MISSING,
256 ".",
257 "bundle 根目录缺少 `.str.toml`",
258 ));
259 return Ok(Scan {
260 root: self.root.clone(),
261 visits,
262 issues,
263 by_id,
264 root_index: None,
265 max_depth: 0,
266 ignore: IgnoreSet::default(),
267 });
268 }
269
270 let (root_parsed, mut root_issues) = match self.read_meta(&self.root)? {
271 MetaLoad::Ok(m, i) => (Some(m), i),
272 MetaLoad::Failed(i) => (None, i),
273 };
274 let mut ignore = self.build_ignore(root_parsed.as_deref());
275 issues.append(&mut root_issues);
276 if let Some(m) = &root_parsed {
277 if let Some(id) = &m.id {
278 by_id.entry(id.clone()).or_default().push(0);
279 }
280 }
281 visits.push(Visit {
282 dir: self.root.clone(),
283 rel: ".".to_string(),
284 depth: 0,
285 meta: root_parsed,
286 parent: None,
287 readable: true,
288 hard_link_to: None,
289 });
290
291 let mut queue: VecDeque<usize> = VecDeque::from([0usize]);
292 let mut max_depth = 0usize;
293
294 while let Some(cur) = queue.pop_front() {
295 let dir = visits[cur].dir.clone();
296 let depth = visits[cur].depth;
297 if depth >= HARD_MAX_DEPTH {
298 continue;
299 }
300 if depth >= 1 && !visits[cur].rel.is_empty() {
302 if let Ok(text) = std::fs::read_to_string(dir.join(".gitignore")) {
303 ignore.push_layer(&visits[cur].rel, &text);
304 }
305 }
306 for child in self.child_dirs(&dir)? {
307 let name = child
308 .file_name()
309 .map(|s| s.to_string_lossy().to_string())
310 .unwrap_or_default();
311 if util::is_os_noise(&name) {
312 continue;
313 }
314 if util::is_sub_bundle(&name) {
315 continue;
317 }
318 let rel = self.rel(&child);
319 if !ignore.is_empty() && ignore.is_ignored(&rel, true) {
321 continue;
322 }
323 if !self.has_meta(&child) {
324 if !util::is_reserved_name(&name) && self.contains_meta_deeper(&child, &rel, &ignore) {
326 issues.push(Issue::error(
327 code::META_MISSING,
328 rel,
329 "父目录不是分支(缺少 `.str.toml`),其内出现 `.str.toml`,无法建立分支层级",
330 ));
331 }
332 continue;
333 }
334 let d = depth + 1;
335 let (parsed, mut iss) = match self.read_meta(&child)? {
336 MetaLoad::Ok(m, i) => (Some(m), i),
337 MetaLoad::Failed(i) => (None, i),
338 };
339 issues.append(&mut iss);
340 let idx = visits.len();
341 if let Some(m) = &parsed {
342 if let Some(id) = &m.id {
343 by_id.entry(id.clone()).or_default().push(idx);
344 }
345 }
346 let hard_link_to = visits[cur]
349 .meta
350 .as_ref()
351 .and_then(|m| {
352 m.entries.iter().find(|e| {
353 e.is_link()
354 && e.mode.as_deref() == Some("hard")
355 && e.path == name
356 })
357 })
358 .and_then(|e| e.target.clone());
359 visits.push(Visit {
360 dir: child.clone(),
361 rel,
362 depth: d,
363 meta: parsed,
364 parent: Some(cur),
365 readable: true,
366 hard_link_to,
367 });
368 max_depth = max_depth.max(d);
369 queue.push_back(idx);
370 }
371 }
372
373 Ok(Scan {
374 root: self.root.clone(),
375 visits,
376 issues,
377 by_id,
378 root_index: Some(0),
379 max_depth,
380 ignore,
381 })
382 }
383}