pub fn try_apply_patch_to_file(
patch: &Patch,
target_dir: &Path,
options: ApplyOptions,
) -> Result<PatchResult, StrictApplyError>Expand description
A strict variant of apply_patch_to_file() that treats partial applications as an error.
This function provides a simpler error handling model for workflows where any failed hunk should be considered a failure for the entire operation.
§Returns
Ok(PatchResult): If all hunks were applied successfully.Err(StrictApplyError::PartialApply): If some hunks failed to apply. The file may be in a partially patched state (unless in dry-run mode). Thereportwithin the error contains the detailed results.Err([StrictApplyError::Patch]): For “hard” errors like I/O problems or a missing target file.
§Example
use mpatch::{parse_single_patch, try_apply_patch_to_file, ApplyOptions, StrictApplyError};
use std::fs;
use tempfile::tempdir;
// --- Success Case ---
let dir = tempdir()?;
let file_path = dir.path().join("hello.txt");
fs::write(&file_path, "Hello, world!\n")?;
let success_diff = r#"
```diff
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-Hello, world!
+Hello, mpatch!
```
"#;
let patch = parse_single_patch(success_diff)?;
let options = ApplyOptions::new();
let result = try_apply_patch_to_file(&patch, dir.path(), options)?;
assert!(result.report.all_applied_cleanly());
// --- Failure Case (Partial Apply) ---
let dir_fail = tempdir()?;
let file_path_fail = dir_fail.path().join("partial.txt");
fs::write(&file_path_fail, "line 1\nline 2\n")?;
let failing_diff = r#"
```diff
--- a/partial.txt
+++ b/partial.txt
@@ -1,2 +1,2 @@
line 1
-WRONG CONTEXT
+line two
```
"#;
let patch_fail = parse_single_patch(failing_diff)?;
let result = try_apply_patch_to_file(&patch_fail, dir_fail.path(), options);
assert!(matches!(result, Err(StrictApplyError::PartialApply { .. })));
if let Err(StrictApplyError::PartialApply { report }) = result {
assert!(!report.all_applied_cleanly());
assert_eq!(report.failures().len(), 1);
}