use super::{Mount, nested_write_denials};
use crate::sandbox::patterns::folders_above;
use openmoat_core::ir::Enforcement;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Placeholder {
pub path: String,
pub dir: bool,
pub contents: &'static str,
}
impl Placeholder {
pub fn empty_file(path: String) -> Self {
Self {
path,
dir: false,
contents: "",
}
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Plan {
pub placeholders: Vec<Placeholder>,
pub mounts: Vec<Mount>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Found {
Missing,
Dir,
Other,
}
pub fn protected(ir: &Enforcement) -> Vec<String> {
nested_write_denials(ir)
}
pub fn plan(
ir: &Enforcement,
real: &str,
found: &dyn Fn(&str) -> Found,
dir_below: &dyn Fn(&str) -> bool,
) -> Plan {
let mut out = Plan::default();
'settings: for rest in protected(ir) {
let path = format!("{real}/{rest}");
if found(&path) != Found::Missing {
continue;
}
let mut folders = Vec::new();
for folder in folders_above(&rest) {
let folder = format!("{real}/{folder}");
match found(&folder) {
Found::Other => continue 'settings,
Found::Dir => {}
Found::Missing => folders.push(folder),
}
}
for folder in folders {
if !out.placeholders.iter().any(|p| p.path == folder) {
out.mounts.push(Mount::ReadWrite(folder.clone()));
out.placeholders.push(Placeholder {
path: folder,
dir: true,
contents: "",
});
}
}
let dir = dir_below(&path);
let json = std::path::Path::new(&rest)
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("json"));
let contents = if !dir && json { "{}" } else { "" };
out.placeholders.push(Placeholder {
path: path.clone(),
dir,
contents,
});
out.mounts.push(Mount::ReadOnly(path));
}
out.mounts.sort_by_key(|m| match m {
Mount::ReadWrite(p) => (0, super::depth(p)),
other => (1, super::depth(super::path_of(other))),
});
out
}
pub fn on_disk(path: &str) -> Found {
match std::fs::symlink_metadata(path) {
Err(_) => Found::Missing,
Ok(meta) if meta.is_dir() => Found::Dir,
Ok(_) => Found::Other,
}
}