1use std::{
4 collections::{BTreeMap, BTreeSet},
5 ffi::OsStr,
6 fs::File,
7 io::Read,
8 path::PathBuf,
9};
10
11use ignore::{
12 Match,
13 gitignore::{Gitignore, GitignoreBuilder},
14};
15use sha2::{Digest, Sha256};
16use tokio_util::sync::CancellationToken;
17
18use crate::{
19 config::RepoConfig,
20 platform::{self, FileKind},
21 process, scope,
22 scope::LogicalTarget,
23};
24
25const MAX_ENTRIES: usize = 10_000;
27const MAX_BYTES: u64 = 1024 * 1024 * 1024;
29const GITIGNORE_BYTES: u64 = 1024 * 1024;
31const MAX_IGNORE_PATTERNS: usize = 64;
33pub(crate) const HASH_BUFFER_BYTES: usize = 64 * 1024;
36const BUILTIN_IGNORES: [&str; 5] = [".git", "__pycache__/", "*.pyc", "target/", "node_modules/"];
37
38pub(super) struct Files {
40 pub digest: crate::types::Sha256Digest,
41 pub files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
42}
43
44#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
47#[serde(try_from = "Vec<String>", into = "Vec<String>")]
48pub struct IgnorePatterns {
49 patterns: Vec<String>,
50 matcher: Gitignore,
51}
52
53impl IgnorePatterns {
54 pub fn patterns(&self) -> &[String] {
56 &self.patterns
57 }
58}
59
60impl Default for IgnorePatterns {
61 fn default() -> Self {
63 Self::try_from(Vec::new()).expect("built-in ignore patterns")
64 }
65}
66
67impl TryFrom<Vec<String>> for IgnorePatterns {
68 type Error = String;
69
70 fn try_from(patterns: Vec<String>) -> Result<Self, String> {
71 let matcher = matcher(&patterns)?;
72 Ok(Self { patterns, matcher })
73 }
74}
75
76impl From<IgnorePatterns> for Vec<String> {
77 fn from(ignore: IgnorePatterns) -> Self {
78 ignore.patterns
79 }
80}
81
82fn matcher(patterns: &[String]) -> Result<Gitignore, String> {
83 if patterns.len() > MAX_IGNORE_PATTERNS
84 || patterns.iter().collect::<BTreeSet<_>>().len() != patterns.len()
85 {
86 return Err("fingerprint.ignore must contain at most 64 unique patterns.".into());
87 }
88 let mut builder = GitignoreBuilder::new(".");
89 builder
92 .case_insensitive(false)
93 .expect("case-sensitive ignore matching");
94 for pattern in BUILTIN_IGNORES {
95 builder.add_line(None, pattern).expect("built-in pattern");
96 }
97 for pattern in patterns {
98 if pattern.trim().is_empty()
99 || pattern.starts_with(['!', '#'])
100 || pattern.bytes().any(|byte| byte.is_ascii_control())
101 {
102 return Err(
103 "fingerprint.ignore patterns must be nonblank .gitignore globs without negation or comments."
104 .into(),
105 );
106 }
107 builder
108 .add_line(None, pattern)
109 .map_err(|error| format!("fingerprint.ignore: {error}"))?;
110 }
111 builder.build().map_err(|error| error.to_string())
112}
113
114pub(super) async fn files(
116 config: &RepoConfig,
117 id: &crate::types::ArtifactName,
118 inputs: &[crate::config::LogicalPath],
119 ignore: &IgnorePatterns,
120 cancellation: &CancellationToken,
121) -> Result<Files, String> {
122 if cancellation.is_cancelled() {
123 return Err(process::Error::Cancelled.to_string());
124 }
125 let walk = Walk::new(config, id, inputs, ignore)?;
126 let token = cancellation.clone();
127 crate::task::joined(tokio::task::spawn_blocking(move || walk.digest(&token)).await)
128 .map_err(|error| error.to_string())?
129}
130
131struct Walk {
132 root: PathBuf,
133 owner: PathBuf,
134 prefix: LogicalTarget,
136 inputs: Vec<LogicalTarget>,
137 file: bool,
138 excluded: BTreeSet<PathBuf>,
140 ignore: Gitignore,
141}
142
143#[derive(Default)]
144struct State {
145 files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
146 entries: usize,
147 bytes: u64,
148}
149
150impl Walk {
151 fn new(
152 config: &RepoConfig,
153 id: &crate::types::ArtifactName,
154 inputs: &[crate::config::LogicalPath],
155 ignore: &IgnorePatterns,
156 ) -> Result<Self, String> {
157 let artifact = &config.artifacts[id];
158 let owner =
159 scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
160 artifact
162 .folder()
163 .to_str()
164 .ok_or("Artifact paths must be UTF-8.")?;
165 let prefix = platform::path_text(artifact.folder())
166 .parse::<LogicalTarget>()
167 .map_err(|error| error.to_string())?;
168 let excluded = config
169 .descendants(id)
170 .into_iter()
171 .flat_map(|name| {
172 let part = &config.artifacts[name];
173 if part.kind == crate::config::ArtifactKind::Aspect {
174 part.select
175 .iter()
176 .map(|path| part.folder().join(path))
177 .collect()
178 } else {
179 vec![part.referenced_path().to_owned()]
180 }
181 })
182 .filter_map(|path| path.strip_prefix(artifact.folder()).ok().map(PathBuf::from))
183 .chain(
184 artifact
185 .nested
186 .keys()
187 .map(|path| PathBuf::from(path.as_str())),
188 )
189 .collect();
190 let inputs = inputs
191 .iter()
192 .map(|input| {
193 if input.as_str() == "." {
194 Ok(LogicalTarget::Root)
195 } else {
196 input
197 .as_str()
198 .parse::<LogicalTarget>()
199 .map_err(|error| error.to_string())
200 }
201 })
202 .collect::<Result<Vec<_>, String>>()?;
203 Ok(Self {
204 root: config.root.clone(),
205 owner,
206 prefix,
207 inputs,
208 file: artifact.file_name().is_some(),
209 excluded,
210 ignore: ignore.matcher.clone(),
211 })
212 }
213
214 fn digest(&self, cancellation: &CancellationToken) -> Result<Files, String> {
215 let mut state = State::default();
216 for input in &self.inputs {
217 if self.excluded(input) {
218 continue;
219 }
220 let label = if input.is_empty() {
221 "."
222 } else {
223 input.as_str()
224 };
225 let file =
226 scope::open_scoped(&self.owner, input).map_err(|e| format!("{label}: {e}"))?;
227 if self.file && !file.metadata().map_err(|e| e.to_string())?.is_file() {
228 return Err(format!(
229 "{label}: File Artifact target must remain a regular file."
230 ));
231 }
232 if file.metadata().map_err(|e| e.to_string())?.is_dir() {
233 let mut gitignores = self.ancestors(input)?;
234 self.directory(&file, input, &mut gitignores, &mut state, cancellation)?;
235 } else if !input.ends_with(".artf") {
236 hash_file(file, input, &mut state)?;
237 }
238 }
239 let mut digest = Sha256::new();
240 for (path, file) in &state.files {
241 digest.update(path.as_bytes());
242 digest.update([0]);
243 digest.update(file.as_bytes());
244 }
245 Ok(Files {
246 digest: hex(&digest.finalize())
247 .parse()
248 .expect("SHA-256 input digest"),
249 files: state.files,
250 })
251 }
252
253 fn excluded(&self, path: &LogicalTarget) -> bool {
254 self.excluded
255 .iter()
256 .any(|part| std::path::Path::new(path.as_str()).starts_with(part))
257 }
258
259 fn directory(
260 &self,
261 directory: &File,
262 path: &LogicalTarget,
263 gitignores: &mut Vec<(LogicalTarget, Gitignore)>,
264 state: &mut State,
265 cancellation: &CancellationToken,
266 ) -> Result<(), String> {
267 let label = if path.is_empty() { "." } else { path.as_str() };
268 let mut entries = Vec::new();
270 for entry in platform::read_dir(directory).map_err(|e| format!("{label}: {e}"))? {
271 let entry = entry.map_err(|e| format!("{label}: {e}"))?;
272 let kind = entry.file_type().map_err(|e| format!("{label}: {e}"))?;
273 let name = entry
274 .file_name()
275 .into_string()
276 .map_err(|_| "Artifact paths must be UTF-8.")?;
277 entries.push((name, kind == FileKind::Directory));
278 }
279 entries.sort();
280 let gitignore =
281 read_gitignore(directory).map_err(|e| format!("{}: {e}", gitignore_name(path)))?;
282 let pushed = gitignore.is_some();
283 if let Some(gitignore) = gitignore {
284 gitignores.push((join(&self.prefix, path)?, gitignore));
285 }
286 for (name, is_dir) in entries {
287 if cancellation.is_cancelled() {
288 return Err(process::Error::Cancelled.to_string());
289 }
290 let child = join(path, &name)?;
291 if (!is_dir && name.ends_with(".artf"))
292 || self.excluded(&child)
293 || self.ignored(&child, is_dir, gitignores)?
294 {
295 continue;
296 }
297 state.entries += 1;
298 if state.entries > MAX_ENTRIES {
299 return Err(format!(
300 "Content inputs exceed {MAX_ENTRIES} entries; narrow fingerprint.files or add fingerprint.ignore."
301 ));
302 }
303 let entry = scope::open_child(directory, OsStr::new(&name))
304 .map_err(|e| format!("{child}: {e} Add it to fingerprint.ignore to skip it."))?;
305 if entry.metadata().map_err(|e| e.to_string())?.is_dir() {
306 self.directory(&entry, &child, gitignores, state, cancellation)?;
307 } else {
308 hash_file(entry, &child, state)?;
309 }
310 }
311 if pushed {
312 gitignores.pop();
313 }
314 Ok(())
315 }
316
317 fn ancestors(&self, input: &LogicalTarget) -> Result<Vec<(LogicalTarget, Gitignore)>, String> {
319 let full = join(&self.prefix, input)?;
320 let parts: Vec<_> = full.split('/').filter(|part| !part.is_empty()).collect();
321 let mut gitignores = Vec::new();
322 for depth in 0..parts.len() {
323 let base: LogicalTarget = parts[..depth]
324 .join("/")
325 .parse()
326 .expect("ancestors of a validated logical path");
327 let label = |e: String| format!("{}: {e}", gitignore_name(&base));
328 let directory =
329 scope::open_scoped(&self.root, &base).map_err(|e| label(e.to_string()))?;
330 if let Some(gitignore) = read_gitignore(&directory).map_err(label)? {
331 gitignores.push((base, gitignore));
332 }
333 }
334 Ok(gitignores)
335 }
336
337 fn ignored(
340 &self,
341 path: &LogicalTarget,
342 is_dir: bool,
343 gitignores: &[(LogicalTarget, Gitignore)],
344 ) -> Result<bool, String> {
345 if self.ignore.matched(path, is_dir).is_ignore() {
346 return Ok(true);
347 }
348 let full = join(&self.prefix, path)?;
349 for (base, gitignore) in gitignores.iter().rev() {
350 let relative = if base.is_empty() {
351 full.as_str()
352 } else {
353 &full[base.len() + 1..]
354 };
355 match gitignore.matched(relative, is_dir) {
356 Match::Ignore(_) => return Ok(true),
357 Match::Whitelist(_) => return Ok(false),
358 Match::None => {}
359 }
360 }
361 Ok(false)
362 }
363}
364
365fn read_gitignore(directory: &File) -> Result<Option<Gitignore>, String> {
367 match platform::entry_kind(directory, OsStr::new(".gitignore")) {
368 Ok(FileKind::Directory) => return Ok(None),
369 Ok(_) => {}
370 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
371 Err(error) => return Err(error.to_string()),
372 }
373 let file = scope::open_child(directory, OsStr::new(".gitignore")).map_err(|e| e.to_string())?;
374 let mut text = Vec::new();
375 file.take(GITIGNORE_BYTES + 1)
376 .read_to_end(&mut text)
377 .map_err(|e| e.to_string())?;
378 if text.len() as u64 > GITIGNORE_BYTES {
379 return Err("A .gitignore file exceeds 1 MiB.".into());
380 }
381 let mut builder = GitignoreBuilder::new(".");
382 builder
385 .case_insensitive(false)
386 .expect("case-sensitive ignore matching");
387 for line in String::from_utf8_lossy(&text).lines() {
388 let _ = builder.add_line(None, line);
389 }
390 builder.build().map(Some).map_err(|e| e.to_string())
391}
392
393fn hash_file(mut file: File, path: &LogicalTarget, state: &mut State) -> Result<(), String> {
394 if !file.metadata().map_err(|e| e.to_string())?.is_file() {
395 return Err(format!("{path}: Content input must be a regular file."));
396 }
397 let mut digest = Sha256::new();
398 let mut buffer = vec![0; HASH_BUFFER_BYTES];
399 loop {
400 let read = file.read(&mut buffer).map_err(|e| format!("{path}: {e}"))?;
401 if read == 0 {
402 break;
403 }
404 state.bytes += read as u64;
405 if state.bytes > MAX_BYTES {
406 return Err(
407 "Content inputs exceed 1 GiB; narrow fingerprint.files or add fingerprint.ignore."
408 .into(),
409 );
410 }
411 digest.update(&buffer[..read]);
412 }
413 state.files.insert(
414 path.clone(),
415 crate::types::Sha256Bytes::from_digest(digest.finalize().into()),
416 );
417 Ok(())
418}
419
420fn gitignore_name(folder: &LogicalTarget) -> String {
423 join(folder, ".gitignore")
424 .map_or_else(|_| format!("{folder}/.gitignore"), |path| path.to_string())
425}
426
427fn join(base: &LogicalTarget, name: &str) -> Result<LogicalTarget, String> {
428 if name.is_empty() {
429 Ok(base.clone())
430 } else {
431 let path = if base.is_empty() {
432 name.to_owned()
433 } else {
434 format!("{base}/{name}")
435 };
436 path.parse::<LogicalTarget>()
437 .map_err(|error| error.to_string())
438 }
439}
440
441pub(super) fn hex(bytes: &[u8]) -> String {
442 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
443}