Skip to main content

apply_patch_to_file

Function apply_patch_to_file 

Source
pub fn apply_patch_to_file(
    patch: &Patch,
    target_dir: &Path,
    options: ApplyOptions,
) -> Result<PatchResult, PatchError>
Expand description

A convenience function that applies a single Patch to the filesystem.

This function orchestrates the patching process for a single file. It handles filesystem interactions like reading the original file and writing the new content, while delegating the core patching logic to apply_patch_to_content(). If the patch results in empty content, the target file is deleted.

§Arguments

  • patch - The Patch object to apply.
  • target_dir - The base directory where the patch should be applied. The patch.file_path will be joined to this directory.
  • options - Configuration for the patch operation, such as dry_run and fuzz_factor.

§Returns

  • Ok(PatchResult) on success. The PatchResult contains a detailed report for each hunk and, if dry_run was enabled, a diff of the proposed changes. If some hunks failed, the file may be in a partially patched state (unless in dry-run mode).
  • Err(PatchError) for “hard” errors like I/O problems, path traversal violations, or a missing target file.

§Example

// 1. Setup a temporary directory and a file to patch.
let dir = tempdir()?;
let file_path = dir.path().join("hello.txt");
fs::write(&file_path, "Hello, world!\n")?;

// 2. Define and parse the patch.
let diff_content = r#"
```diff
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-Hello, world!
+Hello, mpatch!
```
"#;
let patch = parse_single_patch(diff_content)?;

// 3. Apply the patch to the directory.
let options = ApplyOptions::exact();
let result = apply_patch_to_file(&patch, dir.path(), options)?;

// 4. Verify the results.
assert!(result.report.all_applied_cleanly());
let new_content = fs::read_to_string(&file_path)?;
assert_eq!(new_content, "Hello, mpatch!\n");