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}
32
33pub struct Scan {
35 pub root: PathBuf,
37 pub visits: Vec<Visit>,
39 pub issues: Vec<Issue>,
41 pub by_id: HashMap<String, Vec<usize>>,
43 pub root_index: Option<usize>,
45 pub max_depth: usize,
47 pub ignore: IgnoreSet,
49}
50
51impl Scan {
52 pub fn resolve(&self, id: &str) -> Option<usize> {
54 self.by_id.get(id).and_then(|v| v.first().copied())
55 }
56
57 pub fn ancestors(&self, mut idx: usize) -> Vec<usize> {
59 let mut out = vec![idx];
60 while let Some(p) = self.visits[idx].parent {
61 out.push(p);
62 idx = p;
63 }
64 out.reverse();
65 out
66 }
67}
68
69#[derive(Debug, Clone)]
71pub struct Bundle {
72 pub root: PathBuf,
74}
75
76impl Bundle {
77 pub fn new(root: impl Into<PathBuf>) -> Result<Self> {
79 let root = root.into();
80 if !root.exists() {
81 return Err(Error::NotFound(root.display().to_string()));
82 }
83 if !root.is_dir() {
84 return Err(Error::BadArg(format!(
85 "{} 不是目录(`.str` 是目录 bundle)",
86 root.display()
87 )));
88 }
89 let root = std::fs::canonicalize(&root).map_err(|e| Error::io(&root, e))?;
92 Ok(Self { root })
93 }
94
95 pub fn name(&self) -> String {
97 self.root
98 .file_name()
99 .map(|s| s.to_string_lossy().to_string())
100 .unwrap_or_else(|| self.root.display().to_string())
101 }
102
103 pub fn meta_path(&self, dir: &Path) -> PathBuf {
105 dir.join(META_FILE)
106 }
107
108 pub fn has_meta(&self, dir: &Path) -> bool {
110 self.meta_path(dir).is_file()
111 }
112
113 pub fn rel(&self, path: &Path) -> String {
115 util::rel_display(&self.root, path)
116 }
117
118 pub fn read_meta(&self, dir: &Path) -> Result<MetaLoad> {
120 let p = self.meta_path(dir);
121 let rel = self.rel(&p);
122 load(&p, &rel)
123 }
124
125 pub fn list_names(&self, dir: &Path) -> Result<Vec<(String, bool)>> {
127 let mut out = Vec::new();
128 let rd = std::fs::read_dir(dir).map_err(|e| Error::io(dir, e))?;
129 for ent in rd {
130 let ent = ent.map_err(|e| Error::io(dir, e))?;
131 let name = ent.file_name().to_string_lossy().to_string();
132 let is_dir = ent
133 .file_type()
134 .map(|t| t.is_dir())
135 .unwrap_or(false);
136 out.push((name, is_dir));
137 }
138 out.sort();
139 Ok(out)
140 }
141
142 pub fn child_dirs(&self, dir: &Path) -> Result<Vec<PathBuf>> {
144 Ok(self
145 .list_names(dir)?
146 .into_iter()
147 .filter(|(_, is_dir)| *is_dir)
148 .map(|(n, _)| dir.join(n))
149 .collect())
150 }
151
152 fn contains_meta_deeper(&self, dir: &Path, rel_prefix: &str, ignore: &IgnoreSet) -> bool {
157 for entry in walkdir::WalkDir::new(dir)
158 .max_depth(8)
159 .into_iter()
160 .filter_entry(|e| {
161 if e.depth() == 0 {
162 return true;
163 }
164 let name = e.file_name().to_string_lossy().to_string();
165 if util::is_os_noise(&name) || util::is_sub_bundle(&name) {
167 return false;
168 }
169 if ignore.is_empty() {
170 return true;
171 }
172 let rel = match util::rel_display(dir, e.path()) {
173 s if s == "." => rel_prefix.to_string(),
174 s if rel_prefix.is_empty() => s,
175 s => format!("{rel_prefix}/{s}"),
176 };
177 let is_dir = e.file_type().is_dir();
178 !ignore.is_ignored(&rel, is_dir)
179 })
180 .flatten()
181 {
182 if entry.depth() == 0 || !entry.file_type().is_dir() {
183 continue;
184 }
185 if entry.path().join(META_FILE).is_file() {
186 return true;
187 }
188 }
189 false
190 }
191
192 fn build_ignore(&self, root_meta: Option<&Meta>) -> IgnoreSet {
200 let mut set = IgnoreSet::default();
201 let policies = root_meta.map(|m| &m.policies);
202 let auto = policies.map(|p| p.gitignore).unwrap_or(true);
203 if auto {
204 let mut chain: Vec<PathBuf> = Vec::new();
207 let mut cur = self.root.parent();
208 while let Some(d) = cur {
209 chain.push(d.to_path_buf());
210 if d.join(".git").exists() || chain.len() >= 32 {
211 break;
212 }
213 cur = d.parent();
214 }
215 for d in chain.into_iter().rev() {
216 if let Ok(text) = std::fs::read_to_string(d.join(".gitignore")) {
217 let prefix = self
219 .root
220 .strip_prefix(d)
221 .map(|p| p.to_string_lossy().to_string())
222 .unwrap_or_default();
223 set.push_outer(&prefix, &text);
224 }
225 }
226 if let Ok(text) = std::fs::read_to_string(self.root.join(".gitignore")) {
227 set.push_layer("", &text);
228 }
229 }
230 if let Some(p) = policies {
231 if !p.ignore.is_empty() {
232 set.push_layer("", &p.ignore.join("\n"));
233 }
234 }
235 set.push_system_layer();
238 set
239 }
240
241 pub fn scan(&self) -> Result<Scan> {
243 let mut visits: Vec<Visit> = Vec::new();
244 let mut issues: Vec<Issue> = Vec::new();
245 let mut by_id: HashMap<String, Vec<usize>> = HashMap::new();
246
247 let root_meta = self.meta_path(&self.root);
248 if !root_meta.is_file() {
249 issues.push(Issue::error(
250 code::META_MISSING,
251 ".",
252 "bundle 根目录缺少 `._meta`",
253 ));
254 return Ok(Scan {
255 root: self.root.clone(),
256 visits,
257 issues,
258 by_id,
259 root_index: None,
260 max_depth: 0,
261 ignore: IgnoreSet::default(),
262 });
263 }
264
265 let (root_parsed, mut root_issues) = match self.read_meta(&self.root)? {
266 MetaLoad::Ok(m, i) => (Some(m), i),
267 MetaLoad::Failed(i) => (None, i),
268 };
269 let mut ignore = self.build_ignore(root_parsed.as_deref());
270 issues.append(&mut root_issues);
271 if let Some(m) = &root_parsed {
272 if let Some(id) = &m.id {
273 by_id.entry(id.clone()).or_default().push(0);
274 }
275 }
276 visits.push(Visit {
277 dir: self.root.clone(),
278 rel: ".".to_string(),
279 depth: 0,
280 meta: root_parsed,
281 parent: None,
282 readable: true,
283 });
284
285 let mut queue: VecDeque<usize> = VecDeque::from([0usize]);
286 let mut max_depth = 0usize;
287
288 while let Some(cur) = queue.pop_front() {
289 let dir = visits[cur].dir.clone();
290 let depth = visits[cur].depth;
291 if depth >= HARD_MAX_DEPTH {
292 continue;
293 }
294 if depth >= 1 && !visits[cur].rel.is_empty() {
296 if let Ok(text) = std::fs::read_to_string(dir.join(".gitignore")) {
297 ignore.push_layer(&visits[cur].rel, &text);
298 }
299 }
300 for child in self.child_dirs(&dir)? {
301 let name = child
302 .file_name()
303 .map(|s| s.to_string_lossy().to_string())
304 .unwrap_or_default();
305 if util::is_os_noise(&name) {
306 continue;
307 }
308 if util::is_sub_bundle(&name) {
309 continue;
311 }
312 let rel = self.rel(&child);
313 if !ignore.is_empty() && ignore.is_ignored(&rel, true) {
315 continue;
316 }
317 if !self.has_meta(&child) {
318 if !util::is_reserved_name(&name) && self.contains_meta_deeper(&child, &rel, &ignore) {
320 issues.push(Issue::error(
321 code::META_MISSING,
322 rel,
323 "父目录不是分支(缺少 `._meta`),其内出现 `._meta`,无法建立分支层级",
324 ));
325 }
326 continue;
327 }
328 let d = depth + 1;
329 let (parsed, mut iss) = match self.read_meta(&child)? {
330 MetaLoad::Ok(m, i) => (Some(m), i),
331 MetaLoad::Failed(i) => (None, i),
332 };
333 issues.append(&mut iss);
334 let idx = visits.len();
335 if let Some(m) = &parsed {
336 if let Some(id) = &m.id {
337 by_id.entry(id.clone()).or_default().push(idx);
338 }
339 }
340 visits.push(Visit {
341 dir: child.clone(),
342 rel,
343 depth: d,
344 meta: parsed,
345 parent: Some(cur),
346 readable: true,
347 });
348 max_depth = max_depth.max(d);
349 queue.push_back(idx);
350 }
351 }
352
353 Ok(Scan {
354 root: self.root.clone(),
355 visits,
356 issues,
357 by_id,
358 root_index: Some(0),
359 max_depth,
360 ignore,
361 })
362 }
363}