pub fn patch_content_str(
diff_content: &str,
original_content: Option<&str>,
options: &ApplyOptions,
) -> Result<String, OneShotError>Expand description
A high-level, one-shot function to parse a diff and apply it to a string.
This function is the most convenient entry point for the common workflow of taking a diff (e.g., from a markdown file) and applying it to some existing content in memory. It combines parsing and strict application into a single call.
It performs the following steps:
- Parses the
diff_contentusingparse_auto()(supporting Markdown, Unified Diffs, and Conflict Markers). - Ensures that exactly one
Patchis found. If zero or more than one are found, it returns an error. - Applies the single patch to
original_contentusing the strict logic oftry_apply_patch_to_content().
§Arguments
diff_content- A string slice containing the diff. This can be a Markdown code block, a raw Unified Diff, or Conflict Markers.original_content- AnOption<&str>representing the content to be patched. UseSome(content)for an existing file, orNonefor a file creation patch.options- Configuration for the patch operation, such asfuzz_factor.
§Returns
Ok(String): The new, patched content if the patch applied cleanly.Err(OneShotError): If any step fails, including parsing errors, finding the wrong number of patches, or if the patch does not apply cleanly (i.e., any hunk fails).
§Example
// 1. Define the original content and the diff.
let original_content = "fn main() {\n println!(\"Hello, world!\");\n}\n";
let diff_content = r#"
```diff
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,3 @@
fn main() {
- println!("Hello, world!");
+ println!("Hello, mpatch!");
}
```
"#;
// 2. Call the one-shot function.
let options = ApplyOptions::new();
let new_content = patch_content_str(diff_content, Some(original_content), &options)?;
// 3. Verify the new content.
let expected_content = "fn main() {\n println!(\"Hello, mpatch!\");\n}\n";
assert_eq!(new_content, expected_content);
Ok(())