Skip to main content

Patch

Struct Patch 

Source
pub struct Patch {
    pub file_path: PathBuf,
    pub hunks: Vec<Hunk>,
    pub ends_with_newline: bool,
}
Expand description

Represents all the changes to be applied to a single file.

A Patch contains a target file path and a list of Hunks. It is typically created by parsing a diff string (Unified Diff, Markdown block, or Conflict Markers) using functions like parse_auto() or parse_diffs(). It can represent file modifications, creations, or deletions.

It is the primary unit of work for the apply functions.

§Example

let diff = r#"
```diff
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,3 @@
 fn main() {
-    println!("Hello, world!");
+    println!("Hello, mpatch!");
 }
```
"#;
let patch = parse_single_patch(diff).unwrap();

assert_eq!(patch.file_path.to_str(), Some("src/main.rs"));
assert_eq!(patch.hunks.len(), 1);
assert!(patch.ends_with_newline);

Fields§

§file_path: PathBuf

The relative path of the file to be patched, from the target directory.

This path is extracted from the --- a/path/to/file header in the diff. It’s a PathBuf, so you can use it directly with filesystem operations or convert it to a string for display.

§Example

let patch = parse_single_patch(diff).unwrap();

assert_eq!(patch.file_path.to_str(), Some("src/main.rs"));
println!("Patch targets the file: {}", patch.file_path.display());
§hunks: Vec<Hunk>

A list of hunks to be applied to the file.

§ends_with_newline: bool

Indicates whether the file should end with a newline. This is determined by the presence of \ No newline at end of file in the diff.

Implementations§

Source§

impl Patch

Source

pub fn from_texts( file_path: impl Into<PathBuf>, old_text: &str, new_text: &str, context_len: usize, ) -> Result<Self, ParseError>

Creates a new Patch by comparing two texts.

This function generates a unified diff between the old_text and new_text and then parses it into a Patch object. This allows mpatch to be used not just for applying patches, but also for creating them.

§Arguments
  • file_path - The path to associate with the patch (e.g., src/main.rs).
  • old_text - The original text content.
  • new_text - The new, modified text content.
  • context_len - The number of context lines to include around changes.
§Example
let old_code = "fn main() {\n    println!(\"old\");\n}\n";
let new_code = "fn main() {\n    println!(\"new\");\n}\n";

let patch = Patch::from_texts("src/main.rs", old_code, new_code, 3).unwrap();

assert_eq!(patch.file_path.to_str(), Some("src/main.rs"));
assert_eq!(patch.hunks.len(), 1);
assert_eq!(patch.hunks[0].removed_lines(), vec!["    println!(\"old\");"]);
assert_eq!(patch.hunks[0].added_lines(), vec!["    println!(\"new\");"]);
Source

pub fn invert(&self) -> Patch

Creates a new Patch that reverses the changes in this one.

Each hunk in the patch is inverted, swapping additions and deletions. This is useful for “un-applying” a patch.

Note: The ends_with_newline status of the reversed patch is ambiguous in the unified diff format, so it defaults to true.

§Example
let patch = Patch {
    file_path: "file.txt".into(),
    hunks: vec![Hunk {
        lines: vec![
            " context".to_string(),
            "-deleted".to_string(),
            "+added".to_string(),
        ],
        old_start_line: Some(10),
        new_start_line: Some(10),
    }],
    ends_with_newline: true,
};

let inverted = patch.invert();
let inverted_hunk = &inverted.hunks[0];

assert_eq!(inverted_hunk.removed_lines(), vec!["added"]);
assert_eq!(inverted_hunk.added_lines(), vec!["deleted"]);
Source

pub fn is_creation(&self) -> bool

Checks if the patch represents a file creation.

A patch is considered a creation if its first hunk is an addition-only hunk that applies to an empty file (i.e., its “match block” is empty).

§Example
let creation_diff = r#"
```diff
--- a/new_file.txt
+++ b/new_file.txt
@@ -0,0 +1,2 @@
+Hello
+World
```
"#;
let patch = parse_single_patch(creation_diff).unwrap();
assert!(patch.is_creation());
Source

pub fn is_deletion(&self) -> bool

Checks if the patch represents a full file deletion.

A patch is considered a deletion if it contains at least one hunk, and all of its hunks result in removing content without adding any new content (i.e., their “replace blocks” are empty). This is typical for a diff that empties a file.

§Example
let deletion_diff = r#"
```diff
--- a/old_file.txt
+++ b/old_file.txt
@@ -1,2 +0,0 @@
-Hello
-World
```
"#;
let patch = parse_single_patch(deletion_diff).unwrap();
assert!(patch.is_deletion());

Trait Implementations§

Source§

impl Clone for Patch

Source§

fn clone(&self) -> Patch

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Patch

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Patch

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the patch into a valid unified diff string for a single file.

This provides a canonical string representation of the entire patch, including the --- and +++ file headers, followed by the formatted content of all its hunks. It also correctly handles the \ No newline at end of file marker when necessary.

This is useful for logging, debugging, or serializing a Patch object back to its original text format.

§Example
let patch = Patch {
    file_path: "src/main.rs".into(),
    hunks: vec![Hunk {
        lines: vec![
            "-old".to_string(),
            "+new".to_string(),
        ],
        old_start_line: Some(1),
        new_start_line: Some(1),
    }],
    ends_with_newline: false, // To test the marker
};

let expected_output = concat!(
    "--- a/src/main.rs\n",
    "+++ b/src/main.rs\n",
    "@@ -1,1 +1,1 @@\n",
    "-old\n",
    "+new\n",
    "\\ No newline at end of file"
);

assert_eq!(patch.to_string(), expected_output);
Source§

impl PartialEq for Patch

Source§

fn eq(&self, other: &Patch) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Patch

Source§

impl StructuralPartialEq for Patch

Auto Trait Implementations§

§

impl Freeze for Patch

§

impl RefUnwindSafe for Patch

§

impl Send for Patch

§

impl Sync for Patch

§

impl Unpin for Patch

§

impl UnsafeUnpin for Patch

§

impl UnwindSafe for Patch

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.