Skip to main content

patch_content_str

Function patch_content_str 

Source
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:

  1. Parses the diff_content using parse_auto() (supporting Markdown, Unified Diffs, and Conflict Markers).
  2. Ensures that exactly one Patch is found. If zero or more than one are found, it returns an error.
  3. Applies the single patch to original_content using the strict logic of try_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 - An Option<&str> representing the content to be patched. Use Some(content) for an existing file, or None for a file creation patch.
  • options - Configuration for the patch operation, such as fuzz_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(())