1use crate::{
6 git_target::{GitReport, GitTargetError},
7 hook::{HookError, HookOutcome, HookResults, HookRunner, decode},
8 inject::{
9 EditResolution, JsonEditError, PlannedEdit, RegionError, RegionKey, resolve_json_edit,
10 resolve_region_edit,
11 },
12 plan::{Content, Plan, PlanError, Planned, PlannedHook, TargetPath, has_symlink_component},
13 staging::CanonicalTarget,
14 template::Id,
15};
16#[cfg(test)]
17use std::path::Path;
18use std::{fmt, fs, io::Write, path::PathBuf};
19#[derive(Debug, Default, Clone, Copy)]
20pub struct ApplyOptions {
21 pub force: bool,
22 pub trusted: bool,
23}
24#[derive(Debug, Clone)]
29pub struct HookReport {
30 pub id: Option<Id>,
31 pub exit_code: Option<i32>,
32 pub success: bool,
33}
34#[derive(Debug)]
35pub enum Applied {
36 Written {
37 files: Vec<TargetPath>,
38 hooks_run: usize,
39 hooks: Vec<HookReport>,
40 after_apply: Option<String>,
41 git: Option<GitReport>,
43 },
44 NeedsTrust(Plan),
45}
46fn conflict_lines(paths: &[TargetPath]) -> String {
48 paths.iter().map(|path| format!("\n {path}")).collect()
49}
50fn drift_lines(regions: &[(TargetPath, RegionKey)]) -> String {
52 regions
53 .iter()
54 .map(|(path, region)| format!("\n {path} ({region})"))
55 .collect()
56}
57
58struct EditedTarget {
62 path: TargetPath,
63 image: Option<Vec<u8>>,
65 whole_file: Option<usize>,
66}
67#[derive(Debug, thiserror::Error)]
68pub enum ApplyError {
69 #[error("conflicting files:{}", conflict_lines(.0))]
70 Conflicts(Vec<TargetPath>),
71 #[error("{path}: {source}")]
72 Io {
73 path: PathBuf,
74 source: std::io::Error,
75 },
76 #[error("target path contains symlink: {0}")]
77 Symlink(TargetPath),
78 #[error("hook {index} failed: {hook:?}, outcome: {outcome:?}")]
79 Hook {
80 index: usize,
81 hook: PlannedHook,
82 outcome: HookOutcome,
83 },
84 #[error("hook {index} failed: {hook:?}: {source}")]
85 HookIo {
86 index: usize,
87 hook: PlannedHook,
88 source: HookError,
89 },
90 #[error("{0}")]
93 Deferred(PlanError),
94 #[error("region drift; rerun with --force to overwrite:{}", drift_lines(.0))]
97 Drift(Vec<(TargetPath, RegionKey)>),
98 #[error("{0}")]
100 Region(#[from] RegionError),
101 #[error("{0}")]
103 Json(#[from] JsonEditError),
104 #[error("hook {index} `{id}` output: {fault}")]
107 HookOutput {
108 index: usize,
109 id: Id,
110 fault: OutputFault,
111 },
112 #[error("{0}")]
115 Git(#[from] GitTargetError),
116}
117#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum OutputFault {
121 NotUtf8 { valid_up_to: usize },
123 Empty,
125 NotJson { line: usize, column: usize },
127}
128impl fmt::Display for OutputFault {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 match self {
131 Self::NotUtf8 { valid_up_to } => {
132 write!(
133 f,
134 "captured stream is not valid UTF-8 (valid up to byte {valid_up_to})"
135 )
136 }
137 Self::Empty => write!(f, "parse: json but the captured stdout was empty"),
138 Self::NotJson { line, column } => {
139 write!(
140 f,
141 "parse: json but the captured stdout was not JSON at line {line} column {column}"
142 )
143 }
144 }
145 }
146}
147impl Plan {
148 #[allow(clippy::result_large_err)]
151 pub fn apply(
152 self,
153 target: &CanonicalTarget,
154 options: ApplyOptions,
155 runner: &dyn HookRunner,
156 ) -> Result<Applied, ApplyError> {
157 self.apply_reporting(target, options, runner, &mut |_| {})
158 }
159 #[allow(clippy::result_large_err)]
162 pub fn apply_reporting(
163 self,
164 target: &CanonicalTarget,
165 options: ApplyOptions,
166 runner: &dyn HookRunner,
167 on_written: &mut dyn FnMut(&TargetPath),
168 ) -> Result<Applied, ApplyError> {
169 let mut conflicts = self.conflicts.clone();
170 for file in &self.files {
171 if target.as_path().join(file.path.as_path()).exists()
172 && !conflicts.contains(&file.path)
173 {
174 conflicts.push(file.path.clone());
175 }
176 }
177 if !options.force && !conflicts.is_empty() {
178 return Err(ApplyError::Conflicts(conflicts));
179 }
180 if !options.trusted && !self.hooks.is_empty() {
181 return Ok(Applied::NeedsTrust(self));
182 }
183 for file in &self.files {
184 if has_symlink_component(target.as_path(), &file.path).map_err(|source| {
185 ApplyError::Io {
186 path: target.as_path().join(file.path.as_path()),
187 source,
188 }
189 })? {
190 return Err(ApplyError::Symlink(file.path.clone()));
191 }
192 }
193 for edit in &self.edits {
195 if has_symlink_component(target.as_path(), edit.path()).map_err(|source| {
196 ApplyError::Io {
197 path: target.as_path().join(edit.path().as_path()),
198 source,
199 }
200 })? {
201 return Err(ApplyError::Symlink(edit.path().clone()));
202 }
203 }
204 for planned in &self.hooks {
208 if let Planned::Ready(hook) = planned
209 && let Some(cwd) = &hook.cwd
210 && has_symlink_component(target.as_path(), cwd).map_err(|source| {
211 ApplyError::Io {
212 path: target.as_path().join(cwd.as_path()),
213 source,
214 }
215 })?
216 {
217 return Err(ApplyError::Symlink(cwd.clone()));
218 }
219 }
220 let resolved = self.resolve_edits(target, options.force)?;
224 let git = self
227 .git
228 .as_ref()
229 .map(|planned| crate::git_target::preflight(planned, target))
230 .transpose()?;
231 let mut written = Vec::new();
232 for file in &self.files {
235 if resolved.iter().any(|e| e.path == file.path) {
236 continue;
237 }
238 let path = target.as_path().join(file.path.as_path());
239 if let Some(parent) = path.parent() {
240 fs::create_dir_all(parent).map_err(|source| ApplyError::Io {
241 path: parent.into(),
242 source,
243 })?;
244 }
245 match &file.content {
246 Content::Rendered(text) => {
247 fs::write(&path, text).map_err(|source| ApplyError::Io {
248 path: path.clone(),
249 source,
250 })?
251 }
252 Content::Copied(source) => {
253 fs::copy(source, &path).map_err(|source| ApplyError::Io {
254 path: path.clone(),
255 source,
256 })?;
257 }
258 }
259 #[cfg(unix)]
260 {
261 use std::os::unix::fs::PermissionsExt;
262 let mode = fs::metadata(&file.source)
263 .map_err(|source| ApplyError::Io {
264 path: file.source.clone(),
265 source,
266 })?
267 .permissions()
268 .mode()
269 & 0o111;
270 if mode != 0 {
271 let mut permissions = fs::metadata(&path)
272 .map_err(|source| ApplyError::Io {
273 path: path.clone(),
274 source,
275 })?
276 .permissions();
277 permissions.set_mode(permissions.mode() | mode);
278 fs::set_permissions(&path, permissions).map_err(|source| ApplyError::Io {
279 path: path.clone(),
280 source,
281 })?;
282 }
283 }
284 on_written(&file.path);
285 written.push(file.path.clone());
286 }
287 for edited in &resolved {
289 if let Some(bytes) = &edited.image {
290 self.commit_edited(target, edited, bytes)?;
291 on_written(&edited.path);
292 written.push(edited.path.clone());
293 }
294 }
295 let git = git
297 .map(|preflight| crate::git_target::set_up(preflight, target))
298 .transpose()?;
299 let mut results = HookResults::default();
303 for spec in &self.result_seed {
304 results.seed(spec);
305 }
306 let mut hooks_run = 0usize;
307 let mut hook_reports = Vec::new();
308 for (index, planned) in self.hooks.iter().enumerate() {
309 let hook = match planned {
313 Planned::Ready(hook) => hook.clone(),
314 Planned::AfterHooks(deferred) => {
315 let mut rendered = deferred
316 .render_hooks(&results)
317 .map_err(ApplyError::Deferred)?;
318 let Some(hook) = rendered.pop() else {
319 continue;
320 };
321 if let Some(cwd) = &hook.cwd
323 && has_symlink_component(target.as_path(), cwd).map_err(|source| {
324 ApplyError::Io {
325 path: target.as_path().join(cwd.as_path()),
326 source,
327 }
328 })?
329 {
330 return Err(ApplyError::Symlink(cwd.clone()));
331 }
332 hook
333 }
334 };
335 let outcome =
336 runner
337 .run(&hook, target.as_path())
338 .map_err(|source| ApplyError::HookIo {
339 index,
340 hook: hook.clone(),
341 source,
342 })?;
343 hooks_run += 1;
344 let tolerated = hook.allow_failure && outcome.code.is_some();
349 if !outcome.success && !tolerated {
350 return Err(ApplyError::Hook {
351 index,
352 hook,
353 outcome,
354 });
355 }
356 hook_reports.push(HookReport {
357 id: hook.id.clone(),
358 exit_code: outcome.code,
359 success: outcome.success,
360 });
361 if hook.id.is_some() {
362 record_result(&mut results, &hook, &outcome, index)?;
363 }
364 }
365 let after_apply = match self.after_apply {
366 None => None,
367 Some(Planned::Ready(text)) => Some(text),
368 Some(Planned::AfterHooks(deferred)) => deferred
369 .render_message(&results)
370 .map_err(ApplyError::Deferred)?,
371 };
372 Ok(Applied::Written {
373 files: written,
374 hooks_run,
375 hooks: hook_reports,
376 after_apply,
377 git,
378 })
379 }
380
381 #[allow(clippy::result_large_err)]
386 fn resolve_edits(
387 &self,
388 target: &CanonicalTarget,
389 force: bool,
390 ) -> Result<Vec<EditedTarget>, ApplyError> {
391 let mut resolved: Vec<EditedTarget> = Vec::new();
392 let mut drift: Vec<(TargetPath, RegionKey)> = Vec::new();
393 for edit in &self.edits {
394 let path = edit.path();
395 if resolved.iter().any(|e| &e.path == path) {
396 continue;
397 }
398 let whole_file = self.files.iter().position(|f| &f.path == path);
399 let mut buffer = match whole_file {
400 Some(index) => Some(self.file_image(index)?),
401 None => read_current(target, path)?,
402 };
403 let mut changed = whole_file.is_some();
406 for edit in self.edits.iter().filter(|e| e.path() == path) {
407 let resolution = match edit {
408 PlannedEdit::Region(region) => resolve_region_edit(buffer.as_deref(), region)?,
409 PlannedEdit::JsonValue(json) => resolve_json_edit(buffer.as_deref(), json)?,
410 };
411 match resolution {
412 EditResolution::Unchanged => {}
413 EditResolution::Write(bytes) => {
414 buffer = Some(bytes);
415 changed = true;
416 }
417 EditResolution::Drift { forced } => {
418 if force {
419 buffer = Some(forced);
420 changed = true;
421 } else if let PlannedEdit::Region(region) = edit {
422 drift.push((path.clone(), region.region.clone()));
423 }
424 }
425 }
426 }
427 resolved.push(EditedTarget {
428 path: path.clone(),
429 image: changed.then(|| buffer.unwrap_or_default()),
430 whole_file,
431 });
432 }
433 if !drift.is_empty() {
434 return Err(ApplyError::Drift(drift));
435 }
436 Ok(resolved)
437 }
438
439 #[allow(clippy::result_large_err)]
441 fn file_image(&self, index: usize) -> Result<Vec<u8>, ApplyError> {
442 match &self.files[index].content {
443 Content::Rendered(text) => Ok(text.clone().into_bytes()),
444 Content::Copied(source) => fs::read(source).map_err(|error| ApplyError::Io {
445 path: source.clone(),
446 source: error,
447 }),
448 }
449 }
450
451 #[allow(clippy::result_large_err)]
455 fn commit_edited(
456 &self,
457 target: &CanonicalTarget,
458 edited: &EditedTarget,
459 bytes: &[u8],
460 ) -> Result<(), ApplyError> {
461 let path = target.as_path().join(edited.path.as_path());
462 let parent = path
463 .parent()
464 .expect("a joined target path has a parent")
465 .to_owned();
466 fs::create_dir_all(&parent).map_err(|source| ApplyError::Io {
467 path: parent.clone(),
468 source,
469 })?;
470 let io = |source| ApplyError::Io {
471 path: path.clone(),
472 source,
473 };
474 let mut temp = tempfile::NamedTempFile::new_in(&parent).map_err(io)?;
475 temp.write_all(bytes).map_err(io)?;
476 temp.flush().map_err(io)?;
477 #[cfg(unix)]
478 {
479 use std::os::unix::fs::PermissionsExt;
480 let mut mode = fs::metadata(&path)
481 .map(|meta| meta.permissions().mode() & 0o7777)
482 .unwrap_or(0o644);
483 if let Some(index) = edited.whole_file {
484 let exec = fs::metadata(&self.files[index].source)
485 .map_err(|source| ApplyError::Io {
486 path: self.files[index].source.clone(),
487 source,
488 })?
489 .permissions()
490 .mode()
491 & 0o111;
492 mode |= exec;
493 }
494 let mut permissions = temp.as_file().metadata().map_err(io)?.permissions();
495 permissions.set_mode(mode);
496 temp.as_file().set_permissions(permissions).map_err(io)?;
497 }
498 temp.persist(&path).map_err(|error| ApplyError::Io {
499 path: path.clone(),
500 source: error.error,
501 })?;
502 Ok(())
503 }
504}
505
506#[allow(clippy::result_large_err)]
508fn read_current(
509 target: &CanonicalTarget,
510 path: &TargetPath,
511) -> Result<Option<Vec<u8>>, ApplyError> {
512 let full = target.as_path().join(path.as_path());
513 match fs::read(&full) {
514 Ok(bytes) => Ok(Some(bytes)),
515 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
516 Err(source) => Err(ApplyError::Io { path: full, source }),
517 }
518}
519
520#[allow(clippy::result_large_err)]
523fn decode_stream(
524 bytes: &Option<Vec<u8>>,
525 index: usize,
526 id: &Id,
527) -> Result<Option<String>, ApplyError> {
528 match bytes {
529 None => Ok(None),
530 Some(bytes) => {
531 decode(bytes.clone())
532 .map(Some)
533 .map_err(|valid_up_to| ApplyError::HookOutput {
534 index,
535 id: id.clone(),
536 fault: OutputFault::NotUtf8 { valid_up_to },
537 })
538 }
539 }
540}
541
542#[allow(clippy::result_large_err)]
547fn record_result(
548 results: &mut HookResults,
549 hook: &PlannedHook,
550 outcome: &HookOutcome,
551 index: usize,
552) -> Result<(), ApplyError> {
553 let id = hook.id.clone().expect("recorded hook has an id");
554 let stdout = decode_stream(&outcome.stdout, index, &id)?;
555 let stderr = decode_stream(&outcome.stderr, index, &id)?;
556 if !hook.parse_json {
557 results.record_text(&id, outcome.code, stdout, stderr);
558 return Ok(());
559 }
560 let spec = crate::hook::ResultSpec {
561 id: id.clone(),
562 json: true,
563 status_id: hook.status_id.clone(),
564 };
565 let raw = stdout.clone().unwrap_or_default();
567 match parse_json(&raw) {
568 Ok(value) => results.record_json(&spec, outcome.code, stdout, stderr, Some(value), true),
569 Err(fault) => {
570 if outcome.success {
571 return Err(ApplyError::HookOutput { index, id, fault });
573 }
574 results.record_json(&spec, outcome.code, stdout, stderr, None, false);
577 }
578 }
579 Ok(())
580}
581
582fn parse_json(text: &str) -> Result<serde_json::Value, OutputFault> {
586 if text.is_empty() {
587 return Err(OutputFault::Empty);
588 }
589 serde_json::from_str(text).map_err(|e| OutputFault::NotJson {
590 line: e.line(),
591 column: e.column(),
592 })
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598 use crate::{
599 hook::RecordingRunner,
600 plan::{PlannedFile, PlannedProgram},
601 };
602 use std::{cell::RefCell, rc::Rc};
603
604 fn plan(source: &Path, paths: &[&str], hooks: usize) -> Plan {
607 Plan {
608 files: paths
609 .iter()
610 .map(|path| PlannedFile {
611 path: TargetPath::parse(path).unwrap(),
612 content: Content::Rendered(format!("{path}\n")),
613 source: source.to_owned(),
614 })
615 .collect(),
616 edits: vec![],
617 conflicts: vec![],
618 hooks: (0..hooks)
619 .map(|index| {
620 Planned::Ready(PlannedHook {
621 program: PlannedProgram::Run(vec!["tool".into(), index.to_string()]),
622 cwd: None,
623 template_root: source.parent().unwrap().to_owned(),
624 id: None,
625 capture: Default::default(),
626 allow_failure: false,
627 parse_json: false,
628 status_id: None,
629 })
630 })
631 .collect(),
632 before_apply: None,
633 after_apply: None,
634 result_seed: vec![],
635 git: None,
636 }
637 }
638
639 fn support() -> (tempfile::TempDir, PathBuf) {
640 let folder = tempfile::tempdir().unwrap();
641 let source = folder.path().join("support.txt");
642 fs::write(&source, "support\n").unwrap();
643 (folder, source)
644 }
645
646 struct EventRunner(Rc<RefCell<Vec<String>>>);
648 impl HookRunner for EventRunner {
649 fn run(&self, hook: &PlannedHook, _target: &Path) -> Result<HookOutcome, HookError> {
650 self.0.borrow_mut().push(format!("hook {}", hook.argv()[1]));
651 Ok(HookOutcome {
652 success: true,
653 code: Some(0),
654 stdout: None,
655 stderr: None,
656 })
657 }
658 }
659
660 #[allow(clippy::result_large_err)]
661 fn apply(
662 plan: Plan,
663 target: &Path,
664 options: ApplyOptions,
665 runner: &dyn HookRunner,
666 events: &Rc<RefCell<Vec<String>>>,
667 ) -> Result<Applied, ApplyError> {
668 let target = crate::staging::canonical_target(target).unwrap();
669 plan.apply_reporting(&target, options, runner, &mut |path| {
670 events.borrow_mut().push(format!("file {path}"))
671 })
672 }
673
674 const TRUSTED: ApplyOptions = ApplyOptions {
675 force: false,
676 trusted: true,
677 };
678
679 #[test]
680 fn reports_each_file_once_in_plan_order_before_any_hook() {
681 let (_folder, source) = support();
682 let target = tempfile::tempdir().unwrap();
683 let events = Rc::new(RefCell::new(vec![]));
684 let plan = plan(&source, &["b.txt", "a/c.txt", "a.txt"], 2);
685 let runner = EventRunner(events.clone());
686 apply(plan, target.path(), TRUSTED, &runner, &events).unwrap();
687 assert_eq!(
688 *events.borrow(),
689 [
690 "file b.txt",
691 "file a/c.txt",
692 "file a.txt",
693 "hook 0",
694 "hook 1"
695 ]
696 );
697 }
698
699 #[test]
700 fn reports_a_forced_overwrite() {
701 let (_folder, source) = support();
702 let target = tempfile::tempdir().unwrap();
703 fs::write(target.path().join("a.txt"), "existing\n").unwrap();
704 let events = Rc::new(RefCell::new(vec![]));
705 let options = ApplyOptions {
706 force: true,
707 trusted: true,
708 };
709 let plan = plan(&source, &["a.txt", "b.txt"], 0);
710 apply(
711 plan,
712 target.path(),
713 options,
714 &RecordingRunner::new(),
715 &events,
716 )
717 .unwrap();
718 assert_eq!(*events.borrow(), ["file a.txt", "file b.txt"]);
719 assert_eq!(
720 fs::read_to_string(target.path().join("a.txt")).unwrap(),
721 "a.txt\n"
722 );
723 }
724
725 #[test]
726 fn reports_nothing_on_a_conflict_or_without_trust() {
727 let (_folder, source) = support();
728 let target = tempfile::tempdir().unwrap();
729 fs::write(target.path().join("b.txt"), "existing\n").unwrap();
730 let events = Rc::new(RefCell::new(vec![]));
731 let plan_a = plan(&source, &["a.txt", "b.txt"], 0);
732 let error = apply(
733 plan_a,
734 target.path(),
735 TRUSTED,
736 &RecordingRunner::new(),
737 &events,
738 );
739 assert!(matches!(error, Err(ApplyError::Conflicts(_))));
740 let untrusted = ApplyOptions::default();
741 let plan_b = plan(&source, &["c.txt"], 1);
742 let applied = apply(
743 plan_b,
744 target.path(),
745 untrusted,
746 &RecordingRunner::new(),
747 &events,
748 );
749 assert!(matches!(applied, Ok(Applied::NeedsTrust(_))));
750 assert!(events.borrow().is_empty(), "{:?}", events.borrow());
751 }
752
753 #[test]
754 fn a_failed_write_reports_only_the_files_written() {
755 let (_folder, source) = support();
756 let target = tempfile::tempdir().unwrap();
757 fs::create_dir(target.path().join("dir")).unwrap();
758 let events = Rc::new(RefCell::new(vec![]));
759 let options = ApplyOptions {
760 force: true,
761 trusted: true,
762 };
763 let plan = plan(&source, &["a.txt", "dir", "z.txt"], 0);
764 let error = apply(
765 plan,
766 target.path(),
767 options,
768 &RecordingRunner::new(),
769 &events,
770 );
771 assert!(matches!(error, Err(ApplyError::Io { .. })), "{error:?}");
772 assert_eq!(*events.borrow(), ["file a.txt"]);
773 }
774
775 #[test]
776 fn a_failed_hook_keeps_the_reported_files() {
777 let (_folder, source) = support();
778 let target = tempfile::tempdir().unwrap();
779 let events = Rc::new(RefCell::new(vec![]));
780 let plan = plan(&source, &["a.txt", "b.txt"], 1);
781 let error = apply(
782 plan,
783 target.path(),
784 TRUSTED,
785 &RecordingRunner::fail_at(0),
786 &events,
787 );
788 assert!(matches!(error, Err(ApplyError::Hook { .. })));
789 assert_eq!(*events.borrow(), ["file a.txt", "file b.txt"]);
790 }
791}