Skip to main content

apply_patch_to_content

Function apply_patch_to_content 

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

Applies the logic of a patch to a string content.

This is a pure function that takes the patch definition and the original content of a file as a string, and returns the transformed content. It does not interact with the filesystem. This is useful for testing, in-memory operations, or integrating mpatch’s logic into other tools.

§Arguments

Note: For improved performance when content is already available as a slice of lines, consider using apply_patch_to_lines().

  • patch - The Patch object to apply.
  • original_content - An Option<&str> representing the file’s content. Some(content) for an existing file, None for a new file (creation).
  • options - Configuration for the patch operation, such as fuzz_factor.

§Returns

An InMemoryResult containing the new content and a detailed report.

§Example

// 1. Define original content and the patch.
let original_content = "Hello, world!\n";
// Construct the diff string programmatically to avoid rustdoc parsing issues with ```.
let diff_str = [
    "```diff",
    "--- a/hello.txt",
    "+++ b/hello.txt",
    "@@ -1 +1 @@",
    "-Hello, world!",
    "+Hello, mpatch!",
    "```",
].join("\n");

// 2. Parse the diff to get a Patch object.
let patch = parse_single_patch(&diff_str)?;

// 3. Apply the patch to the content in memory.
let options = ApplyOptions::exact();
let result = apply_patch_to_content(&patch, Some(original_content), &options);

// 4. Check the results.
assert_eq!(result.new_content, "Hello, mpatch!\n");
assert!(result.report.all_applied_cleanly());