use crate::{
git_target::{GitReport, GitTargetError},
hook::{HookError, HookOutcome, HookResults, HookRunner, decode},
inject::{
EditResolution, JsonEditError, PlannedEdit, RegionError, RegionKey, resolve_json_edit,
resolve_region_edit,
},
plan::{Content, Plan, PlanError, Planned, PlannedHook, TargetPath, has_symlink_component},
staging::CanonicalTarget,
template::Id,
};
#[cfg(test)]
use std::path::Path;
use std::{fmt, fs, io::Write, path::PathBuf};
#[derive(Debug, Default, Clone, Copy)]
pub struct ApplyOptions {
pub force: bool,
pub trusted: bool,
}
#[derive(Debug, Clone)]
pub struct HookReport {
pub id: Option<Id>,
pub exit_code: Option<i32>,
pub success: bool,
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Applied {
Written {
files: Vec<TargetPath>,
record: crate::applied::RecordOutcome,
hooks_run: usize,
hooks: Vec<HookReport>,
after_apply: Option<String>,
git: Option<GitReport>,
},
NeedsTrust(Plan),
}
fn conflict_lines(paths: &[TargetPath]) -> String {
paths.iter().map(|path| format!("\n {path}")).collect()
}
fn drift_lines(regions: &[(TargetPath, RegionKey)]) -> String {
regions
.iter()
.map(|(path, region)| format!("\n {path} ({region})"))
.collect()
}
struct EditedTarget {
path: TargetPath,
image: Option<Vec<u8>>,
whole_file: Option<usize>,
}
#[derive(Debug, thiserror::Error)]
pub enum ApplyError {
#[error("conflicting files:{}", conflict_lines(.0))]
Conflicts(Vec<TargetPath>),
#[error("{path}: {source}")]
Io {
path: PathBuf,
source: std::io::Error,
},
#[error("target path contains symlink: {0}")]
Symlink(TargetPath),
#[error("hook {index} failed: {hook:?}, outcome: {outcome:?}")]
Hook {
index: usize,
hook: PlannedHook,
outcome: HookOutcome,
},
#[error("hook {index} failed: {hook:?}: {source}")]
HookIo {
index: usize,
hook: PlannedHook,
source: HookError,
},
#[error("{0}")]
Deferred(PlanError),
#[error("region drift; rerun with --force to overwrite:{}", drift_lines(.0))]
Drift(Vec<(TargetPath, RegionKey)>),
#[error("{0}")]
Region(#[from] RegionError),
#[error("{0}")]
Json(#[from] JsonEditError),
#[error("hook {index} `{id}` output: {fault}")]
HookOutput {
index: usize,
id: Id,
fault: OutputFault,
},
#[error("{0}")]
Record(String),
#[error("{0}")]
Git(#[from] GitTargetError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutputFault {
NotUtf8 { valid_up_to: usize },
Empty,
NotJson { line: usize, column: usize },
}
impl fmt::Display for OutputFault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotUtf8 { valid_up_to } => {
write!(
f,
"captured stream is not valid UTF-8 (valid up to byte {valid_up_to})"
)
}
Self::Empty => write!(f, "parse: json but the captured stdout was empty"),
Self::NotJson { line, column } => {
write!(
f,
"parse: json but the captured stdout was not JSON at line {line} column {column}"
)
}
}
}
}
impl Plan {
#[allow(clippy::result_large_err)]
pub fn apply(
self,
target: &CanonicalTarget,
options: ApplyOptions,
runner: &dyn HookRunner,
) -> Result<Applied, ApplyError> {
self.apply_reporting(target, options, runner, &mut |_| {})
}
#[allow(clippy::result_large_err)]
pub fn apply_reporting(
self,
target: &CanonicalTarget,
options: ApplyOptions,
runner: &dyn HookRunner,
on_written: &mut dyn FnMut(&TargetPath),
) -> Result<Applied, ApplyError> {
let mut conflicts = self.conflicts.clone();
for file in &self.files {
if target.as_path().join(file.path.as_path()).exists()
&& !conflicts.contains(&file.path)
{
conflicts.push(file.path.clone());
}
}
if !options.force && !conflicts.is_empty() {
return Err(ApplyError::Conflicts(conflicts));
}
if !options.trusted && !self.hooks.is_empty() {
return Ok(Applied::NeedsTrust(self));
}
for file in &self.files {
if has_symlink_component(target.as_path(), &file.path).map_err(|source| {
ApplyError::Io {
path: target.as_path().join(file.path.as_path()),
source,
}
})? {
return Err(ApplyError::Symlink(file.path.clone()));
}
}
self.check_edit_paths(target)?;
for planned in &self.hooks {
if let Planned::Ready(hook) = planned
&& let Some(cwd) = &hook.cwd
&& has_symlink_component(target.as_path(), cwd).map_err(|source| {
ApplyError::Io {
path: target.as_path().join(cwd.as_path()),
source,
}
})?
{
return Err(ApplyError::Symlink(cwd.clone()));
}
}
if self.record.is_some()
&& let Some(project) = crate::applied::Project::open(target)
.map_err(|e| ApplyError::Record(e.to_string()))?
{
project
.read_record()
.map_err(|e| ApplyError::Record(e.to_string()))?;
}
let record_paths = crate::applied::capture::group_plan(&self);
let before = if self.record.is_some() {
Some(
crate::applied::capture::observe(target.as_path())
.map_err(|e| ApplyError::Record(e.to_string()))?,
)
} else {
None
};
let resolved = self.resolve_edits(target, options.force)?;
let git = self
.git
.as_ref()
.map(|planned| crate::git_target::preflight(planned, target))
.transpose()?;
let mut written = Vec::new();
for file in &self.files {
if resolved.iter().any(|e| e.path == file.path) {
continue;
}
let path = target.as_path().join(file.path.as_path());
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|source| ApplyError::Io {
path: parent.into(),
source,
})?;
}
match &file.content {
Content::Rendered(text) => {
fs::write(&path, text).map_err(|source| ApplyError::Io {
path: path.clone(),
source,
})?
}
Content::Copied(source) => {
fs::copy(source, &path).map_err(|source| ApplyError::Io {
path: path.clone(),
source,
})?;
}
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = fs::metadata(&file.source)
.map_err(|source| ApplyError::Io {
path: file.source.clone(),
source,
})?
.permissions()
.mode()
& 0o111;
if mode != 0 {
let mut permissions = fs::metadata(&path)
.map_err(|source| ApplyError::Io {
path: path.clone(),
source,
})?
.permissions();
permissions.set_mode(permissions.mode() | mode);
fs::set_permissions(&path, permissions).map_err(|source| ApplyError::Io {
path: path.clone(),
source,
})?;
}
}
on_written(&file.path);
written.push(file.path.clone());
}
for edited in &resolved {
if let Some(bytes) = &edited.image {
self.commit_edited(target, edited, bytes)?;
on_written(&edited.path);
written.push(edited.path.clone());
}
}
let git = git
.map(|preflight| crate::git_target::set_up(preflight, target))
.transpose()?;
let mut results = HookResults::default();
for spec in &self.result_seed {
results.seed(spec);
}
let mut hooks_run = 0usize;
let mut hook_reports = Vec::new();
for (index, planned) in self.hooks.iter().enumerate() {
let hook = match planned {
Planned::Ready(hook) => hook.clone(),
Planned::AfterHooks(deferred) => {
let mut rendered = deferred
.render_hooks(&results)
.map_err(ApplyError::Deferred)?;
let Some(hook) = rendered.pop() else {
continue;
};
if let Some(cwd) = &hook.cwd
&& has_symlink_component(target.as_path(), cwd).map_err(|source| {
ApplyError::Io {
path: target.as_path().join(cwd.as_path()),
source,
}
})?
{
return Err(ApplyError::Symlink(cwd.clone()));
}
hook
}
};
let outcome =
runner
.run(&hook, target.as_path())
.map_err(|source| ApplyError::HookIo {
index,
hook: hook.clone(),
source,
})?;
hooks_run += 1;
let tolerated = hook.allow_failure && outcome.code.is_some();
if !outcome.success && !tolerated {
return Err(ApplyError::Hook {
index,
hook,
outcome,
});
}
hook_reports.push(HookReport {
id: hook.id.clone(),
exit_code: outcome.code,
success: outcome.success,
});
if hook.id.is_some() {
record_result(&mut results, &hook, &outcome, index)?;
}
}
let after_apply = match self.after_apply {
None => None,
Some(Planned::Ready(text)) => Some(text),
Some(Planned::AfterHooks(deferred)) => deferred
.render_message(&results)
.map_err(ApplyError::Deferred)?,
};
let record = if let Some(inputs) = self.record {
match crate::applied::Project::open(target)
.map_err(|e| ApplyError::Record(e.to_string()))?
{
None => crate::applied::RecordOutcome::NotGit,
Some(project) => {
let root = project.repo().workdir().expect("project has worktree");
let application = crate::applied::capture::capture(
project.repo(),
root,
project.target(),
&record_paths,
None,
inputs,
before.as_ref(),
)
.map_err(|e| ApplyError::Record(e.to_string()))?;
project
.write_application(application)
.map_err(|e| ApplyError::Record(e.to_string()))?;
crate::applied::RecordOutcome::Written(
project
.record_relative()
.map_err(|e| ApplyError::Record(e.to_string()))?,
)
}
}
} else {
crate::applied::RecordOutcome::Internal
};
Ok(Applied::Written {
record,
files: written,
hooks_run,
hooks: hook_reports,
after_apply,
git,
})
}
#[allow(clippy::result_large_err)]
pub(crate) fn preflight_owned_regions(
&self,
target: &CanonicalTarget,
base: &crate::applied::Application,
force: bool,
) -> Result<(), ApplyError> {
let mut drift = Vec::new();
for owned in base.paths() {
let crate::applied::Origin::Edit { regions, .. } = owned.origin() else {
continue;
};
if regions.is_empty() {
continue;
}
let path = owned.path();
check_edit_path(target, path)?;
let Some(bytes) = read_current(target, path)? else {
continue;
};
for key in regions {
let region = RegionKey::parse(key).map_err(ApplyError::Record)?;
let marker = base.region_marker(path, key);
if crate::inject::region_has_drift(&bytes, ®ion, &marker)? && !force {
drift.push((path.clone(), region));
}
}
}
if drift.is_empty() {
Ok(())
} else {
Err(ApplyError::Drift(drift))
}
}
#[allow(clippy::result_large_err)]
pub(crate) fn preflight_takeovers(
&self,
target: &CanonicalTarget,
base: &crate::applied::Application,
force: bool,
) -> Result<(), ApplyError> {
let takeovers: Vec<_> = base
.paths()
.iter()
.filter_map(|owned| {
let crate::applied::Origin::Edit { regions, values } = owned.origin() else {
return None;
};
self.files
.iter()
.position(|file| &file.path == owned.path())
.map(|index| (owned.path(), regions, values, index))
})
.collect();
if takeovers.is_empty() {
return Ok(());
}
let resolved = self.resolve_edits(target, force)?;
let mut conflicts = Vec::new();
for (path, regions, values, index) in takeovers {
check_edit_path(target, path)?;
let current = read_current(target, path)?;
let desired = match resolved.iter().find(|edit| &edit.path == path) {
Some(edit) => edit
.image
.clone()
.expect("a whole-file image always writes"),
None => self.file_image(index)?,
};
let outside = match current {
Some(current) => {
self.outside_owned(¤t, path, regions, values, base, false)?
}
None => Vec::new(),
};
let candidate = self.outside_owned(&desired, path, regions, values, base, true)?;
if outside != candidate {
conflicts.push(path.clone());
}
}
if conflicts.is_empty() {
Ok(())
} else {
Err(ApplyError::Conflicts(conflicts))
}
}
#[allow(clippy::too_many_arguments, clippy::result_large_err)]
fn outside_owned(
&self,
bytes: &[u8],
path: &TargetPath,
regions: &[String],
values: &[String],
base: &crate::applied::Application,
candidate: bool,
) -> Result<Vec<u8>, ApplyError> {
let mut bytes = bytes.to_vec();
for key in regions {
let region = RegionKey::parse(key).map_err(ApplyError::Record)?;
bytes = crate::inject::retract_region(&bytes, ®ion, &base.region_marker(path, key))?;
}
let mut values = values.to_vec();
if candidate {
for edit in self.edits.iter().filter(|edit| edit.path() == path) {
match edit {
PlannedEdit::Region(region) => {
bytes =
crate::inject::retract_region(&bytes, ®ion.region, ®ion.marker)?
}
PlannedEdit::JsonValue(value) => values.push(value.json_path.to_string()),
}
}
}
let mut values = values
.into_iter()
.map(|value| crate::inject::JsonPath::parse(&value).map_err(ApplyError::Record))
.collect::<Result<Vec<_>, _>>()?;
values.sort_by(|left, right| {
use crate::inject::JsonPathSegment::{Index, Key};
for (a, b) in left.segments().iter().zip(right.segments()) {
let ordering = match (a, b) {
(Key(a), Key(b)) => a.cmp(b),
(Index(a), Index(b)) => a.cmp(b),
(Key(_), Index(_)) => std::cmp::Ordering::Less,
(Index(_), Key(_)) => std::cmp::Ordering::Greater,
};
if ordering != std::cmp::Ordering::Equal {
return ordering;
}
}
left.segments().len().cmp(&right.segments().len())
});
values.dedup();
for json_path in values.into_iter().rev() {
bytes = crate::inject::retract_json_value(
&bytes,
&json_path,
crate::applied::capture::json_format(path),
)?;
}
Ok(bytes)
}
#[allow(clippy::result_large_err)]
pub(crate) fn preflight_edits(
&self,
target: &CanonicalTarget,
force: bool,
) -> Result<(), ApplyError> {
self.check_edit_paths(target)?;
self.resolve_edits(target, force).map(|_| ())
}
#[allow(clippy::result_large_err)]
fn check_edit_paths(&self, target: &CanonicalTarget) -> Result<(), ApplyError> {
for edit in &self.edits {
check_edit_path(target, edit.path())?;
}
Ok(())
}
#[allow(clippy::result_large_err)]
fn resolve_edits(
&self,
target: &CanonicalTarget,
force: bool,
) -> Result<Vec<EditedTarget>, ApplyError> {
let mut resolved: Vec<EditedTarget> = Vec::new();
let mut drift: Vec<(TargetPath, RegionKey)> = Vec::new();
for edit in &self.edits {
let path = edit.path();
if resolved.iter().any(|e| &e.path == path) {
continue;
}
let whole_file = self.files.iter().position(|f| &f.path == path);
let mut buffer = match whole_file {
Some(index) => Some(self.file_image(index)?),
None => read_current(target, path)?,
};
let mut changed = whole_file.is_some();
for edit in self.edits.iter().filter(|e| e.path() == path) {
let resolution = match edit {
PlannedEdit::Region(region) => resolve_region_edit(buffer.as_deref(), region)?,
PlannedEdit::JsonValue(json) => resolve_json_edit(buffer.as_deref(), json)?,
};
match resolution {
EditResolution::Unchanged => {}
EditResolution::Write(bytes) => {
buffer = Some(bytes);
changed = true;
}
EditResolution::Drift { forced } => {
if force {
buffer = Some(forced);
changed = true;
} else if let PlannedEdit::Region(region) = edit {
drift.push((path.clone(), region.region.clone()));
}
}
}
}
resolved.push(EditedTarget {
path: path.clone(),
image: changed.then(|| buffer.unwrap_or_default()),
whole_file,
});
}
if !drift.is_empty() {
return Err(ApplyError::Drift(drift));
}
Ok(resolved)
}
#[allow(clippy::result_large_err)]
fn file_image(&self, index: usize) -> Result<Vec<u8>, ApplyError> {
match &self.files[index].content {
Content::Rendered(text) => Ok(text.clone().into_bytes()),
Content::Copied(source) => fs::read(source).map_err(|error| ApplyError::Io {
path: source.clone(),
source: error,
}),
}
}
#[allow(clippy::result_large_err)]
fn commit_edited(
&self,
target: &CanonicalTarget,
edited: &EditedTarget,
bytes: &[u8],
) -> Result<(), ApplyError> {
let path = target.as_path().join(edited.path.as_path());
let parent = path
.parent()
.expect("a joined target path has a parent")
.to_owned();
fs::create_dir_all(&parent).map_err(|source| ApplyError::Io {
path: parent.clone(),
source,
})?;
let io = |source| ApplyError::Io {
path: path.clone(),
source,
};
let mut temp = tempfile::NamedTempFile::new_in(&parent).map_err(io)?;
temp.write_all(bytes).map_err(io)?;
temp.flush().map_err(io)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut mode = fs::metadata(&path)
.map(|meta| meta.permissions().mode() & 0o7777)
.unwrap_or(0o644);
if let Some(index) = edited.whole_file {
let exec = fs::metadata(&self.files[index].source)
.map_err(|source| ApplyError::Io {
path: self.files[index].source.clone(),
source,
})?
.permissions()
.mode()
& 0o111;
mode |= exec;
}
let mut permissions = temp.as_file().metadata().map_err(io)?.permissions();
permissions.set_mode(mode);
temp.as_file().set_permissions(permissions).map_err(io)?;
}
temp.persist(&path).map_err(|error| ApplyError::Io {
path: path.clone(),
source: error.error,
})?;
Ok(())
}
}
#[allow(clippy::result_large_err)]
fn check_edit_path(target: &CanonicalTarget, path: &TargetPath) -> Result<(), ApplyError> {
if has_symlink_component(target.as_path(), path).map_err(|source| ApplyError::Io {
path: target.as_path().join(path.as_path()),
source,
})? {
return Err(ApplyError::Symlink(path.clone()));
}
Ok(())
}
#[allow(clippy::result_large_err)]
fn read_current(
target: &CanonicalTarget,
path: &TargetPath,
) -> Result<Option<Vec<u8>>, ApplyError> {
let full = target.as_path().join(path.as_path());
match fs::read(&full) {
Ok(bytes) => Ok(Some(bytes)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(ApplyError::Io { path: full, source }),
}
}
#[allow(clippy::result_large_err)]
fn decode_stream(
bytes: &Option<Vec<u8>>,
index: usize,
id: &Id,
) -> Result<Option<String>, ApplyError> {
match bytes {
None => Ok(None),
Some(bytes) => {
decode(bytes.clone())
.map(Some)
.map_err(|valid_up_to| ApplyError::HookOutput {
index,
id: id.clone(),
fault: OutputFault::NotUtf8 { valid_up_to },
})
}
}
}
#[allow(clippy::result_large_err)]
fn record_result(
results: &mut HookResults,
hook: &PlannedHook,
outcome: &HookOutcome,
index: usize,
) -> Result<(), ApplyError> {
let id = hook.id.clone().expect("recorded hook has an id");
let stdout = decode_stream(&outcome.stdout, index, &id)?;
let stderr = decode_stream(&outcome.stderr, index, &id)?;
if !hook.parse_json {
results.record_text(&id, outcome.code, stdout, stderr);
return Ok(());
}
let spec = crate::hook::ResultSpec {
id: id.clone(),
json: true,
status_id: hook.status_id.clone(),
};
let raw = stdout.clone().unwrap_or_default();
match parse_json(&raw) {
Ok(value) => results.record_json(&spec, outcome.code, stdout, stderr, Some(value), true),
Err(fault) => {
if outcome.success {
return Err(ApplyError::HookOutput { index, id, fault });
}
results.record_json(&spec, outcome.code, stdout, stderr, None, false);
}
}
Ok(())
}
fn parse_json(text: &str) -> Result<serde_json::Value, OutputFault> {
if text.is_empty() {
return Err(OutputFault::Empty);
}
serde_json::from_str(text).map_err(|e| OutputFault::NotJson {
line: e.line(),
column: e.column(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
hook::RecordingRunner,
plan::{PlannedFile, PlannedProgram},
};
use std::{cell::RefCell, rc::Rc};
fn plan(source: &Path, paths: &[&str], hooks: usize) -> Plan {
Plan {
record: None,
files: paths
.iter()
.map(|path| PlannedFile {
path: TargetPath::parse(path).unwrap(),
content: Content::Rendered(format!("{path}\n")),
source: source.to_owned(),
})
.collect(),
edits: vec![],
conflicts: vec![],
hooks: (0..hooks)
.map(|index| {
Planned::Ready(PlannedHook {
program: PlannedProgram::Run(vec!["tool".into(), index.to_string()]),
cwd: None,
template_root: source.parent().unwrap().to_owned(),
id: None,
capture: Default::default(),
allow_failure: false,
parse_json: false,
status_id: None,
})
})
.collect(),
before_apply: None,
after_apply: None,
result_seed: vec![],
git: None,
}
}
fn support() -> (tempfile::TempDir, PathBuf) {
let folder = tempfile::tempdir().unwrap();
let source = folder.path().join("support.txt");
fs::write(&source, "support\n").unwrap();
(folder, source)
}
struct EventRunner(Rc<RefCell<Vec<String>>>);
impl HookRunner for EventRunner {
fn run(&self, hook: &PlannedHook, _target: &Path) -> Result<HookOutcome, HookError> {
self.0.borrow_mut().push(format!("hook {}", hook.argv()[1]));
Ok(HookOutcome {
success: true,
code: Some(0),
stdout: None,
stderr: None,
})
}
}
#[allow(clippy::result_large_err)]
fn apply(
plan: Plan,
target: &Path,
options: ApplyOptions,
runner: &dyn HookRunner,
events: &Rc<RefCell<Vec<String>>>,
) -> Result<Applied, ApplyError> {
let target = crate::staging::canonical_target(target).unwrap();
plan.apply_reporting(&target, options, runner, &mut |path| {
events.borrow_mut().push(format!("file {path}"))
})
}
const TRUSTED: ApplyOptions = ApplyOptions {
force: false,
trusted: true,
};
#[test]
fn reports_each_file_once_in_plan_order_before_any_hook() {
let (_folder, source) = support();
let target = tempfile::tempdir().unwrap();
let events = Rc::new(RefCell::new(vec![]));
let plan = plan(&source, &["b.txt", "a/c.txt", "a.txt"], 2);
let runner = EventRunner(events.clone());
apply(plan, target.path(), TRUSTED, &runner, &events).unwrap();
assert_eq!(
*events.borrow(),
[
"file b.txt",
"file a/c.txt",
"file a.txt",
"hook 0",
"hook 1"
]
);
}
#[test]
fn reports_a_forced_overwrite() {
let (_folder, source) = support();
let target = tempfile::tempdir().unwrap();
fs::write(target.path().join("a.txt"), "existing\n").unwrap();
let events = Rc::new(RefCell::new(vec![]));
let options = ApplyOptions {
force: true,
trusted: true,
};
let plan = plan(&source, &["a.txt", "b.txt"], 0);
apply(
plan,
target.path(),
options,
&RecordingRunner::new(),
&events,
)
.unwrap();
assert_eq!(*events.borrow(), ["file a.txt", "file b.txt"]);
assert_eq!(
fs::read_to_string(target.path().join("a.txt")).unwrap(),
"a.txt\n"
);
}
#[test]
fn reports_nothing_on_a_conflict_or_without_trust() {
let (_folder, source) = support();
let target = tempfile::tempdir().unwrap();
fs::write(target.path().join("b.txt"), "existing\n").unwrap();
let events = Rc::new(RefCell::new(vec![]));
let plan_a = plan(&source, &["a.txt", "b.txt"], 0);
let error = apply(
plan_a,
target.path(),
TRUSTED,
&RecordingRunner::new(),
&events,
);
assert!(matches!(error, Err(ApplyError::Conflicts(_))));
let untrusted = ApplyOptions::default();
let plan_b = plan(&source, &["c.txt"], 1);
let applied = apply(
plan_b,
target.path(),
untrusted,
&RecordingRunner::new(),
&events,
);
assert!(matches!(applied, Ok(Applied::NeedsTrust(_))));
assert!(events.borrow().is_empty(), "{:?}", events.borrow());
}
#[test]
fn a_failed_write_reports_only_the_files_written() {
let (_folder, source) = support();
let target = tempfile::tempdir().unwrap();
fs::create_dir(target.path().join("dir")).unwrap();
let events = Rc::new(RefCell::new(vec![]));
let options = ApplyOptions {
force: true,
trusted: true,
};
let plan = plan(&source, &["a.txt", "dir", "z.txt"], 0);
let error = apply(
plan,
target.path(),
options,
&RecordingRunner::new(),
&events,
);
assert!(matches!(error, Err(ApplyError::Io { .. })), "{error:?}");
assert_eq!(*events.borrow(), ["file a.txt"]);
}
#[test]
fn a_failed_hook_keeps_the_reported_files() {
let (_folder, source) = support();
let target = tempfile::tempdir().unwrap();
let events = Rc::new(RefCell::new(vec![]));
let plan = plan(&source, &["a.txt", "b.txt"], 1);
let error = apply(
plan,
target.path(),
TRUSTED,
&RecordingRunner::fail_at(0),
&events,
);
assert!(matches!(error, Err(ApplyError::Hook { .. })));
assert_eq!(*events.borrow(), ["file a.txt", "file b.txt"]);
}
}