1use std::{
4 collections::{BTreeMap, BTreeSet},
5 ffi::OsStr,
6 fs::File,
7 io::Read,
8 path::PathBuf,
9 sync::{Arc, Mutex},
10 time::SystemTime,
11};
12
13use ignore::{
14 Match,
15 gitignore::{Gitignore, GitignoreBuilder},
16};
17use sha2::{Digest, Sha256};
18use tokio_util::sync::CancellationToken;
19
20use crate::{
21 config::RepoConfig,
22 platform::{self, FileKind},
23 process, scope,
24 scope::LogicalTarget,
25};
26
27const MAX_ENTRIES: usize = 10_000;
29const MAX_BYTES: u64 = 1024 * 1024 * 1024;
31const GITIGNORE_BYTES: u64 = 1024 * 1024;
33const MAX_IGNORE_PATTERNS: usize = 64;
35pub(crate) const HASH_BUFFER_BYTES: usize = 64 * 1024;
38const BUILTIN_IGNORES: [&str; 5] = [".git", "__pycache__/", "*.pyc", "target/", "node_modules/"];
39
40pub(super) struct Files {
42 pub digest: crate::types::Sha256Digest,
43 pub files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
44}
45
46#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
49#[serde(try_from = "Vec<String>", into = "Vec<String>")]
50pub struct IgnorePatterns {
51 patterns: Vec<String>,
52 matcher: Gitignore,
53}
54
55impl IgnorePatterns {
56 pub fn patterns(&self) -> &[String] {
58 &self.patterns
59 }
60}
61
62impl Default for IgnorePatterns {
63 fn default() -> Self {
65 Self::try_from(Vec::new()).expect("built-in ignore patterns")
66 }
67}
68
69impl TryFrom<Vec<String>> for IgnorePatterns {
70 type Error = String;
71
72 fn try_from(patterns: Vec<String>) -> Result<Self, String> {
73 let matcher = matcher(&patterns)?;
74 Ok(Self { patterns, matcher })
75 }
76}
77
78impl From<IgnorePatterns> for Vec<String> {
79 fn from(ignore: IgnorePatterns) -> Self {
80 ignore.patterns
81 }
82}
83
84fn matcher(patterns: &[String]) -> Result<Gitignore, String> {
85 if patterns.len() > MAX_IGNORE_PATTERNS
86 || patterns.iter().collect::<BTreeSet<_>>().len() != patterns.len()
87 {
88 return Err("fingerprint.ignore must contain at most 64 unique patterns.".into());
89 }
90 let mut builder = GitignoreBuilder::new(".");
91 builder
94 .case_insensitive(false)
95 .expect("case-sensitive ignore matching");
96 for pattern in BUILTIN_IGNORES {
97 builder.add_line(None, pattern).expect("built-in pattern");
98 }
99 for pattern in patterns {
100 if pattern.trim().is_empty()
101 || pattern.starts_with(['!', '#'])
102 || pattern.bytes().any(|byte| byte.is_ascii_control())
103 {
104 return Err(
105 "fingerprint.ignore patterns must be nonblank .gitignore globs without negation or comments."
106 .into(),
107 );
108 }
109 builder
110 .add_line(None, pattern)
111 .map_err(|error| format!("fingerprint.ignore: {error}"))?;
112 }
113 builder.build().map_err(|error| error.to_string())
114}
115
116type BlobSlot = Arc<Mutex<Option<Blob>>>;
119
120#[derive(Default)]
121pub(super) struct Memo {
122 blobs: Mutex<BTreeMap<Stamp, BlobSlot>>,
123 ignores: Mutex<BTreeMap<PathBuf, Option<Arc<Gitignore>>>>,
124}
125
126#[derive(PartialEq, Eq, PartialOrd, Ord)]
127struct Stamp {
128 path: PathBuf,
129 object: platform::FileIdentity,
130 len: u64,
131 modified: SystemTime,
132}
133
134impl Stamp {
135 fn read(path: PathBuf, file: &File, metadata: &std::fs::Metadata) -> std::io::Result<Self> {
136 Ok(Self {
137 path,
138 object: platform::file_identity(file)?,
139 len: metadata.len(),
140 modified: metadata.modified()?,
141 })
142 }
143}
144
145#[derive(Clone)]
146struct Blob {
147 bytes: u64,
148 digest: crate::types::Sha256Bytes,
149}
150
151impl Memo {
152 fn hash(
153 &self,
154 physical: PathBuf,
155 file: File,
156 path: &LogicalTarget,
157 left: u64,
158 ) -> Result<Blob, String> {
159 let metadata = file
160 .metadata()
161 .map_err(|error| format!("{path}: {error}"))?;
162 if !metadata.is_file() {
163 return Err(format!("{path}: Content input must be a regular file."));
164 }
165 if metadata.len() > left {
166 return Err(too_many_bytes());
167 }
168 #[cfg(test)]
169 let measured_path = physical.clone();
170 let load = || {
171 read_blob(
172 &file,
173 path,
174 left,
175 #[cfg(test)]
176 &measured_path,
177 )
178 };
179 let Ok(stamp) = Stamp::read(physical, &file, &metadata) else {
180 return load();
181 };
182 let cell = self
183 .blobs
184 .lock()
185 .expect("file digest memo")
186 .entry(stamp)
187 .or_default()
188 .clone();
189 let mut blob = cell.lock().expect("file digest slot");
190 if let Some(saved) = blob.as_ref() {
191 return Ok(saved.clone());
192 }
193 let read = load()?;
194 let after = file
195 .metadata()
196 .map_err(|error| format!("{path}: {error}"))?;
197 if metadata.len() != after.len()
198 || metadata.modified().ok() != after.modified().ok()
199 || read.bytes != metadata.len()
200 {
201 return Err(format!("{path}: File changed while being fingerprinted."));
202 }
203 *blob = Some(read.clone());
204 Ok(read)
205 }
206
207 fn ignore(&self, path: PathBuf, directory: &File) -> Result<Option<Arc<Gitignore>>, String> {
208 if let Some(found) = self.ignores.lock().expect("ignore memo").get(&path) {
209 return Ok(found.clone());
210 }
211 let found = read_gitignore(directory)?.map(Arc::new);
212 self.ignores
213 .lock()
214 .expect("ignore memo")
215 .insert(path, found.clone());
216 Ok(found)
217 }
218}
219
220pub(super) async fn files(
222 config: &RepoConfig,
223 id: &crate::types::ArtifactName,
224 inputs: &[crate::config::LogicalPath],
225 ignore: &IgnorePatterns,
226 memo: Arc<Memo>,
227 cancellation: &CancellationToken,
228) -> Result<Files, String> {
229 if cancellation.is_cancelled() {
230 return Err(process::Error::Cancelled.to_string());
231 }
232 let walk = Walk::new(config, id, inputs, ignore, memo)?;
233 let token = cancellation.clone();
234 crate::task::joined(tokio::task::spawn_blocking(move || walk.digest(&token)).await)
235 .map_err(|error| error.to_string())?
236}
237
238struct Walk {
239 root: PathBuf,
240 owner: PathBuf,
241 prefix: LogicalTarget,
243 inputs: Vec<LogicalTarget>,
244 file: bool,
245 excluded: BTreeSet<PathBuf>,
247 ignore: Gitignore,
248 memo: Arc<Memo>,
249}
250
251#[derive(Default)]
252struct State {
253 files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
254 entries: usize,
255 bytes: u64,
256}
257
258impl Walk {
259 fn new(
260 config: &RepoConfig,
261 id: &crate::types::ArtifactName,
262 inputs: &[crate::config::LogicalPath],
263 ignore: &IgnorePatterns,
264 memo: Arc<Memo>,
265 ) -> Result<Self, String> {
266 let artifact = &config.artifacts[id];
267 let owner = config.root.join(artifact.folder());
268 artifact
270 .folder()
271 .to_str()
272 .ok_or("Artifact paths must be UTF-8.")?;
273 let prefix = platform::path_text(artifact.folder())
274 .parse::<LogicalTarget>()
275 .map_err(|error| error.to_string())?;
276 let excluded = config
277 .descendants(id)
278 .into_iter()
279 .flat_map(|name| {
280 let part = &config.artifacts[name];
281 if part.kind() == crate::config::ArtifactKind::Live {
282 return Vec::new();
283 }
284 if part.kind() == crate::config::ArtifactKind::Aspect {
285 part.select()
286 .iter()
287 .map(|path| part.folder().join(path))
288 .collect()
289 } else {
290 part.referenced_path()
291 .map(std::path::Path::to_path_buf)
292 .into_iter()
293 .collect()
294 }
295 })
296 .filter_map(|path| {
297 if artifact.folder().starts_with(&path) {
298 Some(PathBuf::new())
299 } else {
300 path.strip_prefix(artifact.folder()).ok().map(PathBuf::from)
301 }
302 })
303 .chain(
304 artifact
305 .nested
306 .keys()
307 .map(|path| PathBuf::from(path.as_str())),
308 )
309 .collect();
310 let inputs = inputs
311 .iter()
312 .map(|input| {
313 if input.as_str() == "." {
314 Ok(LogicalTarget::Root)
315 } else {
316 input
317 .as_str()
318 .parse::<LogicalTarget>()
319 .map_err(|error| error.to_string())
320 }
321 })
322 .collect::<Result<Vec<_>, String>>()?;
323 Ok(Self {
324 root: config.root.clone(),
325 owner,
326 prefix,
327 inputs,
328 file: artifact.file_name().is_some(),
329 excluded,
330 ignore: ignore.matcher.clone(),
331 memo,
332 })
333 }
334
335 fn digest(&self, cancellation: &CancellationToken) -> Result<Files, String> {
336 let mut state = State::default();
337 for input in &self.inputs {
338 if self.excluded(input) {
339 continue;
340 }
341 let label = if input.is_empty() {
342 "."
343 } else {
344 input.as_str()
345 };
346 let full = join(&self.prefix, input)?;
347 let file =
348 scope::open_scoped(&self.root, &full).map_err(|e| format!("{label}: {e}"))?;
349 let kind = file.metadata().map_err(|error| error.to_string())?;
350 if self.file && !kind.is_file() {
351 return Err(format!(
352 "{label}: File Artifact target must remain a regular file."
353 ));
354 }
355 if kind.is_dir() {
356 let mut gitignores = self.ancestors(input)?;
357 self.directory(&file, input, &mut gitignores, &mut state, cancellation)?;
358 } else {
359 self.hash_file(file, input, &mut state)?;
360 }
361 }
362 Ok(Files {
363 digest: aggregate(&state.files),
364 files: state.files,
365 })
366 }
367
368 fn hash_file(&self, file: File, path: &LogicalTarget, state: &mut State) -> Result<(), String> {
369 let remaining = MAX_BYTES.saturating_sub(state.bytes);
370 let blob = self
371 .memo
372 .hash(self.owner.join(path.as_str()), file, path, remaining)?;
373 state.bytes += blob.bytes;
374 state.files.insert(path.clone(), blob.digest);
375 Ok(())
376 }
377
378 fn excluded(&self, path: &LogicalTarget) -> bool {
379 std::path::Path::new(path.as_str())
380 .ancestors()
381 .any(|part| self.excluded.contains(part))
382 }
383
384 fn directory(
385 &self,
386 directory: &File,
387 path: &LogicalTarget,
388 gitignores: &mut Vec<(LogicalTarget, Arc<Gitignore>)>,
389 state: &mut State,
390 cancellation: &CancellationToken,
391 ) -> Result<(), String> {
392 let label = if path.is_empty() { "." } else { path.as_str() };
393 let mut entries = platform::read_dir(directory)
395 .map_err(|e| format!("{label}: {e}"))?
396 .map(|entry| {
397 let entry = entry.map_err(|e| format!("{label}: {e}"))?;
398 let kind = entry.file_type().map_err(|e| format!("{label}: {e}"))?;
399 let name = platform::os_text(&entry.file_name())
400 .map(str::to_owned)
401 .ok_or("Artifact paths must be UTF-8.")?;
402 Ok((name, kind == FileKind::Directory))
403 })
404 .collect::<Result<Vec<_>, String>>()?;
405 entries.sort();
406 let here = join(&self.prefix, path)?;
407 let gitignore = self
408 .memo
409 .ignore(self.root.join(here.as_str()), directory)
410 .map_err(|e| format!("{}: {e}", gitignore_name(path)))?;
411 let pushed = gitignore.is_some();
412 if let Some(gitignore) = gitignore {
413 gitignores.push((here, gitignore));
414 }
415 for (name, is_dir) in entries {
416 if cancellation.is_cancelled() {
417 return Err(process::Error::Cancelled.to_string());
418 }
419 let child = join(path, &name)?;
420 if self.excluded(&child) || self.ignored(&child, is_dir, gitignores)? {
421 continue;
422 }
423 state.entries += 1;
424 if state.entries > MAX_ENTRIES {
425 return Err(format!(
426 "Content inputs exceed {MAX_ENTRIES} entries; narrow fingerprint.files or add fingerprint.ignore."
427 ));
428 }
429 let entry = scope::open_child(directory, OsStr::new(&name))
430 .map_err(|e| format!("{child}: {e} Add it to fingerprint.ignore to skip it."))?;
431 if entry.metadata().map_err(|e| e.to_string())?.is_dir() {
432 self.directory(&entry, &child, gitignores, state, cancellation)?;
433 } else {
434 self.hash_file(entry, &child, state)?;
435 }
436 }
437 if pushed {
438 gitignores.pop();
439 }
440 Ok(())
441 }
442
443 fn ancestors(
445 &self,
446 input: &LogicalTarget,
447 ) -> Result<Vec<(LogicalTarget, Arc<Gitignore>)>, String> {
448 let full = join(&self.prefix, input)?;
449 let mut parts = full.split('/').filter(|part| !part.is_empty()).peekable();
450 let mut gitignores = Vec::new();
451 if parts.peek().is_none() {
452 return Ok(gitignores);
453 }
454 let mut base = LogicalTarget::Root;
455 let mut directory =
456 scope::open_scoped(&self.root, &base).map_err(|error| error.to_string())?;
457 while let Some(part) = parts.next() {
458 if let Some(gitignore) = self
459 .memo
460 .ignore(self.root.join(base.as_str()), &directory)
461 .map_err(|error| format!("{}: {error}", gitignore_name(&base)))?
462 {
463 gitignores.push((base.clone(), gitignore));
464 }
465 if parts.peek().is_some() {
466 base = join(&base, part)?;
467 directory = scope::open_child(&directory, OsStr::new(part))
468 .map_err(|error| format!("{base}: {error}"))?;
469 }
470 }
471 Ok(gitignores)
472 }
473
474 fn ignored(
477 &self,
478 path: &LogicalTarget,
479 is_dir: bool,
480 gitignores: &[(LogicalTarget, Arc<Gitignore>)],
481 ) -> Result<bool, String> {
482 if self.ignore.matched(path, is_dir).is_ignore() {
483 return Ok(true);
484 }
485 let full = join(&self.prefix, path)?;
486 for (base, gitignore) in gitignores.iter().rev() {
487 let relative = if base.is_empty() {
488 full.as_str()
489 } else {
490 &full[base.len() + 1..]
491 };
492 match gitignore.matched(relative, is_dir) {
493 Match::Ignore(_) => return Ok(true),
494 Match::Whitelist(_) => return Ok(false),
495 Match::None => {}
496 }
497 }
498 Ok(false)
499 }
500}
501
502fn read_gitignore(directory: &File) -> Result<Option<Gitignore>, String> {
504 match platform::entry_kind(directory, OsStr::new(".gitignore")) {
505 Ok(FileKind::Directory) => return Ok(None),
506 Ok(_) => {}
507 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
508 Err(error) => return Err(error.to_string()),
509 }
510 let file = scope::open_child(directory, OsStr::new(".gitignore")).map_err(|e| e.to_string())?;
511 let mut text = Vec::new();
512 file.take(GITIGNORE_BYTES + 1)
513 .read_to_end(&mut text)
514 .map_err(|e| e.to_string())?;
515 if text.len() as u64 > GITIGNORE_BYTES {
516 return Err("A .gitignore file exceeds 1 MiB.".into());
517 }
518 let mut builder = GitignoreBuilder::new(".");
519 builder
522 .case_insensitive(false)
523 .expect("case-sensitive ignore matching");
524 for line in String::from_utf8_lossy(&text).lines() {
525 let _ = builder.add_line(None, line);
526 }
527 builder.build().map(Some).map_err(|e| e.to_string())
528}
529
530fn aggregate(
532 files: &BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
533) -> crate::types::Sha256Digest {
534 let mut digest = Sha256::new();
535 for (path, file) in files {
536 digest.update(path.as_bytes());
537 digest.update([0]);
538 digest.update(file.as_bytes());
539 }
540 hex(&digest.finalize())
541 .parse()
542 .expect("SHA-256 input digest")
543}
544
545fn too_many_bytes() -> String {
546 "Content inputs exceed 1 GiB; narrow fingerprint.files or add fingerprint.ignore.".into()
547}
548
549fn read_blob(
550 mut file: &File,
551 path: &LogicalTarget,
552 limit: u64,
553 #[cfg(test)] physical: &std::path::Path,
554) -> Result<Blob, String> {
555 #[cfg(test)]
556 crate::performance::content_read(physical);
557 let mut digest = Sha256::new();
558 let mut bytes = 0;
559 if path.ends_with(".artf") {
560 let mut source = Vec::new();
561 file.take(limit + 1)
562 .read_to_end(&mut source)
563 .map_err(|error| format!("{path}: {error}"))?;
564 bytes = source.len() as u64;
565 if bytes > limit {
566 return Err(too_many_bytes());
567 }
568 digest.update(artifactize_tools::artf::fingerprinted(&source));
569 } else {
570 let mut buffer = vec![0; HASH_BUFFER_BYTES];
571 loop {
572 let read = file
573 .read(&mut buffer)
574 .map_err(|error| format!("{path}: {error}"))?;
575 if read == 0 {
576 break;
577 }
578 bytes += read as u64;
579 if bytes > limit {
580 return Err(too_many_bytes());
581 }
582 digest.update(&buffer[..read]);
583 }
584 }
585 Ok(Blob {
586 bytes,
587 digest: crate::types::Sha256Bytes::from_digest(digest.finalize().into()),
588 })
589}
590
591fn gitignore_name(folder: &LogicalTarget) -> String {
594 join(folder, ".gitignore")
595 .map_or_else(|_| format!("{folder}/.gitignore"), |path| path.to_string())
596}
597
598fn join(base: &LogicalTarget, name: &str) -> Result<LogicalTarget, String> {
599 if name.is_empty() {
600 Ok(base.clone())
601 } else {
602 let path = if base.is_empty() {
603 name.to_owned()
604 } else {
605 format!("{base}/{name}")
606 };
607 path.parse::<LogicalTarget>()
608 .map_err(|error| error.to_string())
609 }
610}
611
612pub(super) fn hex(bytes: &[u8]) -> String {
613 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
614}