use std::path::{Path, PathBuf};
use openmoat_core::{Action, Decision, EvalContext, Verdict};
use openmoat_hosts::{HookRequest, Host, ProjectSettingsSpec, SettingsFile};
use crate::home::Home;
use crate::install::HostConfig;
#[derive(Debug, PartialEq, Eq)]
struct Outcome {
path: String,
content: String,
}
#[must_use]
pub fn checked(
home: &Home,
request: &HookRequest,
ctx: &EvalContext,
decision: Decision,
) -> Decision {
let hook_file = |host: Host| {
HostConfig::for_host(home, host)
.ok()
.map(|c| c.settings_path)
};
tightened(request, ctx, &hook_file, decision)
}
fn tightened(
request: &HookRequest,
ctx: &EvalContext,
hook_file: &dyn Fn(Host) -> Option<PathBuf>,
decision: Decision,
) -> Decision {
if decision.verdict == Verdict::Deny {
return decision;
}
let found = switched_off(&outcomes(request, ctx), hook_file, Path::new(&ctx.home));
if found.is_empty() {
return decision;
}
let mut deny = Decision::new(Verdict::Deny);
deny.rules.push(super::RULE.to_owned());
deny.reasons.extend(found);
deny
}
fn outcomes(request: &HookRequest, ctx: &EvalContext) -> Vec<Outcome> {
let resolve = |raw: &str| {
openmoat_core::resolve_path(raw, &ctx.home, ctx.project.as_deref(), Some(&ctx.cwd))
};
match &request.action {
Some(Action::FsWrite { path }) => {
let Some(path) = resolve(path).filter(|p| !settings_files_at(p).is_empty()) else {
return Vec::new();
};
let content = match (&request.content, request.edits.is_empty()) {
(Some(content), _) => Some(content.clone()),
(None, false) => text_of(&path)
.and_then(|text| crate::taint::provenance::apply_edits(&text, &request.edits)),
(None, true) => None,
};
content
.map(|content| vec![Outcome { path, content }])
.unwrap_or_default()
}
Some(Action::Patch { .. }) => {
let Some(patch) = &request.patch else {
return Vec::new();
};
let read = |raw: &str| resolve(raw).and_then(|path| text_of(&path));
openmoat_core::patch_replay(patch, &read)
.into_iter()
.filter_map(|r| {
Some(Outcome {
path: resolve(&r.path)?,
content: r.content?,
})
})
.collect()
}
_ => Vec::new(),
}
}
fn text_of(path: &str) -> Option<String> {
let bytes = super::read_bytes(Path::new(path)).ok()??;
String::from_utf8(bytes).ok()
}
fn switched_off(
outcomes: &[Outcome],
hook_file: &dyn Fn(Host) -> Option<PathBuf>,
user_home: &Path,
) -> Vec<String> {
let mut found = Vec::new();
for outcome in outcomes {
for (host, spec) in settings_files_at(&outcome.path) {
let Some(hook) = hook_file(host) else {
continue;
};
let path = Path::new(&outcome.path);
let comments = spec.reader.reads_comments();
let Ok(root) = super::parse(path, outcome.content.as_bytes(), comments) else {
continue;
};
let base = path.parent().unwrap_or(path);
let file = SettingsFile::new(&root, base, &hook, Some(user_home));
let off = spec.reader.project_switched_off(&file);
if !off.is_empty() {
found.push(format!(
"{} ({} project settings): this write {}; a {} session started here \
would run without OpenMoat. Leave that setting out",
path.display(),
host.display_name(),
off.join("; "),
host.display_name(),
));
}
}
}
found
}
fn settings_files_at(path: &str) -> Vec<(Host, &'static ProjectSettingsSpec)> {
let spellings = spellings(path);
Host::ALL
.into_iter()
.filter_map(|host| Some((host, host.spec().project_settings.as_ref()?)))
.filter(|(_, spec)| {
spec.files().into_iter().any(|name| {
let rel = if spec.dir.is_empty() {
name.to_lowercase()
} else {
format!("{}/{name}", spec.dir).to_lowercase()
};
spellings
.iter()
.any(|s| *s == rel || s.ends_with(&format!("/{rel}")))
})
})
.collect()
}
fn spellings(path: &str) -> Vec<String> {
let mut out = vec![path.to_lowercase()];
let path = Path::new(path);
let real = std::fs::canonicalize(path).ok().or_else(|| {
let name = path.file_name()?;
Some(std::fs::canonicalize(path.parent()?).ok()?.join(name))
});
if let Some(real) = real {
out.push(real.to_string_lossy().replace('\\', "/").to_lowercase());
}
out
}
#[cfg(test)]
mod tests;