Skip to main content

try_apply_patch_to_content

Function try_apply_patch_to_content 

Source
pub fn try_apply_patch_to_content(
    patch: &Patch,
    original_content: Option<&str>,
    options: &ApplyOptions,
) -> Result<InMemoryResult, StrictApplyError>
Expand description

A strict variant of apply_patch_to_content() 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(InMemoryResult): If all hunks were applied successfully.
  • Err(StrictApplyError::PartialApply): If some hunks failed to apply. The returned report within the error contains the detailed results.

§Example

use mpatch::{parse_single_patch, try_apply_patch_to_content, ApplyOptions, StrictApplyError};

let original_content = "line 1\nline 2\n";

// --- Success Case ---
let success_diff = r#"
```diff
--- a/file.txt
+++ b/file.txt
@@ -1,2 +1,2 @@
 line 1
-line 2
+line two
```
"#;
let patch = parse_single_patch(success_diff)?;
let options = ApplyOptions::new();
let result = try_apply_patch_to_content(&patch, Some(original_content), &options)?;
assert!(result.report.all_applied_cleanly());
assert_eq!(result.new_content, "line 1\nline two\n");

// --- Failure Case ---
let failing_diff = r#"
```diff
--- a/file.txt
+++ b/file.txt
@@ -1,2 +1,2 @@
 line 1
-WRONG CONTEXT
+line two
```
"#;
let failing_patch = parse_single_patch(failing_diff)?;
let result = try_apply_patch_to_content(&failing_patch, Some(original_content), &options);

assert!(matches!(result, Err(StrictApplyError::PartialApply { .. })));
if let Err(StrictApplyError::PartialApply { report }) = result {
    assert!(!report.all_applied_cleanly());
}