Skip to main content

apply_patch_to_lines

Function apply_patch_to_lines 

Source
pub fn apply_patch_to_lines<T: AsRef<str>>(
    patch: &Patch,
    original_lines: Option<&[T]>,
    options: &ApplyOptions,
) -> InMemoryResult
Expand description

Applies the logic of a patch to a slice of lines.

This is a high-level convenience function that drives a HunkApplier iterator to completion and returns the final result. For more granular control, create and use a HunkApplier directly.

§Arguments

  • patch - The Patch object to apply.
  • original_lines - An Option containing a slice of strings representing the file’s content. Some(lines) for an existing file, None for a new file (creation). The slice can contain String or &str.
  • 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_lines = vec!["Hello, world!"];
// 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 lines in memory.
let options = ApplyOptions::exact();
let result = apply_patch_to_lines(&patch, Some(&original_lines), &options);

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