Skip to main content

parse_diffs

Function parse_diffs 

Source
pub fn parse_diffs(content: &str) -> Result<Vec<Patch>, ParseError>
Expand description

Parses a string containing one or more markdown diff blocks into a vector of Patch objects.

This function scans the input content for markdown-style code blocks. It supports variable-length code fences (e.g., ``` or ````) and correctly handles nested code blocks.

It checks every block to see if it contains valid diff content (Unified Diff or Conflict Markers) at the top level of the block. Diffs inside nested code blocks (e.g., examples within documentation) are ignored. Blocks that do not contain recognizable patch signatures are skipped efficiently.

It supports two formats within the blocks:

  1. Unified Diff: Standard --- a/file, +++ b/file, @@ ... @@ format.
  2. Conflict Markers: <<<<, ====, >>>> blocks. Since these lack file headers, patches will be assigned a generic file path (patch_target).

For automatic format detection (supporting raw diffs and conflict markers outside of markdown), use parse_auto().

§Arguments

  • content - A string slice containing the text to parse.

§Errors

Returns Err(ParseError) if a block looks like a patch (e.g. has --- a/file) but fails to parse correctly. Blocks that simply lack headers are ignored.

§Example

use mpatch::parse_diffs;

let diff_content = r#"
```rust
// This block will be checked, and if it contains a diff, it will be parsed.
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,3 @@
 fn main() {
-    println!("Hello, world!");
+    println!("Hello, mpatch!");
 }
```
"#;

let patches = parse_diffs(diff_content).unwrap();
assert_eq!(patches.len(), 1);
assert_eq!(patches[0].file_path.to_str(), Some("src/main.rs"));
assert_eq!(patches[0].hunks.len(), 1);