use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result, bail};
use openmoat_core::{AtomicAction, CompiledPolicy, EvalContext, Policy, Verdict};
use super::git::ShadowGit;
use super::lock::Held;
use super::paths::{in_state_folder, is_plain};
use super::{LeftOut, META_VERSION, Meta, Omitted, REF_PREFIX, Reason, Store};
pub const MAX_LISTED: usize = 10_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
pub file_bytes: u64,
pub files: usize,
pub total_bytes: u64,
}
impl Default for Limits {
fn default() -> Self {
Self {
file_bytes: 5 << 20,
files: 100_000,
total_bytes: 1 << 30,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Taken {
New(super::Listed),
Unchanged(super::Listed),
}
impl Taken {
pub fn snapshot(&self) -> &super::Listed {
match self {
Self::New(s) | Self::Unchanged(s) => s,
}
}
}
pub struct Denied {
compiled: CompiledPolicy<'static>,
root: String,
}
impl Denied {
pub fn new(policy: Policy, ctx: &EvalContext) -> Result<Self> {
let root = ctx.project.clone().context("a snapshot needs a project")?;
Ok(Self {
compiled: CompiledPolicy::compile_owned(policy, ctx)?,
root,
})
}
pub fn names(&self, rel: &str) -> bool {
let path = format!("{}/{rel}", self.root.trim_end_matches('/'));
[
AtomicAction::FsRead { path: path.clone() },
AtomicAction::FsWrite { path },
]
.iter()
.any(|atom| {
self.compiled
.evaluate_atomic(atom)
.is_some_and(|d| d.verdict == Verdict::Deny)
})
}
}
impl Store {
pub fn take(
&self,
held: &Held,
denied: &Denied,
limits: Limits,
reason: Reason,
session: Option<&str>,
) -> Result<Taken> {
self.check_held(held)?;
let shared = self.git.index().to_path_buf();
if self.git.pin_attributes()? {
remove_if_there(&shared).context("starting the snapshot index again")?;
}
let own = private_name(&shared);
match fs::copy(&shared, &own) {
Ok(_) => keep_mtime(&shared, &own).context("copying the snapshot index's time")?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e).context("copying the snapshot index"),
}
let git = self.git.with_index(own.clone());
let tree = (|| {
let (kept, omitted, bytes) = self.select(denied, limits)?;
stage(&git, &kept)?;
let tree = git.text(&["write-tree"], None)?;
fs::rename(&own, &shared).context("keeping the snapshot index")?;
Ok::<_, anyhow::Error>((tree, kept.len(), omitted, bytes))
})();
let _ = remove_if_there(&own);
let (tree, files, mut omitted, bytes) = tree?;
let left_out_total = omitted.len();
omitted.truncate(MAX_LISTED);
let mut ignored = self.ignored_paths()?;
let ignored_total = ignored.len();
ignored.truncate(MAX_LISTED);
let meta = Meta {
version: META_VERSION,
reason,
session: session.map(str::to_owned),
files,
bytes,
left_out: omitted,
left_out_total,
ignored,
ignored_total,
};
let newest = self.list()?.pop();
if let Some(newest) = &newest
&& newest.tree == tree
&& newest.meta.left_out == meta.left_out
&& newest.meta.ignored == meta.ignored
&& (reason != Reason::RunStart
|| (newest.meta.reason == reason && newest.meta.session == meta.session))
{
return Ok(Taken::Unchanged(newest.clone()));
}
let message = serde_json::to_string(&meta)?;
let commit = self
.git
.text(&["commit-tree", &tree], Some(message.as_bytes()))?;
let after = newest
.as_ref()
.and_then(ref_ms)
.map_or(0, |ms| ms.saturating_add(1));
let refname = format!(
"{REF_PREFIX}{:015}-{}",
crate::time::now_ms().max(after),
&commit[..commit.len().min(12)]
);
self.git.output(&["update-ref", &refname, &commit], None)?;
self.find(&commit[..commit.len().min(12)]).map(Taken::New)
}
fn select(&self, denied: &Denied, limits: Limits) -> Result<(Vec<String>, Vec<Omitted>, u64)> {
let listed = self.listed_files()?;
let mut kept = Vec::new();
let mut omitted = Vec::new();
let mut bytes = 0u64;
for raw in listed.split(|b| *b == 0).filter(|p| !p.is_empty()) {
let Ok(rel) = std::str::from_utf8(raw) else {
omitted.push(omit(&String::from_utf8_lossy(raw), LeftOut::NameNotUtf8));
continue;
};
if let Some(dir) = rel.strip_suffix('/') {
omitted.push(omit(dir, LeftOut::NestedRepository));
continue;
}
if !is_plain(rel) || in_state_folder(rel) {
omitted.push(omit(rel, LeftOut::StateFolder));
continue;
}
if denied.names(rel) {
omitted.push(omit(rel, LeftOut::Denied));
continue;
}
let Ok(meta) = fs::symlink_metadata(self.project.join(rel)) else {
continue;
};
if !(meta.is_file() || meta.file_type().is_symlink()) {
omitted.push(omit(rel, LeftOut::NotAFile));
continue;
}
if meta.is_file() && meta.len() > limits.file_bytes {
omitted.push(omit(rel, LeftOut::TooLarge));
continue;
}
bytes = bytes.saturating_add(meta.len());
kept.push(rel.to_owned());
}
if kept.len() > limits.files {
bail!(
"no snapshot taken: the project has {} files to keep, more than the limit of {}; \
add the generated folders to .gitignore",
kept.len(),
limits.files
);
}
if bytes > limits.total_bytes {
bail!(
"no snapshot taken: the project's files hold {} MiB, more than the limit of {} MiB; \
add the generated folders to .gitignore",
bytes >> 20,
limits.total_bytes >> 20
);
}
Ok((kept, omitted, bytes))
}
fn listed_files(&self) -> Result<Vec<u8>> {
self.list_others(&[])
}
fn ignored_paths(&self) -> Result<Vec<String>> {
let listed = self.list_others(&["--ignored", "--directory"])?;
let mut paths: Vec<String> = listed
.split(|b| *b == 0)
.filter(|p| !p.is_empty())
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect();
paths.sort();
Ok(paths)
}
fn list_others(&self, extra: &[&str]) -> Result<Vec<u8>> {
let index = private_name(&self.dir.join("openmoat-list-index"));
let lister = self.git.with_index(index.clone());
let exclude = self.project.join(".git").join("info").join("exclude");
let exclude_setting = format!(
"core.excludesFile={}",
crate::context::path_string(&exclude)
);
let mut args = vec!["ls-files", "-z", "--others", "--exclude-standard"];
args.extend_from_slice(extra);
if exclude.is_file() {
args.splice(0..0, ["-c", exclude_setting.as_str()]);
}
let files = lister.output(&args, None);
let _ = fs::remove_file(&index);
files
}
}
fn stage(git: &ShadowGit, kept: &[String]) -> Result<()> {
let cached = git.output(&["ls-files", "-z", "--cached"], None)?;
let wanted: BTreeSet<&str> = kept.iter().map(String::as_str).collect();
let stale: Vec<u8> = cached
.split(|b| *b == 0)
.filter(|p| !p.is_empty())
.filter(|p| std::str::from_utf8(p).map_or(true, |p| !wanted.contains(p)))
.flat_map(|p| p.iter().copied().chain([0]))
.collect();
if !stale.is_empty() {
git.output(
&["update-index", "-z", "--force-remove", "--stdin"],
Some(&stale),
)?;
}
let list: Vec<u8> = kept.iter().flat_map(|p| p.bytes().chain([0])).collect();
if !list.is_empty() {
git.output(
&["update-index", "-z", "--add", "--remove", "--stdin"],
Some(&list),
)?;
}
Ok(())
}
fn private_name(path: &Path) -> PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
let mut name = path.as_os_str().to_owned();
name.push(format!("-{}-{nanos}", std::process::id()));
PathBuf::from(name)
}
fn remove_if_there(path: &Path) -> std::io::Result<()> {
match fs::remove_file(path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
fn keep_mtime(original: &Path, copy: &Path) -> std::io::Result<()> {
let modified = fs::metadata(original)?.modified()?;
fs::OpenOptions::new()
.write(true)
.open(copy)?
.set_modified(modified)
}
fn ref_ms(snapshot: &super::Listed) -> Option<i64> {
let rest = snapshot.refname.strip_prefix(REF_PREFIX)?;
rest.split('-').next()?.parse().ok()
}
fn omit(path: &str, why: LeftOut) -> Omitted {
Omitted {
path: path.to_owned(),
why,
}
}
pub fn relative(root: &Path, path: &Path) -> Option<String> {
let rel = path.strip_prefix(root).ok()?;
let text = crate::context::path_string(rel);
is_plain(&text).then_some(text)
}