Getting an error when trying to apply git patch with git2

I have created a test git patch file and I'm trying to apply it to another repo using the git2::Repository::apply function but I'm getting the following error Err(Error { code: -35, klass: 31, message: "hunk at line 59 did not apply" }).

I'm doing this like so.

let target_repo = Repository::open(target_repo_path_str).unwrap();
let patch_file_content = fs::read_to_string(Path::new("./patches/0001-my.patch")).unwrap();

let diff_from_patch = Diff::from_buffer(patch_file_content.as_bytes()).unwrap();

let mut apply_opts = git2::ApplyOptions::new();

let apply_result = target_repo.apply(
  Some(&mut apply_opts),

And the patch file contents look like this.

diff --git a/package.json b/package.json
index 975a6ee..8f126bb 100644
--- a/package.json
+++ b/package.json
@@ -56,6 +59,7 @@
     "eslint-plugin-prettier": "^3.3.1",
     "loader.js": "^4.7.0",
     "npm-run-all": "^4.1.5",
+    "postcss-import": "^14.0.2",
     "prettier": "^2.2.1",
     "qunit": "^2.14.1",
     "qunit-dom": "^1.6.0"

If I run the apply command directly in the terminal with git apply patches/0001-my.patch, the patch is correctly applied without any errors.

Is there something I'm missing here or is there a difference in the way the two commands work?

For what it's worth, I came across this searching for how to apply a patch with git2... and your code above worked for me. I removed the apply_opts part, which didn't seem to make a difference, and just included the small patch as a String.

So I think your Rust code works.

Is there a more complete repo somewhere I could look at?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.