From f7f4a395c091fdd9d858f0fa9a8fc95215a5cd58 Mon Sep 17 00:00:00 2001 From: Aleksey Kulikov Date: Wed, 15 Sep 2021 15:18:27 +0300 Subject: [PATCH] feat(diff): add ability to get patchid --- lib/src/bindings/diff.dart | 21 +++++++++++++++++++++ lib/src/diff.dart | 12 ++++++++++++ test/diff_test.dart | 1 + 3 files changed, 34 insertions(+) diff --git a/lib/src/bindings/diff.dart b/lib/src/bindings/diff.dart index da8f34f..a7425fc 100644 --- a/lib/src/bindings/diff.dart +++ b/lib/src/bindings/diff.dart @@ -199,6 +199,27 @@ void findSimilar( calloc.free(opts); } +/// Calculate the patch ID for the given patch. +/// +/// Calculate a stable patch ID for the given patch by summing the hash of the file diffs, +/// ignoring whitespace and line numbers. This can be used to derive whether two diffs are +/// the same with a high probability. +/// +/// Currently, this function only calculates stable patch IDs, as defined in `git-patch-id(1)`, +/// and should in fact generate the same IDs as the upstream git project does. +/// +/// Throws a [LibGit2Error] if error occured. +Pointer patchId(Pointer diff) { + final out = calloc(); + final error = libgit2.git_diff_patchid(out, diff, nullptr); + + if (error < 0) { + throw LibGit2Error(libgit2.git_error_last()); + } else { + return out; + } +} + /// Return the diff delta for an entry in the diff list. /// /// Throws [RangeError] if index out of range. diff --git a/lib/src/diff.dart b/lib/src/diff.dart index e363e63..261f8f0 100644 --- a/lib/src/diff.dart +++ b/lib/src/diff.dart @@ -75,6 +75,18 @@ class Diff { ); } + /// Calculate the patch ID for the given patch. + /// + /// Calculate a stable patch ID for the given patch by summing the hash of the file diffs, + /// ignoring whitespace and line numbers. This can be used to derive whether two diffs are + /// the same with a high probability. + /// + /// Currently, this function only calculates stable patch IDs, as defined in `git-patch-id(1)`, + /// and should in fact generate the same IDs as the upstream git project does. + /// + /// Throws a [LibGit2Error] if error occured. + Oid get patchId => Oid(bindings.patchId(_diffPointer)); + /// Releases memory allocated for diff object. void free() => bindings.free(_diffPointer); } diff --git a/test/diff_test.dart b/test/diff_test.dart index dca6b65..54bff98 100644 --- a/test/diff_test.dart +++ b/test/diff_test.dart @@ -188,6 +188,7 @@ index e69de29..c217c63 100644 expect(diff.length, 1); expect(stats.filesChanged, 1); expect(stats.insertions, 1); + expect(diff.patchId.sha, '699556913185bc38632ae20a49d5c18b9233335e'); stats.free(); diff.free();