use std::{
collections::{BTreeMap, BTreeSet},
ffi::OsStr,
fs::File,
io::Read,
path::PathBuf,
sync::{Arc, Mutex},
time::SystemTime,
};
use ignore::{
Match,
gitignore::{Gitignore, GitignoreBuilder},
};
use sha2::{Digest, Sha256};
use tokio_util::sync::CancellationToken;
use crate::{
config::RepoConfig,
platform::{self, FileKind},
process, scope,
scope::LogicalTarget,
};
const MAX_ENTRIES: usize = 10_000;
const MAX_BYTES: u64 = 1024 * 1024 * 1024;
const GITIGNORE_BYTES: u64 = 1024 * 1024;
const MAX_IGNORE_PATTERNS: usize = 64;
pub(crate) const HASH_BUFFER_BYTES: usize = 64 * 1024;
const BUILTIN_IGNORES: [&str; 5] = [".git", "__pycache__/", "*.pyc", "target/", "node_modules/"];
pub(super) struct Files {
pub digest: crate::types::Sha256Digest,
pub files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "Vec<String>", into = "Vec<String>")]
pub struct IgnorePatterns {
patterns: Vec<String>,
matcher: Gitignore,
}
impl IgnorePatterns {
pub fn patterns(&self) -> &[String] {
&self.patterns
}
}
impl Default for IgnorePatterns {
fn default() -> Self {
Self::try_from(Vec::new()).expect("built-in ignore patterns")
}
}
impl TryFrom<Vec<String>> for IgnorePatterns {
type Error = String;
fn try_from(patterns: Vec<String>) -> Result<Self, String> {
let matcher = matcher(&patterns)?;
Ok(Self { patterns, matcher })
}
}
impl From<IgnorePatterns> for Vec<String> {
fn from(ignore: IgnorePatterns) -> Self {
ignore.patterns
}
}
fn matcher(patterns: &[String]) -> Result<Gitignore, String> {
if patterns.len() > MAX_IGNORE_PATTERNS
|| patterns.iter().collect::<BTreeSet<_>>().len() != patterns.len()
{
return Err("fingerprint.ignore must contain at most 64 unique patterns.".into());
}
let mut builder = GitignoreBuilder::new(".");
builder
.case_insensitive(false)
.expect("case-sensitive ignore matching");
for pattern in BUILTIN_IGNORES {
builder.add_line(None, pattern).expect("built-in pattern");
}
for pattern in patterns {
if pattern.trim().is_empty()
|| pattern.starts_with(['!', '#'])
|| pattern.bytes().any(|byte| byte.is_ascii_control())
{
return Err(
"fingerprint.ignore patterns must be nonblank .gitignore globs without negation or comments."
.into(),
);
}
builder
.add_line(None, pattern)
.map_err(|error| format!("fingerprint.ignore: {error}"))?;
}
builder.build().map_err(|error| error.to_string())
}
type BlobSlot = Arc<Mutex<Option<Blob>>>;
#[derive(Default)]
pub(super) struct Memo {
blobs: Mutex<BTreeMap<Stamp, BlobSlot>>,
ignores: Mutex<BTreeMap<PathBuf, Option<Arc<Gitignore>>>>,
}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct Stamp {
path: PathBuf,
object: platform::FileIdentity,
len: u64,
modified: SystemTime,
}
impl Stamp {
fn read(path: PathBuf, file: &File, metadata: &std::fs::Metadata) -> std::io::Result<Self> {
Ok(Self {
path,
object: platform::file_identity(file)?,
len: metadata.len(),
modified: metadata.modified()?,
})
}
}
#[derive(Clone)]
struct Blob {
bytes: u64,
digest: crate::types::Sha256Bytes,
}
impl Memo {
fn hash(
&self,
physical: PathBuf,
file: File,
path: &LogicalTarget,
left: u64,
) -> Result<Blob, String> {
let metadata = file
.metadata()
.map_err(|error| format!("{path}: {error}"))?;
if !metadata.is_file() {
return Err(format!("{path}: Content input must be a regular file."));
}
if metadata.len() > left {
return Err(too_many_bytes());
}
#[cfg(test)]
let measured_path = physical.clone();
let load = || {
read_blob(
&file,
path,
left,
#[cfg(test)]
&measured_path,
)
};
let Ok(stamp) = Stamp::read(physical, &file, &metadata) else {
return load();
};
let cell = self
.blobs
.lock()
.expect("file digest memo")
.entry(stamp)
.or_default()
.clone();
let mut blob = cell.lock().expect("file digest slot");
if let Some(saved) = blob.as_ref() {
return Ok(saved.clone());
}
let read = load()?;
let after = file
.metadata()
.map_err(|error| format!("{path}: {error}"))?;
if metadata.len() != after.len()
|| metadata.modified().ok() != after.modified().ok()
|| read.bytes != metadata.len()
{
return Err(format!("{path}: File changed while being fingerprinted."));
}
*blob = Some(read.clone());
Ok(read)
}
fn ignore(&self, path: PathBuf, directory: &File) -> Result<Option<Arc<Gitignore>>, String> {
if let Some(found) = self.ignores.lock().expect("ignore memo").get(&path) {
return Ok(found.clone());
}
let found = read_gitignore(directory)?.map(Arc::new);
self.ignores
.lock()
.expect("ignore memo")
.insert(path, found.clone());
Ok(found)
}
}
pub(super) async fn files(
config: &RepoConfig,
id: &crate::types::ArtifactName,
inputs: &[crate::config::LogicalPath],
ignore: &IgnorePatterns,
memo: Arc<Memo>,
cancellation: &CancellationToken,
) -> Result<Files, String> {
if cancellation.is_cancelled() {
return Err(process::Error::Cancelled.to_string());
}
let walk = Walk::new(config, id, inputs, ignore, memo)?;
let token = cancellation.clone();
crate::task::joined(tokio::task::spawn_blocking(move || walk.digest(&token)).await)
.map_err(|error| error.to_string())?
}
struct Walk {
root: PathBuf,
owner: PathBuf,
prefix: LogicalTarget,
inputs: Vec<LogicalTarget>,
file: bool,
excluded: BTreeSet<PathBuf>,
ignore: Gitignore,
memo: Arc<Memo>,
}
#[derive(Default)]
struct State {
files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
entries: usize,
bytes: u64,
}
impl Walk {
fn new(
config: &RepoConfig,
id: &crate::types::ArtifactName,
inputs: &[crate::config::LogicalPath],
ignore: &IgnorePatterns,
memo: Arc<Memo>,
) -> Result<Self, String> {
let artifact = &config.artifacts[id];
let owner = config.root.join(artifact.folder());
artifact
.folder()
.to_str()
.ok_or("Artifact paths must be UTF-8.")?;
let prefix = platform::path_text(artifact.folder())
.parse::<LogicalTarget>()
.map_err(|error| error.to_string())?;
let excluded = config
.descendants(id)
.into_iter()
.flat_map(|name| {
let part = &config.artifacts[name];
if part.kind() == crate::config::ArtifactKind::Live {
return Vec::new();
}
if part.kind() == crate::config::ArtifactKind::Aspect {
part.select()
.iter()
.map(|path| part.folder().join(path))
.collect()
} else {
part.referenced_path()
.map(std::path::Path::to_path_buf)
.into_iter()
.collect()
}
})
.filter_map(|path| {
if artifact.folder().starts_with(&path) {
Some(PathBuf::new())
} else {
path.strip_prefix(artifact.folder()).ok().map(PathBuf::from)
}
})
.chain(
artifact
.nested
.keys()
.map(|path| PathBuf::from(path.as_str())),
)
.collect();
let inputs = inputs
.iter()
.map(|input| {
if input.as_str() == "." {
Ok(LogicalTarget::Root)
} else {
input
.as_str()
.parse::<LogicalTarget>()
.map_err(|error| error.to_string())
}
})
.collect::<Result<Vec<_>, String>>()?;
Ok(Self {
root: config.root.clone(),
owner,
prefix,
inputs,
file: artifact.file_name().is_some(),
excluded,
ignore: ignore.matcher.clone(),
memo,
})
}
fn digest(&self, cancellation: &CancellationToken) -> Result<Files, String> {
let mut state = State::default();
for input in &self.inputs {
if self.excluded(input) {
continue;
}
let label = if input.is_empty() {
"."
} else {
input.as_str()
};
let full = join(&self.prefix, input)?;
let file =
scope::open_scoped(&self.root, &full).map_err(|e| format!("{label}: {e}"))?;
let kind = file.metadata().map_err(|error| error.to_string())?;
if self.file && !kind.is_file() {
return Err(format!(
"{label}: File Artifact target must remain a regular file."
));
}
if kind.is_dir() {
let mut gitignores = self.ancestors(input)?;
self.directory(&file, input, &mut gitignores, &mut state, cancellation)?;
} else {
self.hash_file(file, input, &mut state)?;
}
}
Ok(Files {
digest: aggregate(&state.files),
files: state.files,
})
}
fn hash_file(&self, file: File, path: &LogicalTarget, state: &mut State) -> Result<(), String> {
let remaining = MAX_BYTES.saturating_sub(state.bytes);
let blob = self
.memo
.hash(self.owner.join(path.as_str()), file, path, remaining)?;
state.bytes += blob.bytes;
state.files.insert(path.clone(), blob.digest);
Ok(())
}
fn excluded(&self, path: &LogicalTarget) -> bool {
std::path::Path::new(path.as_str())
.ancestors()
.any(|part| self.excluded.contains(part))
}
fn directory(
&self,
directory: &File,
path: &LogicalTarget,
gitignores: &mut Vec<(LogicalTarget, Arc<Gitignore>)>,
state: &mut State,
cancellation: &CancellationToken,
) -> Result<(), String> {
let label = if path.is_empty() { "." } else { path.as_str() };
let mut entries = platform::read_dir(directory)
.map_err(|e| format!("{label}: {e}"))?
.map(|entry| {
let entry = entry.map_err(|e| format!("{label}: {e}"))?;
let kind = entry.file_type().map_err(|e| format!("{label}: {e}"))?;
let name = platform::os_text(&entry.file_name())
.map(str::to_owned)
.ok_or("Artifact paths must be UTF-8.")?;
Ok((name, kind == FileKind::Directory))
})
.collect::<Result<Vec<_>, String>>()?;
entries.sort();
let here = join(&self.prefix, path)?;
let gitignore = self
.memo
.ignore(self.root.join(here.as_str()), directory)
.map_err(|e| format!("{}: {e}", gitignore_name(path)))?;
let pushed = gitignore.is_some();
if let Some(gitignore) = gitignore {
gitignores.push((here, gitignore));
}
for (name, is_dir) in entries {
if cancellation.is_cancelled() {
return Err(process::Error::Cancelled.to_string());
}
let child = join(path, &name)?;
if self.excluded(&child) || self.ignored(&child, is_dir, gitignores)? {
continue;
}
state.entries += 1;
if state.entries > MAX_ENTRIES {
return Err(format!(
"Content inputs exceed {MAX_ENTRIES} entries; narrow fingerprint.files or add fingerprint.ignore."
));
}
let entry = scope::open_child(directory, OsStr::new(&name))
.map_err(|e| format!("{child}: {e} Add it to fingerprint.ignore to skip it."))?;
if entry.metadata().map_err(|e| e.to_string())?.is_dir() {
self.directory(&entry, &child, gitignores, state, cancellation)?;
} else {
self.hash_file(entry, &child, state)?;
}
}
if pushed {
gitignores.pop();
}
Ok(())
}
fn ancestors(
&self,
input: &LogicalTarget,
) -> Result<Vec<(LogicalTarget, Arc<Gitignore>)>, String> {
let full = join(&self.prefix, input)?;
let mut parts = full.split('/').filter(|part| !part.is_empty()).peekable();
let mut gitignores = Vec::new();
if parts.peek().is_none() {
return Ok(gitignores);
}
let mut base = LogicalTarget::Root;
let mut directory =
scope::open_scoped(&self.root, &base).map_err(|error| error.to_string())?;
while let Some(part) = parts.next() {
if let Some(gitignore) = self
.memo
.ignore(self.root.join(base.as_str()), &directory)
.map_err(|error| format!("{}: {error}", gitignore_name(&base)))?
{
gitignores.push((base.clone(), gitignore));
}
if parts.peek().is_some() {
base = join(&base, part)?;
directory = scope::open_child(&directory, OsStr::new(part))
.map_err(|error| format!("{base}: {error}"))?;
}
}
Ok(gitignores)
}
fn ignored(
&self,
path: &LogicalTarget,
is_dir: bool,
gitignores: &[(LogicalTarget, Arc<Gitignore>)],
) -> Result<bool, String> {
if self.ignore.matched(path, is_dir).is_ignore() {
return Ok(true);
}
let full = join(&self.prefix, path)?;
for (base, gitignore) in gitignores.iter().rev() {
let relative = if base.is_empty() {
full.as_str()
} else {
&full[base.len() + 1..]
};
match gitignore.matched(relative, is_dir) {
Match::Ignore(_) => return Ok(true),
Match::Whitelist(_) => return Ok(false),
Match::None => {}
}
}
Ok(false)
}
}
fn read_gitignore(directory: &File) -> Result<Option<Gitignore>, String> {
match platform::entry_kind(directory, OsStr::new(".gitignore")) {
Ok(FileKind::Directory) => return Ok(None),
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.to_string()),
}
let file = scope::open_child(directory, OsStr::new(".gitignore")).map_err(|e| e.to_string())?;
let mut text = Vec::new();
file.take(GITIGNORE_BYTES + 1)
.read_to_end(&mut text)
.map_err(|e| e.to_string())?;
if text.len() as u64 > GITIGNORE_BYTES {
return Err("A .gitignore file exceeds 1 MiB.".into());
}
let mut builder = GitignoreBuilder::new(".");
builder
.case_insensitive(false)
.expect("case-sensitive ignore matching");
for line in String::from_utf8_lossy(&text).lines() {
let _ = builder.add_line(None, line);
}
builder.build().map(Some).map_err(|e| e.to_string())
}
fn aggregate(
files: &BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
) -> crate::types::Sha256Digest {
let mut digest = Sha256::new();
for (path, file) in files {
digest.update(path.as_bytes());
digest.update([0]);
digest.update(file.as_bytes());
}
hex(&digest.finalize())
.parse()
.expect("SHA-256 input digest")
}
fn too_many_bytes() -> String {
"Content inputs exceed 1 GiB; narrow fingerprint.files or add fingerprint.ignore.".into()
}
fn read_blob(
mut file: &File,
path: &LogicalTarget,
limit: u64,
#[cfg(test)] physical: &std::path::Path,
) -> Result<Blob, String> {
#[cfg(test)]
crate::performance::content_read(physical);
let mut digest = Sha256::new();
let mut bytes = 0;
if path.ends_with(".artf") {
let mut source = Vec::new();
file.take(limit + 1)
.read_to_end(&mut source)
.map_err(|error| format!("{path}: {error}"))?;
bytes = source.len() as u64;
if bytes > limit {
return Err(too_many_bytes());
}
digest.update(artifactize_tools::artf::fingerprinted(&source));
} else {
let mut buffer = vec![0; HASH_BUFFER_BYTES];
loop {
let read = file
.read(&mut buffer)
.map_err(|error| format!("{path}: {error}"))?;
if read == 0 {
break;
}
bytes += read as u64;
if bytes > limit {
return Err(too_many_bytes());
}
digest.update(&buffer[..read]);
}
}
Ok(Blob {
bytes,
digest: crate::types::Sha256Bytes::from_digest(digest.finalize().into()),
})
}
fn gitignore_name(folder: &LogicalTarget) -> String {
join(folder, ".gitignore")
.map_or_else(|_| format!("{folder}/.gitignore"), |path| path.to_string())
}
fn join(base: &LogicalTarget, name: &str) -> Result<LogicalTarget, String> {
if name.is_empty() {
Ok(base.clone())
} else {
let path = if base.is_empty() {
name.to_owned()
} else {
format!("{base}/{name}")
};
path.parse::<LogicalTarget>()
.map_err(|error| error.to_string())
}
}
pub(super) fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}