From 4f7e6287cbfecacc910274fddd7ea0452ff1a5ef Mon Sep 17 00:00:00 2001 From: Chris Hescock Date: Thu, 19 Nov 2015 15:11:34 -0500 Subject: [PATCH 01/50] Handle exceptions and null returns from CredentialsProvider. --- LibGit2Sharp/RemoteCallbacks.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/LibGit2Sharp/RemoteCallbacks.cs b/LibGit2Sharp/RemoteCallbacks.cs index 42037a22e..678fb84e1 100644 --- a/LibGit2Sharp/RemoteCallbacks.cs +++ b/LibGit2Sharp/RemoteCallbacks.cs @@ -285,9 +285,21 @@ private int GitCredentialHandler( types |= SupportedCredentialTypes.Default; } - var cred = CredentialsProvider(url, username, types); - - return cred.GitCredentialHandler(out ptr); + ptr = IntPtr.Zero; + try + { + var cred = CredentialsProvider(url, username, types); + if (cred == null) + { + return (int)GitErrorCode.PassThrough; + } + return cred.GitCredentialHandler(out ptr); + } + catch (Exception exception) + { + Proxy.giterr_set_str(GitErrorCategory.Callback, exception); + return (int)GitErrorCode.Error; + } } private int GitCertificateCheck(IntPtr certPtr, int valid, IntPtr cHostname, IntPtr payload) From b1f1f4744c1e68105ae93cc312031a267ec6f802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 11 Dec 2015 02:34:29 +0100 Subject: [PATCH 02/50] Use a pointer to retrieve the library's error As the first step to moving away from marshalling data into managed memory when we can avoid it, we start with a simple one which we only read from. --- LibGit2Sharp/Core/EncodingMarshaler.cs | 9 +++++++-- LibGit2Sharp/Core/Ensure.cs | 16 +++++---------- LibGit2Sharp/Core/GitError.cs | 4 ++-- .../Core/Handles/GitErrorSafeHandle.cs | 20 ------------------- LibGit2Sharp/Core/NativeMethods.cs | 2 +- LibGit2Sharp/Core/Utf8Marshaler.cs | 5 +++++ LibGit2Sharp/LibGit2Sharp.csproj | 1 - 7 files changed, 20 insertions(+), 37 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs diff --git a/LibGit2Sharp/Core/EncodingMarshaler.cs b/LibGit2Sharp/Core/EncodingMarshaler.cs index fadc15610..0cafd9aa1 100644 --- a/LibGit2Sharp/Core/EncodingMarshaler.cs +++ b/LibGit2Sharp/Core/EncodingMarshaler.cs @@ -93,7 +93,12 @@ public static void Cleanup(IntPtr pNativeData) public static unsafe string FromNative(Encoding encoding, IntPtr pNativeData) { - if (pNativeData == IntPtr.Zero) + return FromNative(encoding, (byte*)pNativeData); + } + + public static unsafe string FromNative(Encoding encoding, byte* pNativeData) + { + if (pNativeData == null) { return null; } @@ -112,7 +117,7 @@ public static unsafe string FromNative(Encoding encoding, IntPtr pNativeData) return String.Empty; } - return new String((sbyte*)pNativeData.ToPointer(), 0, (int)(walk - start), encoding); + return new String((sbyte*)pNativeData, 0, (int)(walk - start), encoding); } public static unsafe string FromNative(Encoding encoding, IntPtr pNativeData, int length) diff --git a/LibGit2Sharp/Core/Ensure.cs b/LibGit2Sharp/Core/Ensure.cs index b85cf712c..d82fa3a4b 100644 --- a/LibGit2Sharp/Core/Ensure.cs +++ b/LibGit2Sharp/Core/Ensure.cs @@ -130,25 +130,19 @@ private static readonly Dictionary new PeelException(m, r, c) }, }; - private static void HandleError(int result) + private static unsafe void HandleError(int result) { string errorMessage; - GitError error = null; - var errHandle = NativeMethods.giterr_last(); - - if (errHandle != null && !errHandle.IsInvalid) - { - error = errHandle.MarshalAsGitError(); - } + GitErrorCategory errorCategory = GitErrorCategory.Unknown; + GitError* error = NativeMethods.giterr_last(); if (error == null) { - error = new GitError { Category = GitErrorCategory.Unknown, Message = IntPtr.Zero }; errorMessage = "No error message has been provided by the native library"; } else { - errorMessage = LaxUtf8Marshaler.FromNative(error.Message); + errorMessage = LaxUtf8Marshaler.FromNative(error->Message); } Func exceptionBuilder; @@ -157,7 +151,7 @@ private static void HandleError(int result) exceptionBuilder = (m, r, c) => new LibGit2SharpException(m, r, c); } - throw exceptionBuilder(errorMessage, (GitErrorCode)result, error.Category); + throw exceptionBuilder(errorMessage, (GitErrorCode)result, errorCategory); } /// diff --git a/LibGit2Sharp/Core/GitError.cs b/LibGit2Sharp/Core/GitError.cs index 0041097da..3d982f466 100644 --- a/LibGit2Sharp/Core/GitError.cs +++ b/LibGit2Sharp/Core/GitError.cs @@ -4,9 +4,9 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitError + internal unsafe struct GitError { - public IntPtr Message; + public char* Message; public GitErrorCategory Category; } } diff --git a/LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs b/LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs deleted file mode 100644 index d0010a635..000000000 --- a/LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace LibGit2Sharp.Core.Handles -{ - internal class GitErrorSafeHandle : NotOwnedSafeHandleBase - { - public GitError MarshalAsGitError() - { - // Required on Mono < 3.0.8 - // https://bugzilla.xamarin.com/show_bug.cgi?id=11417 - // https://github.com/mono/mono/commit/9cdddca7ec283f3b9181f3f69c1acecc0d9cc289 - if (handle == IntPtr.Zero) - { - return null; - } - - return handle.MarshalAs(); - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 0e3d6b3fc..ed8bad349 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -79,7 +79,7 @@ static NativeMethods() } [DllImport(libgit2)] - internal static extern GitErrorSafeHandle giterr_last(); + internal static extern unsafe GitError* giterr_last(); [DllImport(libgit2)] internal static extern void giterr_set_str( diff --git a/LibGit2Sharp/Core/Utf8Marshaler.cs b/LibGit2Sharp/Core/Utf8Marshaler.cs index c56a71c5f..fbe127abf 100644 --- a/LibGit2Sharp/Core/Utf8Marshaler.cs +++ b/LibGit2Sharp/Core/Utf8Marshaler.cs @@ -112,6 +112,11 @@ public override IntPtr MarshalManagedToNative(object managedObj) #endregion + public static unsafe string FromNative(char* pNativeData) + { + return FromNative(Encoding, (byte*)pNativeData); + } + public static string FromNative(IntPtr pNativeData) { return FromNative(Encoding, pNativeData); diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index c2fc74e2e..bdcc523bf 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -280,7 +280,6 @@ - From c2b73dfb4e227e1156a23bfdc1e8d5af51a5b01e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 11 Dec 2015 02:53:11 +0100 Subject: [PATCH 03/50] Use pointers for retrieving a config entry This avoids a copy of the struct when we only want to grab the strings to convert them to managed strings. --- LibGit2Sharp/Configuration.cs | 11 ++++---- LibGit2Sharp/Core/GitConfigEntry.cs | 10 +++---- .../Core/Handles/GitConfigEntryHandle.cs | 16 ----------- LibGit2Sharp/Core/NativeMethods.cs | 6 ++--- LibGit2Sharp/Core/Proxy.cs | 27 ++++++------------- LibGit2Sharp/LibGit2Sharp.csproj | 1 - 6 files changed, 21 insertions(+), 50 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/GitConfigEntryHandle.cs diff --git a/LibGit2Sharp/Configuration.cs b/LibGit2Sharp/Configuration.cs index 4dbab2412..afdf69a31 100644 --- a/LibGit2Sharp/Configuration.cs +++ b/LibGit2Sharp/Configuration.cs @@ -732,13 +732,12 @@ private IEnumerable> BuildConfigEntries() return Proxy.git_config_foreach(configHandle, BuildConfigEntry); } - private static ConfigurationEntry BuildConfigEntry(IntPtr entryPtr) + private static unsafe ConfigurationEntry BuildConfigEntry(IntPtr entryPtr) { - var entry = entryPtr.MarshalAs(); - - return new ConfigurationEntry(LaxUtf8Marshaler.FromNative(entry.namePtr), - LaxUtf8Marshaler.FromNative(entry.valuePtr), - (ConfigurationLevel)entry.level); + var entry = (GitConfigEntry*)entryPtr.ToPointer(); + return new ConfigurationEntry(LaxUtf8Marshaler.FromNative(entry->namePtr), + LaxUtf8Marshaler.FromNative(entry->valuePtr), + (ConfigurationLevel)entry->level); } /// diff --git a/LibGit2Sharp/Core/GitConfigEntry.cs b/LibGit2Sharp/Core/GitConfigEntry.cs index 85d1669a8..30550126b 100644 --- a/LibGit2Sharp/Core/GitConfigEntry.cs +++ b/LibGit2Sharp/Core/GitConfigEntry.cs @@ -4,12 +4,12 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal struct GitConfigEntry + internal unsafe struct GitConfigEntry { - public IntPtr namePtr; - public IntPtr valuePtr; + public char* namePtr; + public char* valuePtr; public uint level; - public IntPtr freePtr; - public IntPtr payloadPtr; + public void* freePtr; + public void* payloadPtr; } } diff --git a/LibGit2Sharp/Core/Handles/GitConfigEntryHandle.cs b/LibGit2Sharp/Core/Handles/GitConfigEntryHandle.cs deleted file mode 100644 index 677c5fbdc..000000000 --- a/LibGit2Sharp/Core/Handles/GitConfigEntryHandle.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class GitConfigEntryHandle : SafeHandleBase - { - public GitConfigEntry MarshalAsGitConfigEntry() - { - return handle.MarshalAs(); - } - - protected override bool ReleaseHandleImpl() - { - Proxy.git_config_entry_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index ed8bad349..06088cd12 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -348,11 +348,11 @@ internal static extern int git_config_delete_multivar( internal static extern void git_config_free(IntPtr cfg); [DllImport(libgit2)] - internal static extern void git_config_entry_free(IntPtr entry); + internal static extern unsafe void git_config_entry_free(GitConfigEntry* entry); [DllImport(libgit2)] - internal static extern int git_config_get_entry( - out GitConfigEntryHandle entry, + internal static extern unsafe int git_config_get_entry( + out GitConfigEntry* entry, ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index dec711d24..c1db98494 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -473,42 +473,31 @@ public static void git_config_free(IntPtr config) NativeMethods.git_config_free(config); } - public static void git_config_entry_free(IntPtr entry) + public static unsafe ConfigurationEntry git_config_get_entry(ConfigurationSafeHandle config, string key) { - NativeMethods.git_config_entry_free(entry); - } - - public static ConfigurationEntry git_config_get_entry(ConfigurationSafeHandle config, string key) - { - GitConfigEntryHandle handle = null; - if (!configurationParser.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } - GitConfigEntry entry; - + GitConfigEntry* entry = null; try { - var res = NativeMethods.git_config_get_entry(out handle, config, key); + var res = NativeMethods.git_config_get_entry(out entry, config, key); if (res == (int)GitErrorCode.NotFound) { return null; } Ensure.ZeroResult(res); - - entry = handle.MarshalAsGitConfigEntry(); + return new ConfigurationEntry(LaxUtf8Marshaler.FromNative(entry->namePtr), + (T)configurationParser[typeof(T)](LaxUtf8Marshaler.FromNative(entry->valuePtr)), + (ConfigurationLevel)entry->level); } finally { - handle.SafeDispose(); + NativeMethods.git_config_entry_free(entry); } - - return new ConfigurationEntry(LaxUtf8Marshaler.FromNative(entry.namePtr), - (T)configurationParser[typeof(T)](LaxUtf8Marshaler.FromNative(entry.valuePtr)), - (ConfigurationLevel)entry.level); } public static ConfigurationSafeHandle git_config_new() @@ -593,7 +582,7 @@ public static ICollection git_config_foreach( return git_foreach(resultSelector, c => NativeMethods.git_config_foreach(config, (e, p) => c(e, p), IntPtr.Zero)); } - public static IEnumerable> git_config_iterator_glob( + public static unsafe IEnumerable> git_config_iterator_glob( ConfigurationSafeHandle config, string regexp, Func> resultSelector) diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index bdcc523bf..5d5e4643d 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -241,7 +241,6 @@ - From e5aa4fbfe42aa1fbbb9df0a04f94bcf1d55544c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 11 Dec 2015 03:39:23 +0100 Subject: [PATCH 04/50] Use pointers for tree entries We wrap the owned handle in a IDisposable to keep the using() pattern. --- .../Core/Handles/TreeEntryOwnedHandle.cs | 19 +++++++++++++++++++ .../Core/Handles/TreeEntrySafeHandle_Owned.cs | 11 ----------- LibGit2Sharp/Core/NativeMethods.cs | 16 ++++++++-------- LibGit2Sharp/Core/Opaques.cs | 7 +++++++ LibGit2Sharp/Core/Proxy.cs | 18 +++++++++--------- LibGit2Sharp/LibGit2Sharp.csproj | 3 ++- LibGit2Sharp/Tree.cs | 19 +++++++++++-------- LibGit2Sharp/TreeEntry.cs | 10 +++++----- 8 files changed, 61 insertions(+), 42 deletions(-) create mode 100644 LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/TreeEntrySafeHandle_Owned.cs create mode 100644 LibGit2Sharp/Core/Opaques.cs diff --git a/LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs b/LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs new file mode 100644 index 000000000..ddd253c52 --- /dev/null +++ b/LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs @@ -0,0 +1,19 @@ +using System; + +namespace LibGit2Sharp.Core.Handles +{ + internal unsafe class TreeEntryOwnedHandle : IDisposable + { + internal git_tree_entry* Handle { get; set; } + + internal TreeEntryOwnedHandle(git_tree_entry* entry) + { + Handle = entry; + } + + public void Dispose() + { + Proxy.git_tree_entry_free(Handle); + } + } +} diff --git a/LibGit2Sharp/Core/Handles/TreeEntrySafeHandle_Owned.cs b/LibGit2Sharp/Core/Handles/TreeEntrySafeHandle_Owned.cs deleted file mode 100644 index f2d63e13f..000000000 --- a/LibGit2Sharp/Core/Handles/TreeEntrySafeHandle_Owned.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class TreeEntrySafeHandle_Owned : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_tree_entry_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 06088cd12..4309090c7 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1737,29 +1737,29 @@ internal static extern int git_transport_unregister( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string prefix); [DllImport(libgit2)] - internal static extern uint git_tree_entry_filemode(SafeHandle entry); + internal static extern unsafe uint git_tree_entry_filemode(git_tree_entry* entry); [DllImport(libgit2)] - internal static extern TreeEntrySafeHandle git_tree_entry_byindex(GitObjectSafeHandle tree, UIntPtr idx); + internal static extern unsafe git_tree_entry* git_tree_entry_byindex(GitObjectSafeHandle tree, UIntPtr idx); [DllImport(libgit2)] - internal static extern int git_tree_entry_bypath( - out TreeEntrySafeHandle_Owned tree, + internal static extern unsafe int git_tree_entry_bypath( + out git_tree_entry* tree, GitObjectSafeHandle root, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath treeentry_path); [DllImport(libgit2)] - internal static extern void git_tree_entry_free(IntPtr treeEntry); + internal static extern unsafe void git_tree_entry_free(git_tree_entry* treeEntry); [DllImport(libgit2)] - internal static extern OidSafeHandle git_tree_entry_id(SafeHandle entry); + internal static extern unsafe OidSafeHandle git_tree_entry_id(git_tree_entry* entry); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_tree_entry_name(SafeHandle entry); + internal static extern unsafe string git_tree_entry_name(git_tree_entry* entry); [DllImport(libgit2)] - internal static extern GitObjectType git_tree_entry_type(SafeHandle entry); + internal static extern unsafe GitObjectType git_tree_entry_type(git_tree_entry* entry); [DllImport(libgit2)] internal static extern UIntPtr git_tree_entrycount(GitObjectSafeHandle tree); diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs new file mode 100644 index 000000000..f13e62945 --- /dev/null +++ b/LibGit2Sharp/Core/Opaques.cs @@ -0,0 +1,7 @@ +using System; + +namespace LibGit2Sharp.Core +{ + internal struct git_tree_entry {} +} + diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index c1db98494..3eb7b5f4d 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -3156,21 +3156,21 @@ public static void git_transport_unregister(String prefix) #region git_tree_ - public static Mode git_tree_entry_attributes(SafeHandle entry) + public static unsafe Mode git_tree_entry_attributes(git_tree_entry* entry) { return (Mode)NativeMethods.git_tree_entry_filemode(entry); } - public static TreeEntrySafeHandle git_tree_entry_byindex(GitObjectSafeHandle tree, long idx) + public static unsafe git_tree_entry* git_tree_entry_byindex(GitObjectSafeHandle tree, long idx) { return NativeMethods.git_tree_entry_byindex(tree, (UIntPtr)idx); } - public static TreeEntrySafeHandle_Owned git_tree_entry_bypath(RepositorySafeHandle repo, ObjectId id, FilePath treeentry_path) + public static unsafe TreeEntryOwnedHandle git_tree_entry_bypath(RepositorySafeHandle repo, ObjectId id, FilePath treeentry_path) { using (var obj = new ObjectSafeWrapper(id, repo)) { - TreeEntrySafeHandle_Owned treeEntryPtr; + git_tree_entry* treeEntryPtr; int res = NativeMethods.git_tree_entry_bypath(out treeEntryPtr, obj.ObjectPtr, treeentry_path); if (res == (int)GitErrorCode.NotFound) @@ -3180,26 +3180,26 @@ public static TreeEntrySafeHandle_Owned git_tree_entry_bypath(RepositorySafeHand Ensure.ZeroResult(res); - return treeEntryPtr; + return new TreeEntryOwnedHandle(treeEntryPtr); } } - public static void git_tree_entry_free(IntPtr treeEntry) + public static unsafe void git_tree_entry_free(git_tree_entry* treeEntry) { NativeMethods.git_tree_entry_free(treeEntry); } - public static ObjectId git_tree_entry_id(SafeHandle entry) + public static unsafe ObjectId git_tree_entry_id(git_tree_entry* entry) { return NativeMethods.git_tree_entry_id(entry).MarshalAsObjectId(); } - public static string git_tree_entry_name(SafeHandle entry) + public static unsafe string git_tree_entry_name(git_tree_entry* entry) { return NativeMethods.git_tree_entry_name(entry); } - public static GitObjectType git_tree_entry_type(SafeHandle entry) + public static unsafe GitObjectType git_tree_entry_type(git_tree_entry* entry) { return NativeMethods.git_tree_entry_type(entry); } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 5d5e4643d..1b3219771 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -287,7 +287,6 @@ - @@ -381,6 +380,8 @@ + + diff --git a/LibGit2Sharp/Tree.cs b/LibGit2Sharp/Tree.cs index 08e867d84..a8b761ac7 100644 --- a/LibGit2Sharp/Tree.cs +++ b/LibGit2Sharp/Tree.cs @@ -47,16 +47,16 @@ public virtual TreeEntry this[string relativePath] get { return RetrieveFromPath(relativePath); } } - private TreeEntry RetrieveFromPath(FilePath relativePath) + private unsafe TreeEntry RetrieveFromPath(FilePath relativePath) { if (relativePath.IsNullOrEmpty()) { return null; } - using (TreeEntrySafeHandle_Owned treeEntryPtr = Proxy.git_tree_entry_bypath(repo.Handle, Id, relativePath)) + using (TreeEntryOwnedHandle treeEntry = Proxy.git_tree_entry_bypath(repo.Handle, Id, relativePath)) { - if (treeEntryPtr == null) + if (treeEntry == null) { return null; } @@ -64,7 +64,7 @@ private TreeEntry RetrieveFromPath(FilePath relativePath) string posixPath = relativePath.Posix; string filename = posixPath.Split('/').Last(); string parentPath = posixPath.Substring(0, posixPath.Length - filename.Length); - return new TreeEntry(treeEntryPtr, Id, repo, path.Combine(parentPath)); + return new TreeEntry(treeEntry.Handle, Id, repo, path.Combine(parentPath)); } } @@ -75,6 +75,11 @@ internal string Path #region IEnumerable Members + unsafe TreeEntry byIndex(ObjectSafeWrapper obj, uint i, ObjectId parentTreeId, Repository repo, FilePath parentPath) + { + return new TreeEntry(Proxy.git_tree_entry_byindex(obj.ObjectPtr, i), parentTreeId, repo, parentPath); + } + /// /// Returns an enumerator that iterates through the collection. /// @@ -83,10 +88,8 @@ public virtual IEnumerator GetEnumerator() { using (var obj = new ObjectSafeWrapper(Id, repo.Handle)) { - for (uint i = 0; i < Count; i++) - { - TreeEntrySafeHandle handle = Proxy.git_tree_entry_byindex(obj.ObjectPtr, i); - yield return new TreeEntry(handle, Id, repo, path); + for (uint i = 0; i < Count; i++) { + yield return byIndex(obj, i, Id, repo, path); } } } diff --git a/LibGit2Sharp/TreeEntry.cs b/LibGit2Sharp/TreeEntry.cs index 30ced73c2..7f2879e49 100644 --- a/LibGit2Sharp/TreeEntry.cs +++ b/LibGit2Sharp/TreeEntry.cs @@ -27,19 +27,19 @@ public class TreeEntry : IEquatable protected TreeEntry() { } - internal TreeEntry(SafeHandle obj, ObjectId parentTreeId, Repository repo, FilePath parentPath) + internal unsafe TreeEntry(git_tree_entry* entry, ObjectId parentTreeId, Repository repo, FilePath parentPath) { this.parentTreeId = parentTreeId; this.repo = repo; - targetOid = Proxy.git_tree_entry_id(obj); + targetOid = Proxy.git_tree_entry_id(entry); - GitObjectType treeEntryTargetType = Proxy.git_tree_entry_type(obj); + GitObjectType treeEntryTargetType = Proxy.git_tree_entry_type(entry); TargetType = treeEntryTargetType.ToTreeEntryTargetType(); target = new Lazy(RetrieveTreeEntryTarget); - Mode = Proxy.git_tree_entry_attributes(obj); - Name = Proxy.git_tree_entry_name(obj); + Mode = Proxy.git_tree_entry_attributes(entry); + Name = Proxy.git_tree_entry_name(entry); path = new Lazy(() => System.IO.Path.Combine(parentPath.Native, Name)); } From 7445d4cf82a46efe9a61da8822c1b94bfeb1359c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 11 Dec 2015 09:33:13 +0100 Subject: [PATCH 05/50] Use pointers for git references The public methods use the disposable wrapper so we don't have to mark them as unsafe. --- LibGit2Sharp/BranchCollection.cs | 4 +- .../Core/Handles/GitReferenceHandle.cs | 38 ++++++ .../Core/Handles/ReferenceSafeHandle.cs | 11 -- LibGit2Sharp/Core/NativeMethods.cs | 62 +++++----- LibGit2Sharp/Core/Opaques.cs | 1 + LibGit2Sharp/Core/Proxy.cs | 112 +++++++++--------- LibGit2Sharp/LibGit2Sharp.csproj | 2 +- LibGit2Sharp/Rebase.cs | 12 +- LibGit2Sharp/Reference.cs | 8 +- LibGit2Sharp/ReferenceCollection.cs | 24 ++-- LibGit2Sharp/Repository.cs | 4 +- 11 files changed, 155 insertions(+), 123 deletions(-) create mode 100644 LibGit2Sharp/Core/Handles/GitReferenceHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/ReferenceSafeHandle.cs diff --git a/LibGit2Sharp/BranchCollection.cs b/LibGit2Sharp/BranchCollection.cs index 803e28d00..f0a7c937b 100644 --- a/LibGit2Sharp/BranchCollection.cs +++ b/LibGit2Sharp/BranchCollection.cs @@ -199,7 +199,7 @@ public virtual void Remove(Branch branch) { Ensure.ArgumentNotNull(branch, "branch"); - using (ReferenceSafeHandle referencePtr = repo.Refs.RetrieveReferencePtr(branch.CanonicalName)) + using (GitReferenceHandle referencePtr = repo.Refs.RetrieveReferencePtr(branch.CanonicalName)) { Proxy.git_branch_delete(referencePtr); } @@ -267,7 +267,7 @@ public virtual Branch Rename(Branch branch, string newName, bool allowOverwrite) branch.FriendlyName); } - using (ReferenceSafeHandle referencePtr = repo.Refs.RetrieveReferencePtr(Reference.LocalBranchPrefix + branch.FriendlyName)) + using (GitReferenceHandle referencePtr = repo.Refs.RetrieveReferencePtr(Reference.LocalBranchPrefix + branch.FriendlyName)) { using (Proxy.git_branch_move(referencePtr, newName, allowOverwrite)) { } diff --git a/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs b/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs new file mode 100644 index 000000000..976121c52 --- /dev/null +++ b/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs @@ -0,0 +1,38 @@ +using System; + +namespace LibGit2Sharp.Core.Handles +{ + internal unsafe class GitReferenceHandle : IDisposable + { + git_reference* ptr; + + internal GitReferenceHandle(git_reference* refPtr) + { + this.ptr = refPtr; + } + + ~GitReferenceHandle() + { + Dispose(); + } + + internal git_reference* ToPointer() + { + return ptr; + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + public void Dispose() + { + NativeMethods.git_reference_free(new IntPtr(ptr)); + ptr = null; + } + } +} diff --git a/LibGit2Sharp/Core/Handles/ReferenceSafeHandle.cs b/LibGit2Sharp/Core/Handles/ReferenceSafeHandle.cs deleted file mode 100644 index 9ac7d1f7e..000000000 --- a/LibGit2Sharp/Core/Handles/ReferenceSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class ReferenceSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_reference_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 4309090c7..9455e440c 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -145,16 +145,16 @@ internal static extern int git_blob_filtered_content( internal static extern Int64 git_blob_rawsize(GitObjectSafeHandle blob); [DllImport(libgit2)] - internal static extern int git_branch_create_from_annotated( - out ReferenceSafeHandle ref_out, + internal static extern unsafe int git_branch_create_from_annotated( + out git_reference* ref_out, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string branch_name, GitAnnotatedCommitHandle target, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] - internal static extern int git_branch_delete( - ReferenceSafeHandle reference); + internal static extern unsafe int git_branch_delete( + git_reference* reference); internal delegate int branch_foreach_callback( IntPtr branch_name, @@ -172,15 +172,15 @@ internal static extern int git_branch_iterator_new( GitBranchType branch_type); [DllImport(libgit2)] - internal static extern int git_branch_move( - out ReferenceSafeHandle ref_out, - ReferenceSafeHandle reference, + internal static extern unsafe int git_branch_move( + out git_reference* ref_out, + git_reference* reference, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string new_branch_name, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_branch_next( - out ReferenceSafeHandle ref_out, + out IntPtr ref_out, out GitBranchType type_out, BranchIteratorSafeHandle iter); @@ -741,10 +741,10 @@ internal static extern int git_merge_base_octopus( [In] GitOid[] input_array); [DllImport(libgit2)] - internal static extern int git_annotated_commit_from_ref( + internal static extern unsafe int git_annotated_commit_from_ref( out GitAnnotatedCommitHandle annotatedCommit, RepositorySafeHandle repo, - ReferenceSafeHandle reference); + git_reference* reference); [DllImport(libgit2)] internal static extern int git_annotated_commit_from_fetchhead( @@ -984,8 +984,8 @@ internal static extern int git_packbuilder_write( internal static extern UInt32 git_packbuilder_written(PackBuilderSafeHandle packbuilder); [DllImport(libgit2)] - internal static extern int git_reference_create( - out ReferenceSafeHandle reference, + internal static extern unsafe int git_reference_create( + out git_reference* reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, ref GitOid oid, @@ -993,8 +993,8 @@ internal static extern int git_reference_create( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string log_message); [DllImport(libgit2)] - internal static extern int git_reference_symbolic_create( - out ReferenceSafeHandle reference, + internal static extern unsafe int git_reference_symbolic_create( + out git_reference* reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string target, @@ -1023,14 +1023,14 @@ internal static extern int git_reference_is_valid_name( internal static extern int git_reference_list(out GitStrArray array, RepositorySafeHandle repo); [DllImport(libgit2)] - internal static extern int git_reference_lookup( - out ReferenceSafeHandle reference, + internal static extern unsafe int git_reference_lookup( + out git_reference* reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_reference_name(ReferenceSafeHandle reference); + internal static extern unsafe string git_reference_name(git_reference* reference); [DllImport(libgit2)] internal static extern int git_reference_remove( @@ -1038,36 +1038,36 @@ internal static extern int git_reference_remove( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern OidSafeHandle git_reference_target(ReferenceSafeHandle reference); + internal static extern unsafe OidSafeHandle git_reference_target(git_reference* reference); [DllImport(libgit2)] - internal static extern int git_reference_rename( - out ReferenceSafeHandle ref_out, - ReferenceSafeHandle reference, + internal static extern unsafe int git_reference_rename( + out git_reference* ref_out, + git_reference* reference, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string newName, [MarshalAs(UnmanagedType.Bool)] bool force, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string log_message); [DllImport(libgit2)] - internal static extern int git_reference_set_target( - out ReferenceSafeHandle ref_out, - ReferenceSafeHandle reference, + internal static extern unsafe int git_reference_set_target( + out git_reference* ref_out, + git_reference* reference, ref GitOid id, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string log_message); [DllImport(libgit2)] - internal static extern int git_reference_symbolic_set_target( - out ReferenceSafeHandle ref_out, - ReferenceSafeHandle reference, + internal static extern unsafe int git_reference_symbolic_set_target( + out git_reference* ref_out, + git_reference* reference, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string target, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string log_message); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_reference_symbolic_target(ReferenceSafeHandle reference); + internal static extern unsafe string git_reference_symbolic_target(git_reference* reference); [DllImport(libgit2)] - internal static extern GitReferenceType git_reference_type(ReferenceSafeHandle reference); + internal static extern unsafe GitReferenceType git_reference_type(git_reference* reference); [DllImport(libgit2)] internal static extern int git_reference_ensure_log( @@ -1442,9 +1442,9 @@ internal static extern int git_revert( GitRevertOpts opts); [DllImport(libgit2)] - internal static extern int git_revparse_ext( + internal static extern unsafe int git_revparse_ext( out GitObjectSafeHandle obj, - out ReferenceSafeHandle reference, + out git_reference* reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string spec); diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index f13e62945..25f77be68 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -3,5 +3,6 @@ namespace LibGit2Sharp.Core { internal struct git_tree_entry {} + internal struct git_reference { } } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 3eb7b5f4d..3fca7d3f1 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -190,9 +190,9 @@ public static bool git_blob_is_binary(GitObjectSafeHandle obj) #region git_branch_ - public static ReferenceSafeHandle git_branch_create_from_annotated(RepositorySafeHandle repo, string branch_name, string targetIdentifier, bool force) + public static unsafe GitReferenceHandle git_branch_create_from_annotated(RepositorySafeHandle repo, string branch_name, string targetIdentifier, bool force) { - ReferenceSafeHandle reference; + git_reference* reference; using (var annotatedCommit = git_annotated_commit_from_revspec(repo, targetIdentifier)) { @@ -200,28 +200,29 @@ public static ReferenceSafeHandle git_branch_create_from_annotated(RepositorySaf Ensure.ZeroResult(res); } - return reference; + return new GitReferenceHandle(reference); } - public static void git_branch_delete(ReferenceSafeHandle reference) + public static unsafe void git_branch_delete(GitReferenceHandle reference) { - int res = NativeMethods.git_branch_delete(reference); + int res = NativeMethods.git_branch_delete(reference.ToPointer()); Ensure.ZeroResult(res); } - public static IEnumerable git_branch_iterator(Repository repo, GitBranchType branchType) + public static unsafe IEnumerable git_branch_iterator(Repository repo, GitBranchType branchType) { return git_iterator((out BranchIteratorSafeHandle iter_out) => NativeMethods.git_branch_iterator_new(out iter_out, repo.Handle, branchType), - (BranchIteratorSafeHandle iter, out ReferenceSafeHandle ref_out, out int res) => + (BranchIteratorSafeHandle iter, out IntPtr refPtr, out int res) => { GitBranchType type_out; - res = NativeMethods.git_branch_next(out ref_out, out type_out, iter); + res = NativeMethods.git_branch_next(out refPtr, out type_out, iter); return new { BranchType = type_out }; }, (handle, payload) => { - var reference = Reference.BuildFromPtr(handle, repo); + git_reference* refPtr = (git_reference*)handle.ToPointer(); + var reference = Reference.BuildFromPtr(refPtr, repo); return new Branch(repo, reference, reference.CanonicalName); }); } @@ -231,12 +232,12 @@ public static void git_branch_iterator_free(IntPtr iter) NativeMethods.git_branch_iterator_free(iter); } - public static ReferenceSafeHandle git_branch_move(ReferenceSafeHandle reference, string new_branch_name, bool force) + public static unsafe GitReferenceHandle git_branch_move(GitReferenceHandle reference, string new_branch_name, bool force) { - ReferenceSafeHandle ref_out; - int res = NativeMethods.git_branch_move(out ref_out, reference, new_branch_name, force); + git_reference* ref_out; + int res = NativeMethods.git_branch_move(out ref_out, reference.ToPointer(), new_branch_name, force); Ensure.ZeroResult(res); - return ref_out; + return new GitReferenceHandle(ref_out); } public static string git_branch_remote_name(RepositorySafeHandle repo, string canonical_branch_name, bool shouldThrowIfNotFound) @@ -589,10 +590,9 @@ public static unsafe IEnumerable> git_config_iterator { return git_iterator((out ConfigurationIteratorSafeHandle iter) => NativeMethods.git_config_iterator_glob_new(out iter, config, regexp), - (ConfigurationIteratorSafeHandle iter, out SafeHandleBase handle, out int res) => + (ConfigurationIteratorSafeHandle iter, out IntPtr handle, out int res) => { - handle = null; - + handle = IntPtr.Zero; IntPtr entry; res = NativeMethods.git_config_next(out entry, iter); return new { EntryPtr = entry }; @@ -1151,11 +1151,11 @@ public static GitAnnotatedCommitHandle git_annotated_commit_lookup(RepositorySaf return their_head; } - public static GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositorySafeHandle repo, ReferenceSafeHandle reference) + public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositorySafeHandle repo, GitReferenceHandle reference) { GitAnnotatedCommitHandle their_head; - int res = NativeMethods.git_annotated_commit_from_ref(out their_head, repo, reference); + int res = NativeMethods.git_annotated_commit_from_ref(out their_head, repo, reference.ToPointer()); Ensure.ZeroResult(res); @@ -1777,7 +1777,7 @@ public static void git_rebase_free(IntPtr rebase) #region git_reference_ - public static ReferenceSafeHandle git_reference_create( + public static unsafe GitReferenceHandle git_reference_create( RepositorySafeHandle repo, string name, ObjectId targetId, @@ -1785,27 +1785,27 @@ public static ReferenceSafeHandle git_reference_create( string logMessage) { GitOid oid = targetId.Oid; - ReferenceSafeHandle handle; + git_reference* handle; int res = NativeMethods.git_reference_create(out handle, repo, name, ref oid, allowOverwrite, logMessage); Ensure.ZeroResult(res); - return handle; + return new GitReferenceHandle(handle); } - public static ReferenceSafeHandle git_reference_symbolic_create( + public static unsafe GitReferenceHandle git_reference_symbolic_create( RepositorySafeHandle repo, string name, string target, bool allowOverwrite, string logMessage) { - ReferenceSafeHandle handle; + git_reference* handle; int res = NativeMethods.git_reference_symbolic_create(out handle, repo, name, target, allowOverwrite, logMessage); Ensure.ZeroResult(res); - return handle; + return new GitReferenceHandle(handle); } public static ICollection git_reference_foreach_glob( @@ -1846,9 +1846,9 @@ public static IList git_reference_list(RepositorySafeHandle repo) } } - public static ReferenceSafeHandle git_reference_lookup(RepositorySafeHandle repo, string name, bool shouldThrowIfNotFound) + public static unsafe GitReferenceHandle git_reference_lookup(RepositorySafeHandle repo, string name, bool shouldThrowIfNotFound) { - ReferenceSafeHandle handle; + git_reference* handle; int res = NativeMethods.git_reference_lookup(out handle, repo, name); if (!shouldThrowIfNotFound && res == (int)GitErrorCode.NotFound) @@ -1858,10 +1858,10 @@ public static ReferenceSafeHandle git_reference_lookup(RepositorySafeHandle repo Ensure.ZeroResult(res); - return handle; + return new GitReferenceHandle(handle); } - public static string git_reference_name(ReferenceSafeHandle reference) + public static unsafe string git_reference_name(git_reference* reference) { return NativeMethods.git_reference_name(reference); } @@ -1872,52 +1872,52 @@ public static void git_reference_remove(RepositorySafeHandle repo, string name) Ensure.ZeroResult(res); } - public static ObjectId git_reference_target(ReferenceSafeHandle reference) + public static unsafe ObjectId git_reference_target(git_reference* reference) { return NativeMethods.git_reference_target(reference).MarshalAsObjectId(); } - public static ReferenceSafeHandle git_reference_rename( - ReferenceSafeHandle reference, + public static unsafe GitReferenceHandle git_reference_rename( + GitReferenceHandle reference, string newName, bool allowOverwrite, string logMessage) { - ReferenceSafeHandle ref_out; + git_reference* ref_out; - int res = NativeMethods.git_reference_rename(out ref_out, reference, newName, allowOverwrite, logMessage); + int res = NativeMethods.git_reference_rename(out ref_out, reference.ToPointer(), newName, allowOverwrite, logMessage); Ensure.ZeroResult(res); - return ref_out; + return new GitReferenceHandle(ref_out); } - public static ReferenceSafeHandle git_reference_set_target(ReferenceSafeHandle reference, ObjectId id, string logMessage) + public static unsafe GitReferenceHandle git_reference_set_target(GitReferenceHandle reference, ObjectId id, string logMessage) { GitOid oid = id.Oid; - ReferenceSafeHandle ref_out; + git_reference* ref_out; - int res = NativeMethods.git_reference_set_target(out ref_out, reference, ref oid, logMessage); + int res = NativeMethods.git_reference_set_target(out ref_out, reference.ToPointer(), ref oid, logMessage); Ensure.ZeroResult(res); - return ref_out; + return new GitReferenceHandle(ref_out); } - public static ReferenceSafeHandle git_reference_symbolic_set_target(ReferenceSafeHandle reference, string target, string logMessage) + public static unsafe GitReferenceHandle git_reference_symbolic_set_target(GitReferenceHandle reference, string target, string logMessage) { - ReferenceSafeHandle ref_out; + git_reference* ref_out; - int res = NativeMethods.git_reference_symbolic_set_target(out ref_out, reference, target, logMessage); + int res = NativeMethods.git_reference_symbolic_set_target(out ref_out, reference.ToPointer(), target, logMessage); Ensure.ZeroResult(res); - return ref_out; + return new GitReferenceHandle(ref_out); } - public static string git_reference_symbolic_target(ReferenceSafeHandle reference) + public static unsafe string git_reference_symbolic_target(git_reference* reference) { return NativeMethods.git_reference_symbolic_target(reference); } - public static GitReferenceType git_reference_type(ReferenceSafeHandle reference) + public static unsafe GitReferenceType git_reference_type(git_reference* reference) { return NativeMethods.git_reference_type(reference); } @@ -2600,10 +2600,10 @@ public static void git_revert( #region git_revparse_ - public static Tuple git_revparse_ext(RepositorySafeHandle repo, string objectish) + public static unsafe Tuple git_revparse_ext(RepositorySafeHandle repo, string objectish) { GitObjectSafeHandle obj; - ReferenceSafeHandle reference; + git_reference* reference; int res = NativeMethods.git_revparse_ext(out obj, out reference, repo, objectish); switch (res) @@ -2620,7 +2620,7 @@ public static Tuple git_revparse_ext(R break; } - return new Tuple(obj, reference); + return new Tuple(obj, new GitReferenceHandle(reference)); } public static GitObjectSafeHandle git_revparse_single(RepositorySafeHandle repo, string objectish) @@ -3410,15 +3410,14 @@ private static THandle git_iterator_new(IteratorNew newFunc) return iter; } - private static IEnumerable git_iterator_next( + private static IEnumerable git_iterator_next( TIterator iter, - IteratorNext nextFunc, - Func resultSelector) - where THandle : SafeHandleBase + IteratorNext nextFunc, + Func resultSelector) { while (true) { - var next = default(THandle); + var next = IntPtr.Zero; try { int res; @@ -3434,18 +3433,17 @@ private static IEnumerable git_iterator_next git_iterator( + private static IEnumerable git_iterator( IteratorNew newFunc, - IteratorNext nextFunc, - Func resultSelector + IteratorNext nextFunc, + Func resultSelector ) where TIterator : SafeHandleBase - where THandle : SafeHandleBase { using (var iter = git_iterator_new(newFunc)) { diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 1b3219771..8d39ecb08 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -73,6 +73,7 @@ + @@ -287,7 +288,6 @@ - diff --git a/LibGit2Sharp/Rebase.cs b/LibGit2Sharp/Rebase.cs index c479f12ca..5e2019627 100644 --- a/LibGit2Sharp/Rebase.cs +++ b/LibGit2Sharp/Rebase.cs @@ -85,15 +85,15 @@ public virtual RebaseResult Start(Branch branch, Branch upstream, Branch onto, I this.repository.Info.CurrentOperation); } - Func RefHandleFromBranch = (Branch b) => + Func RefHandleFromBranch = (Branch b) => { return (b == null) ? null : this.repository.Refs.RetrieveReferencePtr(b.CanonicalName); }; - Func AnnotatedCommitHandleFromRefHandle = - (ReferenceSafeHandle refHandle) => + Func AnnotatedCommitHandleFromRefHandle = + (GitReferenceHandle refHandle) => { return (refHandle == null) ? new GitAnnotatedCommitHandle() : @@ -108,9 +108,9 @@ public virtual RebaseResult Start(Branch branch, Branch upstream, Branch onto, I checkout_options = checkoutOptionsWrapper.Options, }; - using (ReferenceSafeHandle branchRefPtr = RefHandleFromBranch(branch)) - using (ReferenceSafeHandle upstreamRefPtr = RefHandleFromBranch(upstream)) - using (ReferenceSafeHandle ontoRefPtr = RefHandleFromBranch(onto)) + using (GitReferenceHandle branchRefPtr = RefHandleFromBranch(branch)) + using (GitReferenceHandle upstreamRefPtr = RefHandleFromBranch(upstream)) + using (GitReferenceHandle ontoRefPtr = RefHandleFromBranch(onto)) using (GitAnnotatedCommitHandle annotatedBranchCommitHandle = AnnotatedCommitHandleFromRefHandle(branchRefPtr)) using (GitAnnotatedCommitHandle upstreamRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(upstreamRefPtr)) using (GitAnnotatedCommitHandle ontoRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(ontoRefPtr)) diff --git a/LibGit2Sharp/Reference.cs b/LibGit2Sharp/Reference.cs index fa6d9be9e..20da027a9 100644 --- a/LibGit2Sharp/Reference.cs +++ b/LibGit2Sharp/Reference.cs @@ -36,7 +36,13 @@ internal Reference(IRepository repo, string canonicalName, string targetIdentifi this.targetIdentifier = targetIdentifier; } - internal static T BuildFromPtr(ReferenceSafeHandle handle, Repository repo) where T : Reference + // This overload lets public-facing methods avoid having to use the pointers directly + internal static unsafe T BuildFromPtr(GitReferenceHandle handle, Repository repo) where T : Reference + { + return BuildFromPtr(handle.ToPointer(), repo); + } + + internal static unsafe T BuildFromPtr(git_reference* handle, Repository repo) where T : Reference { GitReferenceType type = Proxy.git_reference_type(handle); string name = Proxy.git_reference_name(handle); diff --git a/LibGit2Sharp/ReferenceCollection.cs b/LibGit2Sharp/ReferenceCollection.cs index e91115445..b8692f1f7 100644 --- a/LibGit2Sharp/ReferenceCollection.cs +++ b/LibGit2Sharp/ReferenceCollection.cs @@ -124,7 +124,7 @@ public virtual Reference Add(string name, string canonicalRefNameOrObjectish, st if (refState == RefState.DoesNotExistButLooksValid && gitObject == null) { - using (ReferenceSafeHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, name, canonicalRefNameOrObjectish, allowOverwrite, + using (GitReferenceHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, name, canonicalRefNameOrObjectish, allowOverwrite, logMessage)) { return Reference.BuildFromPtr(handle, repo); @@ -191,7 +191,7 @@ public virtual DirectReference Add(string name, ObjectId targetId, string logMes Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(targetId, "targetId"); - using (ReferenceSafeHandle handle = Proxy.git_reference_create(repo.Handle, name, targetId, allowOverwrite, logMessage)) + using (GitReferenceHandle handle = Proxy.git_reference_create(repo.Handle, name, targetId, allowOverwrite, logMessage)) { return (DirectReference)Reference.BuildFromPtr(handle, repo); } @@ -245,7 +245,7 @@ public virtual SymbolicReference Add(string name, Reference targetRef, string lo Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(targetRef, "targetRef"); - using (ReferenceSafeHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, + using (GitReferenceHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, name, targetRef.CanonicalName, allowOverwrite, @@ -343,8 +343,8 @@ public virtual Reference Rename(Reference reference, string newName, string logM newName); } - using (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(reference.CanonicalName)) - using (ReferenceSafeHandle handle = Proxy.git_reference_rename(referencePtr, newName, allowOverwrite, logMessage)) + using (GitReferenceHandle referencePtr = RetrieveReferencePtr(reference.CanonicalName)) + using (GitReferenceHandle handle = Proxy.git_reference_rename(referencePtr, newName, allowOverwrite, logMessage)) { return Reference.BuildFromPtr(handle, repo); } @@ -438,7 +438,7 @@ internal T Resolve(string name) where T : Reference { Ensure.ArgumentNotNullOrEmptyString(name, "name"); - using (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(name, false)) + using (GitReferenceHandle referencePtr = RetrieveReferencePtr(name, false)) { return referencePtr == null ? null @@ -468,8 +468,8 @@ public virtual Reference UpdateTarget(Reference directRef, ObjectId targetId, st private Reference UpdateDirectReferenceTarget(Reference directRef, ObjectId targetId, string logMessage) { - using (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(directRef.CanonicalName)) - using (ReferenceSafeHandle handle = Proxy.git_reference_set_target(referencePtr, targetId, logMessage)) + using (GitReferenceHandle referencePtr = RetrieveReferencePtr(directRef.CanonicalName)) + using (GitReferenceHandle handle = Proxy.git_reference_set_target(referencePtr, targetId, logMessage)) { return Reference.BuildFromPtr(handle, repo); } @@ -594,8 +594,8 @@ public virtual Reference UpdateTarget(Reference symbolicRef, Reference targetRef private Reference UpdateSymbolicRefenceTarget(Reference symbolicRef, Reference targetRef, string logMessage) { - using (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(symbolicRef.CanonicalName)) - using (ReferenceSafeHandle handle = Proxy.git_reference_symbolic_set_target(referencePtr, targetRef.CanonicalName, logMessage)) + using (GitReferenceHandle referencePtr = RetrieveReferencePtr(symbolicRef.CanonicalName)) + using (GitReferenceHandle handle = Proxy.git_reference_symbolic_set_target(referencePtr, targetRef.CanonicalName, logMessage)) { return Reference.BuildFromPtr(handle, repo); } @@ -671,9 +671,9 @@ internal Reference UpdateHeadTarget(string target, string logMessage) return repo.Refs.Head; } - internal ReferenceSafeHandle RetrieveReferencePtr(string referenceName, bool shouldThrowIfNotFound = true) + internal GitReferenceHandle RetrieveReferencePtr(string referenceName, bool shouldThrowIfNotFound = true) { - ReferenceSafeHandle reference = Proxy.git_reference_lookup(repo.Handle, referenceName, shouldThrowIfNotFound); + GitReferenceHandle reference = Proxy.git_reference_lookup(repo.Handle, referenceName, shouldThrowIfNotFound); return reference; } diff --git a/LibGit2Sharp/Repository.cs b/LibGit2Sharp/Repository.cs index 6c55a1eae..948daf7a5 100644 --- a/LibGit2Sharp/Repository.cs +++ b/LibGit2Sharp/Repository.cs @@ -857,7 +857,7 @@ public Branch Checkout(string committishOrBranchSpec, CheckoutOptions options) GitObject obj; try { - if (!refH.IsInvalid) + if (!refH.IsNull) { var reference = Reference.BuildFromPtr(refH, this); if (reference.IsLocalBranch) @@ -1225,7 +1225,7 @@ public MergeResult Merge(Branch branch, Signature merger, MergeOptions options) options = options ?? new MergeOptions(); - using (ReferenceSafeHandle referencePtr = Refs.RetrieveReferencePtr(branch.CanonicalName)) + using (GitReferenceHandle referencePtr = Refs.RetrieveReferencePtr(branch.CanonicalName)) using (GitAnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_from_ref(Handle, referencePtr)) { return Merge(new[] { annotatedCommitHandle }, merger, options); From ed25e6976bdd71d9cd9ae55516f71268dcc75ea5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Sat, 12 Dec 2015 17:38:13 +0100 Subject: [PATCH 06/50] Use pointers for getting the list of advertised refs --- LibGit2Sharp/Core/GitOid.cs | 6 ++++++ LibGit2Sharp/Core/GitRemoteHead.cs | 12 ++++++------ LibGit2Sharp/Core/NativeMethods.cs | 4 +--- LibGit2Sharp/Core/Proxy.cs | 25 +++++++------------------ LibGit2Sharp/ObjectId.cs | 16 ++++++++++++++++ 5 files changed, 36 insertions(+), 27 deletions(-) diff --git a/LibGit2Sharp/Core/GitOid.cs b/LibGit2Sharp/Core/GitOid.cs index 0f1be6743..f466621b1 100644 --- a/LibGit2Sharp/Core/GitOid.cs +++ b/LibGit2Sharp/Core/GitOid.cs @@ -2,6 +2,12 @@ namespace LibGit2Sharp.Core { + internal struct git_oid + { + public const int Size = 20; + public unsafe fixed byte Id[20]; + } + /// /// Represents a unique id in git which is the sha1 hash of this id's content. /// diff --git a/LibGit2Sharp/Core/GitRemoteHead.cs b/LibGit2Sharp/Core/GitRemoteHead.cs index 02c2def8b..cbaf3c818 100644 --- a/LibGit2Sharp/Core/GitRemoteHead.cs +++ b/LibGit2Sharp/Core/GitRemoteHead.cs @@ -4,12 +4,12 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal struct GitRemoteHead + internal unsafe struct git_remote_head { - public bool Local; - public GitOid Oid; - public GitOid Loid; - public IntPtr NamePtr; - public IntPtr SymRefTargetPtr; + public int Local; + public git_oid Oid; + public git_oid Loid; + public char* Name; + public char* SymrefTarget; } } diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 9455e440c..ce803c086 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1244,10 +1244,8 @@ internal static extern int git_remote_lookup( RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); - internal delegate int git_headlist_cb(ref GitRemoteHead remoteHeadPtr, IntPtr payload); - [DllImport(libgit2)] - internal static extern int git_remote_ls(out IntPtr heads, out UIntPtr size, RemoteSafeHandle remote); + internal static extern unsafe int git_remote_ls(out git_remote_head** heads, out UIntPtr size, RemoteSafeHandle remote); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 3fca7d3f1..ca86384ac 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -2214,32 +2214,23 @@ public static IList git_remote_list(RepositorySafeHandle repo) } } - public static IEnumerable git_remote_ls(Repository repository, RemoteSafeHandle remote) + public static unsafe IEnumerable git_remote_ls(Repository repository, RemoteSafeHandle remote) { - IntPtr heads; + git_remote_head** heads; UIntPtr count; int res = NativeMethods.git_remote_ls(out heads, out count, remote); Ensure.ZeroResult(res); - var intCount = (int)count.ToUInt32(); - - if (intCount < 0) - { - throw new OverflowException(); - } - + var intCount = checked(count.ToUInt32()); var directRefs = new Dictionary(); var symRefs = new Dictionary(); - IntPtr currentHead = heads; - for (int i = 0; i < intCount; i++) { - var remoteHead = Marshal.ReadIntPtr(currentHead).MarshalAs(); - - string name = LaxUtf8Marshaler.FromNative(remoteHead.NamePtr); - string symRefTarget = LaxUtf8Marshaler.FromNative(remoteHead.SymRefTargetPtr); + git_remote_head* currentHead = heads[i]; + string name = LaxUtf8Marshaler.FromNative(currentHead->Name); + string symRefTarget = LaxUtf8Marshaler.FromNative(currentHead->SymrefTarget); // The name pointer should never be null - if it is, // this indicates a bug somewhere (libgit2, server, etc). @@ -2254,10 +2245,8 @@ public static IEnumerable git_remote_ls(Repository repository, Remote } else { - directRefs.Add(name, new DirectReference(name, repository, remoteHead.Oid)); + directRefs.Add(name, new DirectReference(name, repository, new ObjectId(currentHead->Oid.Id))); } - - currentHead = IntPtr.Add(currentHead, IntPtr.Size); } for (int i = 0; i < symRefs.Count; i++) diff --git a/LibGit2Sharp/ObjectId.cs b/LibGit2Sharp/ObjectId.cs index 8c4290741..5c569e9fd 100644 --- a/LibGit2Sharp/ObjectId.cs +++ b/LibGit2Sharp/ObjectId.cs @@ -57,6 +57,22 @@ public ObjectId(byte[] rawId) Ensure.ArgumentConformsTo(rawId, b => b.Length == rawSize, "rawId"); } + internal unsafe ObjectId(byte* rawId) + { + byte[] id = new byte[GitOid.Size]; + + fixed(byte* p = id) + { + for (int i = 0; i < rawSize; i++) + { + p[i] = rawId[i]; + } + } + + this.oid = new GitOid { Id = id }; + this.sha = ToString(oid.Id, oid.Id.Length * 2); + } + /// /// Initializes a new instance of the class. /// From 92fc8f54053408a4856bb5329c599faad044e2a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 14 Dec 2015 04:02:01 +0100 Subject: [PATCH 07/50] Use pointers to read the index entries --- LibGit2Sharp/Core/GitIndexEntry.cs | 24 +++++++++++++++++++++++ LibGit2Sharp/Core/NativeMethods.cs | 22 ++++++++++----------- LibGit2Sharp/Core/Proxy.cs | 31 ++++++++++++------------------ LibGit2Sharp/Index.cs | 10 +++++----- LibGit2Sharp/IndexEntry.cs | 16 +++++++-------- 5 files changed, 59 insertions(+), 44 deletions(-) diff --git a/LibGit2Sharp/Core/GitIndexEntry.cs b/LibGit2Sharp/Core/GitIndexEntry.cs index 11bee09ea..a8ea73d31 100644 --- a/LibGit2Sharp/Core/GitIndexEntry.cs +++ b/LibGit2Sharp/Core/GitIndexEntry.cs @@ -3,6 +3,30 @@ namespace LibGit2Sharp.Core { + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct git_index_mtime + { + public int seconds; + public uint nanoseconds; + } + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct git_index_entry + { + public git_index_mtime ctime; + public git_index_mtime mtime; + public uint dev; + public uint ino; + public uint mode; + public uint uid; + public uint gid; + public uint file_size; + public git_oid id; + public ushort flags; + public ushort extended_flags; + public char* path; + } + [StructLayout(LayoutKind.Sequential)] internal class GitIndexEntry { diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index ce803c086..b7a6913b4 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -634,10 +634,10 @@ internal static extern int git_index_add( GitIndexEntry entry); [DllImport(libgit2)] - internal static extern int git_index_conflict_get( - out IndexEntrySafeHandle ancestor, - out IndexEntrySafeHandle ours, - out IndexEntrySafeHandle theirs, + internal static extern unsafe int git_index_conflict_get( + out git_index_entry* ancestor, + out git_index_entry* ours, + out git_index_entry* theirs, IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); @@ -647,10 +647,10 @@ internal static extern int git_index_conflict_iterator_new( IndexSafeHandle index); [DllImport(libgit2)] - internal static extern int git_index_conflict_next( - out IndexEntrySafeHandle ancestor, - out IndexEntrySafeHandle ours, - out IndexEntrySafeHandle theirs, + internal static extern unsafe int git_index_conflict_next( + out git_index_entry* ancestor, + out git_index_entry* ours, + out git_index_entry* theirs, ConflictIteratorSafeHandle iterator); [DllImport(libgit2)] @@ -661,16 +661,16 @@ internal static extern void git_index_conflict_iterator_free( internal static extern UIntPtr git_index_entrycount(IndexSafeHandle index); [DllImport(libgit2)] - internal static extern int git_index_entry_stage(IndexEntrySafeHandle indexentry); + internal static extern unsafe int git_index_entry_stage(git_index_entry* indexentry); [DllImport(libgit2)] internal static extern void git_index_free(IntPtr index); [DllImport(libgit2)] - internal static extern IndexEntrySafeHandle git_index_get_byindex(IndexSafeHandle index, UIntPtr n); + internal static extern unsafe git_index_entry* git_index_get_byindex(IndexSafeHandle index, UIntPtr n); [DllImport(libgit2)] - internal static extern IndexEntrySafeHandle git_index_get_bypath( + internal static extern unsafe git_index_entry* git_index_get_bypath( IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, int stage); diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index ca86384ac..2514d8ff3 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -905,11 +905,11 @@ public static void git_index_add_bypath(IndexSafeHandle index, FilePath path) Ensure.ZeroResult(res); } - public static Conflict git_index_conflict_get( + public static unsafe Conflict git_index_conflict_get( IndexSafeHandle index, FilePath path) { - IndexEntrySafeHandle ancestor, ours, theirs; + git_index_entry* ancestor, ours, theirs; int res = NativeMethods.git_index_conflict_get(out ancestor, out ours, @@ -938,9 +938,9 @@ public static ConflictIteratorSafeHandle git_index_conflict_iterator_new(IndexSa return iter; } - public static Conflict git_index_conflict_next(ConflictIteratorSafeHandle iterator) + public static unsafe Conflict git_index_conflict_next(ConflictIteratorSafeHandle iterator) { - IndexEntrySafeHandle ancestor, ours, theirs; + git_index_entry* ancestor, ours, theirs; int res = NativeMethods.git_index_conflict_next(out ancestor, out ours, out theirs, iterator); @@ -951,14 +951,9 @@ public static Conflict git_index_conflict_next(ConflictIteratorSafeHandle iterat Ensure.ZeroResult(res); - using (ancestor) - using (ours) - using (theirs) - { - return new Conflict(IndexEntry.BuildFromPtr(ancestor), - IndexEntry.BuildFromPtr(ours), - IndexEntry.BuildFromPtr(theirs)); - } + return new Conflict(IndexEntry.BuildFromPtr(ancestor), + IndexEntry.BuildFromPtr(ours), + IndexEntry.BuildFromPtr(theirs)); } public static void git_index_conflict_iterator_free(IntPtr iterator) @@ -972,9 +967,9 @@ public static int git_index_entrycount(IndexSafeHandle index) .ConvertToInt(); } - public static StageLevel git_index_entry_stage(IndexEntrySafeHandle index) + public static unsafe StageLevel git_index_entry_stage(git_index_entry* entry) { - return (StageLevel)NativeMethods.git_index_entry_stage(index); + return (StageLevel)NativeMethods.git_index_entry_stage(entry); } public static void git_index_free(IntPtr index) @@ -982,16 +977,14 @@ public static void git_index_free(IntPtr index) NativeMethods.git_index_free(index); } - public static IndexEntrySafeHandle git_index_get_byindex(IndexSafeHandle index, UIntPtr n) + public static unsafe git_index_entry* git_index_get_byindex(IndexSafeHandle index, UIntPtr n) { return NativeMethods.git_index_get_byindex(index, n); } - public static IndexEntrySafeHandle git_index_get_bypath(IndexSafeHandle index, FilePath path, int stage) + public static unsafe git_index_entry* git_index_get_bypath(IndexSafeHandle index, FilePath path, int stage) { - IndexEntrySafeHandle handle = NativeMethods.git_index_get_bypath(index, path, stage); - - return handle.IsZero ? null : handle; + return NativeMethods.git_index_get_bypath(index, path, stage); } public static bool git_index_has_conflicts(IndexSafeHandle index) diff --git a/LibGit2Sharp/Index.cs b/LibGit2Sharp/Index.cs index f63c91d7c..810ea5909 100644 --- a/LibGit2Sharp/Index.cs +++ b/LibGit2Sharp/Index.cs @@ -70,22 +70,22 @@ public virtual bool IsFullyMerged /// /// Gets the with the specified relative path. /// - public virtual IndexEntry this[string path] + public virtual unsafe IndexEntry this[string path] { get { Ensure.ArgumentNotNullOrEmptyString(path, "path"); - IndexEntrySafeHandle entryHandle = Proxy.git_index_get_bypath(handle, path, 0); - return IndexEntry.BuildFromPtr(entryHandle); + git_index_entry* entry = Proxy.git_index_get_bypath(handle, path, 0); + return IndexEntry.BuildFromPtr(entry); } } - private IndexEntry this[int index] + private unsafe IndexEntry this[int index] { get { - IndexEntrySafeHandle entryHandle = Proxy.git_index_get_byindex(handle, (UIntPtr)index); + git_index_entry* entryHandle = Proxy.git_index_get_byindex(handle, (UIntPtr)index); return IndexEntry.BuildFromPtr(entryHandle); } } diff --git a/LibGit2Sharp/IndexEntry.cs b/LibGit2Sharp/IndexEntry.cs index 501d12717..a8c271e2f 100644 --- a/LibGit2Sharp/IndexEntry.cs +++ b/LibGit2Sharp/IndexEntry.cs @@ -40,24 +40,22 @@ public class IndexEntry : IEquatable /// public virtual ObjectId Id { get; private set; } - internal static IndexEntry BuildFromPtr(IndexEntrySafeHandle handle) + internal static unsafe IndexEntry BuildFromPtr(git_index_entry* entry) { - if (handle == null || handle.IsZero) + if (entry == null) { return null; } - GitIndexEntry entry = handle.MarshalAsGitIndexEntry(); - - FilePath path = LaxFilePathMarshaler.FromNative(entry.Path); + FilePath path = LaxFilePathMarshaler.FromNative(entry->path); return new IndexEntry { Path = path.Native, - Id = entry.Id, - StageLevel = Proxy.git_index_entry_stage(handle), - Mode = (Mode)entry.Mode, - AssumeUnchanged = (GitIndexEntry.GIT_IDXENTRY_VALID & entry.Flags) == GitIndexEntry.GIT_IDXENTRY_VALID + Id = new ObjectId(entry->id.Id), + StageLevel = Proxy.git_index_entry_stage(entry), + Mode = (Mode)entry->mode, + AssumeUnchanged = (GitIndexEntry.GIT_IDXENTRY_VALID & entry->flags) == GitIndexEntry.GIT_IDXENTRY_VALID }; } From 966ec5a06a32a0adbe533e186c3f6426b97a5608 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 15 Dec 2015 22:27:17 +0100 Subject: [PATCH 08/50] Get rid of the index entry SafeHandle --- LibGit2Sharp/Core/GitIndexEntry.cs | 21 ++----------------- .../Core/Handles/IndexEntrySafeHandle.cs | 10 --------- LibGit2Sharp/Core/NativeMethods.cs | 4 ++-- LibGit2Sharp/Core/Proxy.cs | 2 +- LibGit2Sharp/Index.cs | 16 +++++++------- LibGit2Sharp/IndexEntry.cs | 2 +- LibGit2Sharp/LibGit2Sharp.csproj | 1 - 7 files changed, 15 insertions(+), 41 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/IndexEntrySafeHandle.cs diff --git a/LibGit2Sharp/Core/GitIndexEntry.cs b/LibGit2Sharp/Core/GitIndexEntry.cs index a8ea73d31..ac0c141ed 100644 --- a/LibGit2Sharp/Core/GitIndexEntry.cs +++ b/LibGit2Sharp/Core/GitIndexEntry.cs @@ -13,6 +13,8 @@ internal unsafe struct git_index_mtime [StructLayout(LayoutKind.Sequential)] internal unsafe struct git_index_entry { + internal const ushort GIT_IDXENTRY_VALID = 0x8000; + public git_index_mtime ctime; public git_index_mtime mtime; public uint dev; @@ -26,23 +28,4 @@ internal unsafe struct git_index_entry public ushort extended_flags; public char* path; } - - [StructLayout(LayoutKind.Sequential)] - internal class GitIndexEntry - { - internal const ushort GIT_IDXENTRY_VALID = 0x8000; - - public GitIndexTime CTime; - public GitIndexTime MTime; - public uint Dev; - public uint Ino; - public uint Mode; - public uint Uid; - public uint Gid; - public uint file_size; - public GitOid Id; - public ushort Flags; - public ushort ExtendedFlags; - public IntPtr Path; - } } diff --git a/LibGit2Sharp/Core/Handles/IndexEntrySafeHandle.cs b/LibGit2Sharp/Core/Handles/IndexEntrySafeHandle.cs deleted file mode 100644 index f09e01c00..000000000 --- a/LibGit2Sharp/Core/Handles/IndexEntrySafeHandle.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class IndexEntrySafeHandle : NotOwnedSafeHandleBase - { - public GitIndexEntry MarshalAsGitIndexEntry() - { - return handle.MarshalAs(); - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index b7a6913b4..7f8e9ca8f 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -629,9 +629,9 @@ internal static extern int git_index_add_bypath( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] - internal static extern int git_index_add( + internal static extern unsafe int git_index_add( IndexSafeHandle index, - GitIndexEntry entry); + git_index_entry* entry); [DllImport(libgit2)] internal static extern unsafe int git_index_conflict_get( diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 2514d8ff3..9fb8e71b9 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -893,7 +893,7 @@ public static bool git_ignore_path_is_ignored(RepositorySafeHandle repo, string #region git_index_ - public static void git_index_add(IndexSafeHandle index, GitIndexEntry entry) + public static unsafe void git_index_add(IndexSafeHandle index, git_index_entry* entry) { int res = NativeMethods.git_index_add(index, entry); Ensure.ZeroResult(res); diff --git a/LibGit2Sharp/Index.cs b/LibGit2Sharp/Index.cs index 810ea5909..033400c67 100644 --- a/LibGit2Sharp/Index.cs +++ b/LibGit2Sharp/Index.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Globalization; +using System.Runtime.InteropServices; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; @@ -270,17 +271,18 @@ public virtual ConflictCollection Conflicts get { return conflicts; } } - private void AddEntryToTheIndex(string path, ObjectId id, Mode mode) + private unsafe void AddEntryToTheIndex(string path, ObjectId id, Mode mode) { - var indexEntry = new GitIndexEntry + IntPtr pathPtr = StrictFilePathMarshaler.FromManaged(path); + var indexEntry = new git_index_entry { - Mode = (uint)mode, - Id = id.Oid, - Path = StrictFilePathMarshaler.FromManaged(path), + mode = (uint)mode, + path = (char*) pathPtr, }; + Marshal.Copy(id.RawId, 0, new IntPtr(indexEntry.id.Id), GitOid.Size); - Proxy.git_index_add(handle, indexEntry); - EncodingMarshaler.Cleanup(indexEntry.Path); + Proxy.git_index_add(handle, &indexEntry); + EncodingMarshaler.Cleanup(pathPtr); } private string DebuggerDisplay diff --git a/LibGit2Sharp/IndexEntry.cs b/LibGit2Sharp/IndexEntry.cs index a8c271e2f..dc652dfcf 100644 --- a/LibGit2Sharp/IndexEntry.cs +++ b/LibGit2Sharp/IndexEntry.cs @@ -55,7 +55,7 @@ internal static unsafe IndexEntry BuildFromPtr(git_index_entry* entry) Id = new ObjectId(entry->id.Id), StageLevel = Proxy.git_index_entry_stage(entry), Mode = (Mode)entry->mode, - AssumeUnchanged = (GitIndexEntry.GIT_IDXENTRY_VALID & entry->flags) == GitIndexEntry.GIT_IDXENTRY_VALID + AssumeUnchanged = (git_index_entry.GIT_IDXENTRY_VALID & entry->flags) == git_index_entry.GIT_IDXENTRY_VALID }; } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 8d39ecb08..fc2030a43 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -284,7 +284,6 @@ - From 43521a638a13d1423ce17461d13cdaa70a70d1e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 16 Dec 2015 10:44:23 +0100 Subject: [PATCH 09/50] Disentangle the reference and config iterators While these both work roughly in the same manner (as they both represent iterators) the actual code duplication between these two is rather small as each `_next()` method is different and how we return the managed values is different. The net reduction in lines of code indicates that this is indeed the case. --- LibGit2Sharp/Configuration.cs | 4 +- .../Core/Handles/GitReferenceHandle.cs | 7 +- LibGit2Sharp/Core/NativeMethods.cs | 2 +- LibGit2Sharp/Core/Proxy.cs | 140 ++++++------------ 4 files changed, 57 insertions(+), 96 deletions(-) diff --git a/LibGit2Sharp/Configuration.cs b/LibGit2Sharp/Configuration.cs index afdf69a31..95467f7e9 100644 --- a/LibGit2Sharp/Configuration.cs +++ b/LibGit2Sharp/Configuration.cs @@ -679,7 +679,7 @@ public virtual IEnumerable> Find(string regexp, Confi using (ConfigurationSafeHandle snapshot = Snapshot()) using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, snapshot)) { - return Proxy.git_config_iterator_glob(h, regexp, BuildConfigEntry).ToList(); + return Proxy.git_config_iterator_glob(h, regexp).ToList(); } } @@ -732,7 +732,7 @@ private IEnumerable> BuildConfigEntries() return Proxy.git_config_foreach(configHandle, BuildConfigEntry); } - private static unsafe ConfigurationEntry BuildConfigEntry(IntPtr entryPtr) + internal static unsafe ConfigurationEntry BuildConfigEntry(IntPtr entryPtr) { var entry = (GitConfigEntry*)entryPtr.ToPointer(); return new ConfigurationEntry(LaxUtf8Marshaler.FromNative(entry->namePtr), diff --git a/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs b/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs index 976121c52..13ca58aad 100644 --- a/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs +++ b/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs @@ -11,6 +11,11 @@ internal GitReferenceHandle(git_reference* refPtr) this.ptr = refPtr; } + internal GitReferenceHandle(IntPtr refPtr) + { + this.ptr = (git_reference*) refPtr.ToPointer(); + } + ~GitReferenceHandle() { Dispose(); @@ -31,7 +36,7 @@ internal bool IsNull public void Dispose() { - NativeMethods.git_reference_free(new IntPtr(ptr)); + NativeMethods.git_reference_free(ptr); ptr = null; } } diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 7f8e9ca8f..1f3b86454 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1013,7 +1013,7 @@ internal static extern int git_reference_foreach_glob( IntPtr payload); [DllImport(libgit2)] - internal static extern void git_reference_free(IntPtr reference); + internal static extern unsafe void git_reference_free(git_reference* reference); [DllImport(libgit2)] internal static extern int git_reference_is_valid_name( diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 9fb8e71b9..14842f766 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -209,22 +209,33 @@ public static unsafe void git_branch_delete(GitReferenceHandle reference) Ensure.ZeroResult(res); } - public static unsafe IEnumerable git_branch_iterator(Repository repo, GitBranchType branchType) - { - return git_iterator((out BranchIteratorSafeHandle iter_out) => - NativeMethods.git_branch_iterator_new(out iter_out, repo.Handle, branchType), - (BranchIteratorSafeHandle iter, out IntPtr refPtr, out int res) => - { - GitBranchType type_out; - res = NativeMethods.git_branch_next(out refPtr, out type_out, iter); - return new { BranchType = type_out }; - }, - (handle, payload) => - { - git_reference* refPtr = (git_reference*)handle.ToPointer(); - var reference = Reference.BuildFromPtr(refPtr, repo); - return new Branch(repo, reference, reference.CanonicalName); - }); + public static IEnumerable git_branch_iterator(Repository repo, GitBranchType branchType) + { + BranchIteratorSafeHandle iter; + var res = NativeMethods.git_branch_iterator_new(out iter, repo.Handle, branchType); + Ensure.ZeroResult(res); + + using (iter) + { + while (true) + { + IntPtr refPtr = IntPtr.Zero; + GitBranchType _branchType; + res = NativeMethods.git_branch_next(out refPtr, out _branchType, iter); + if (res == (int)GitErrorCode.IterOver) + { + yield break; + } + Ensure.ZeroResult(res); + + Reference reference; + using (var refHandle = new GitReferenceHandle(refPtr)) + { + reference = Reference.BuildFromPtr(refHandle, repo); + } + yield return new Branch(repo, reference, reference.CanonicalName); + } + } } public static void git_branch_iterator_free(IntPtr iter) @@ -583,22 +594,28 @@ public static ICollection git_config_foreach( return git_foreach(resultSelector, c => NativeMethods.git_config_foreach(config, (e, p) => c(e, p), IntPtr.Zero)); } - public static unsafe IEnumerable> git_config_iterator_glob( + public static IEnumerable> git_config_iterator_glob( ConfigurationSafeHandle config, - string regexp, - Func> resultSelector) - { - return git_iterator((out ConfigurationIteratorSafeHandle iter) => - NativeMethods.git_config_iterator_glob_new(out iter, config, regexp), - (ConfigurationIteratorSafeHandle iter, out IntPtr handle, out int res) => - { - handle = IntPtr.Zero; - IntPtr entry; - res = NativeMethods.git_config_next(out entry, iter); - return new { EntryPtr = entry }; - }, - (handle, payload) => - resultSelector(payload.EntryPtr)); + string regexp) + { + ConfigurationIteratorSafeHandle iter; + var res = NativeMethods.git_config_iterator_glob_new(out iter, config, regexp); + Ensure.ZeroResult(res); + using (iter) + { + while (true) + { + IntPtr entry; + res = NativeMethods.git_config_next(out entry, iter); + if (res == (int)GitErrorCode.IterOver) + { + yield break; + } + Ensure.ZeroResult(res); + + yield return Configuration.BuildConfigEntry(entry); + } + } } public static void git_config_iterator_free(IntPtr iter) @@ -1809,11 +1826,6 @@ public static ICollection git_reference_foreach_glob( return git_foreach(resultSelector, c => NativeMethods.git_reference_foreach_glob(repo, glob, (x, p) => c(x, p), IntPtr.Zero)); } - public static void git_reference_free(IntPtr reference) - { - NativeMethods.git_reference_free(reference); - } - public static bool git_reference_is_valid_name(string refname) { int res = NativeMethods.git_reference_is_valid_name(refname); @@ -3380,62 +3392,6 @@ private static ICollection git_foreach( return result; } - private delegate int IteratorNew(out THandle iter); - - private delegate TPayload IteratorNext(TIterator iter, out THandle next, out int res); - - private static THandle git_iterator_new(IteratorNew newFunc) - where THandle : SafeHandleBase - { - THandle iter; - Ensure.ZeroResult(newFunc(out iter)); - return iter; - } - - private static IEnumerable git_iterator_next( - TIterator iter, - IteratorNext nextFunc, - Func resultSelector) - { - while (true) - { - var next = IntPtr.Zero; - try - { - int res; - var payload = nextFunc(iter, out next, out res); - - if (res == (int)GitErrorCode.IterOver) - { - yield break; - } - - Ensure.ZeroResult(res); - yield return resultSelector(next, payload); - } - finally - { - NativeMethods.git_reference_free(next); - } - } - } - - private static IEnumerable git_iterator( - IteratorNew newFunc, - IteratorNext nextFunc, - Func resultSelector - ) - where TIterator : SafeHandleBase - { - using (var iter = git_iterator_new(newFunc)) - { - foreach (var next in git_iterator_next(iter, nextFunc, resultSelector)) - { - yield return next; - } - } - } - private static bool RepositoryStateChecker(RepositorySafeHandle repo, Func checker) { int res = checker(repo); From 690af7063ce3db294d226e7171d608127f7674bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 12 Jan 2016 05:52:05 +0100 Subject: [PATCH 10/50] Get rid of the branch iterator SafeHandle --- LibGit2Sharp/Core/Handles/BranchIteratorSafeHandle.cs | 11 ----------- LibGit2Sharp/Core/NativeMethods.cs | 6 +++--- LibGit2Sharp/Core/Proxy.cs | 8 ++++++-- LibGit2Sharp/LibGit2Sharp.csproj | 1 - 4 files changed, 9 insertions(+), 17 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/BranchIteratorSafeHandle.cs diff --git a/LibGit2Sharp/Core/Handles/BranchIteratorSafeHandle.cs b/LibGit2Sharp/Core/Handles/BranchIteratorSafeHandle.cs deleted file mode 100644 index 6764bee66..000000000 --- a/LibGit2Sharp/Core/Handles/BranchIteratorSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class BranchIteratorSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_branch_iterator_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 1f3b86454..03b4fe751 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -166,8 +166,8 @@ internal static extern void git_branch_iterator_free( IntPtr iterator); [DllImport(libgit2)] - internal static extern int git_branch_iterator_new( - out BranchIteratorSafeHandle iter_out, + internal static extern int git_branch_iterator_new( + out IntPtr iter_out, RepositorySafeHandle repo, GitBranchType branch_type); @@ -182,7 +182,7 @@ internal static extern unsafe int git_branch_move( internal static extern int git_branch_next( out IntPtr ref_out, out GitBranchType type_out, - BranchIteratorSafeHandle iter); + IntPtr iter); [DllImport(libgit2)] internal static extern int git_branch_remote_name( diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 14842f766..eb012e509 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -211,11 +211,11 @@ public static unsafe void git_branch_delete(GitReferenceHandle reference) public static IEnumerable git_branch_iterator(Repository repo, GitBranchType branchType) { - BranchIteratorSafeHandle iter; + IntPtr iter; var res = NativeMethods.git_branch_iterator_new(out iter, repo.Handle, branchType); Ensure.ZeroResult(res); - using (iter) + try { while (true) { @@ -236,6 +236,10 @@ public static IEnumerable git_branch_iterator(Repository repo, GitBranch yield return new Branch(repo, reference, reference.CanonicalName); } } + finally + { + NativeMethods.git_branch_iterator_free(iter); + } } public static void git_branch_iterator_free(IntPtr iter) diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index fc2030a43..e0eb93edd 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -147,7 +147,6 @@ - From c05ee2781d8a681aa7fd9604045efd58b269dbd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 05:18:50 +0100 Subject: [PATCH 11/50] Create handles via templating We cannot create libgit2 wrapper objects which are generic over the pointer types, so let's use a template instead. We map the C name to the C# name and generate the same code for each of them. --- LibGit2Sharp/Core/Handles/Objects.cs | 42 +++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 63 +++++++++++++++++++ .../Core/Handles/TreeEntryOwnedHandle.cs | 19 ------ LibGit2Sharp/Core/Proxy.cs | 19 +++--- LibGit2Sharp/LibGit2Sharp.csproj | 8 ++- LibGit2Sharp/Tree.cs | 4 +- LibGit2Sharp/TreeEntry.cs | 3 +- 7 files changed, 126 insertions(+), 32 deletions(-) create mode 100644 LibGit2Sharp/Core/Handles/Objects.cs create mode 100644 LibGit2Sharp/Core/Handles/Objects.tt delete mode 100644 LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs new file mode 100644 index 000000000..45bd99846 --- /dev/null +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -0,0 +1,42 @@ + +using System; + +namespace LibGit2Sharp.Core +{ + + internal unsafe class TreeEntryHandle : IDisposable + { + internal git_tree_entry* Handle { get; private set; } + bool owned; + bool disposed; + + public unsafe TreeEntryHandle(git_tree_entry* handle, bool owned) + { + this.Handle = handle; + this.owned = owned; + } + + ~TreeEntryHandle() + { + Dispose(false); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_tree_entry_free(Handle); + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + } +} diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt new file mode 100644 index 000000000..2ca3ba917 --- /dev/null +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -0,0 +1,63 @@ +<#@ template language="C#" #> +<#@ output extention=".cs" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections.Generic" #> + +using System; + +namespace LibGit2Sharp.Core +{ + +<# +var cNames = new[] { + "git_tree_entry", +}; + +var csNames = new[] { + "TreeEntryHandle" +}; + +for (var i = 0; i < cNames.Length; i++) +{ +#> + internal unsafe class <#= csNames[i] #> : IDisposable + { + internal <#= cNames[i] #>* Handle { get; private set; } + bool owned; + bool disposed; + + public unsafe <#= csNames[i] #>(<#= cNames[i] #>* handle, bool owned) + { + this.Handle = handle; + this.owned = owned; + } + + ~<#= csNames[i] #>() + { + Dispose(false); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.<#= cNames[i] #>_free(Handle); + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + } +<# +} +#> +} diff --git a/LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs b/LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs deleted file mode 100644 index ddd253c52..000000000 --- a/LibGit2Sharp/Core/Handles/TreeEntryOwnedHandle.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -namespace LibGit2Sharp.Core.Handles -{ - internal unsafe class TreeEntryOwnedHandle : IDisposable - { - internal git_tree_entry* Handle { get; set; } - - internal TreeEntryOwnedHandle(git_tree_entry* entry) - { - Handle = entry; - } - - public void Dispose() - { - Proxy.git_tree_entry_free(Handle); - } - } -} diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index eb012e509..96c83ff63 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -3159,12 +3159,18 @@ public static unsafe Mode git_tree_entry_attributes(git_tree_entry* entry) return (Mode)NativeMethods.git_tree_entry_filemode(entry); } - public static unsafe git_tree_entry* git_tree_entry_byindex(GitObjectSafeHandle tree, long idx) + public static unsafe TreeEntryHandle git_tree_entry_byindex(GitObjectSafeHandle tree, long idx) { - return NativeMethods.git_tree_entry_byindex(tree, (UIntPtr)idx); + var handle = NativeMethods.git_tree_entry_byindex(tree, (UIntPtr)idx); + if (handle == null) + { + return null; + } + + return new TreeEntryHandle(handle, false); } - public static unsafe TreeEntryOwnedHandle git_tree_entry_bypath(RepositorySafeHandle repo, ObjectId id, FilePath treeentry_path) + public static unsafe TreeEntryHandle git_tree_entry_bypath(RepositorySafeHandle repo, ObjectId id, FilePath treeentry_path) { using (var obj = new ObjectSafeWrapper(id, repo)) { @@ -3178,15 +3184,10 @@ public static unsafe TreeEntryOwnedHandle git_tree_entry_bypath(RepositorySafeHa Ensure.ZeroResult(res); - return new TreeEntryOwnedHandle(treeEntryPtr); + return new TreeEntryHandle(treeEntryPtr, true); } } - public static unsafe void git_tree_entry_free(git_tree_entry* treeEntry) - { - NativeMethods.git_tree_entry_free(treeEntry); - } - public static unsafe ObjectId git_tree_entry_id(git_tree_entry* entry) { return NativeMethods.git_tree_entry_id(entry).MarshalAsObjectId(); diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index e0eb93edd..22da481d0 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -379,7 +379,9 @@ - + + Objects.tt + @@ -389,6 +391,10 @@ + + TextTemplatingFileGenerator + Objects.cs + diff --git a/LibGit2Sharp/Tree.cs b/LibGit2Sharp/Tree.cs index a8b761ac7..af7946186 100644 --- a/LibGit2Sharp/Tree.cs +++ b/LibGit2Sharp/Tree.cs @@ -54,7 +54,7 @@ private unsafe TreeEntry RetrieveFromPath(FilePath relativePath) return null; } - using (TreeEntryOwnedHandle treeEntry = Proxy.git_tree_entry_bypath(repo.Handle, Id, relativePath)) + using (TreeEntryHandle treeEntry = Proxy.git_tree_entry_bypath(repo.Handle, Id, relativePath)) { if (treeEntry == null) { @@ -64,7 +64,7 @@ private unsafe TreeEntry RetrieveFromPath(FilePath relativePath) string posixPath = relativePath.Posix; string filename = posixPath.Split('/').Last(); string parentPath = posixPath.Substring(0, posixPath.Length - filename.Length); - return new TreeEntry(treeEntry.Handle, Id, repo, path.Combine(parentPath)); + return new TreeEntry(treeEntry, Id, repo, path.Combine(parentPath)); } } diff --git a/LibGit2Sharp/TreeEntry.cs b/LibGit2Sharp/TreeEntry.cs index 7f2879e49..3c80f606d 100644 --- a/LibGit2Sharp/TreeEntry.cs +++ b/LibGit2Sharp/TreeEntry.cs @@ -27,8 +27,9 @@ public class TreeEntry : IEquatable protected TreeEntry() { } - internal unsafe TreeEntry(git_tree_entry* entry, ObjectId parentTreeId, Repository repo, FilePath parentPath) + internal unsafe TreeEntry(TreeEntryHandle handle, ObjectId parentTreeId, Repository repo, FilePath parentPath) { + var entry = handle.Handle; this.parentTreeId = parentTreeId; this.repo = repo; targetOid = Proxy.git_tree_entry_id(entry); From 5762938b509c9efaa1c01b6b354bae8031a14b4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 10:57:00 +0100 Subject: [PATCH 12/50] Move git_reference to the template --- LibGit2Sharp/BranchCollection.cs | 4 +- .../Core/Handles/GitReferenceHandle.cs | 43 --------- LibGit2Sharp/Core/Handles/Objects.cs | 89 ++++++++++++++++++- LibGit2Sharp/Core/Handles/Objects.tt | 34 ++++++- LibGit2Sharp/Core/Proxy.cs | 56 ++++++------ LibGit2Sharp/LibGit2Sharp.csproj | 3 - LibGit2Sharp/Rebase.cs | 12 +-- LibGit2Sharp/Reference.cs | 4 +- LibGit2Sharp/ReferenceCollection.cs | 24 ++--- LibGit2Sharp/Repository.cs | 2 +- 10 files changed, 167 insertions(+), 104 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/GitReferenceHandle.cs diff --git a/LibGit2Sharp/BranchCollection.cs b/LibGit2Sharp/BranchCollection.cs index f0a7c937b..d81a48177 100644 --- a/LibGit2Sharp/BranchCollection.cs +++ b/LibGit2Sharp/BranchCollection.cs @@ -199,7 +199,7 @@ public virtual void Remove(Branch branch) { Ensure.ArgumentNotNull(branch, "branch"); - using (GitReferenceHandle referencePtr = repo.Refs.RetrieveReferencePtr(branch.CanonicalName)) + using (ReferenceHandle referencePtr = repo.Refs.RetrieveReferencePtr(branch.CanonicalName)) { Proxy.git_branch_delete(referencePtr); } @@ -267,7 +267,7 @@ public virtual Branch Rename(Branch branch, string newName, bool allowOverwrite) branch.FriendlyName); } - using (GitReferenceHandle referencePtr = repo.Refs.RetrieveReferencePtr(Reference.LocalBranchPrefix + branch.FriendlyName)) + using (ReferenceHandle referencePtr = repo.Refs.RetrieveReferencePtr(Reference.LocalBranchPrefix + branch.FriendlyName)) { using (Proxy.git_branch_move(referencePtr, newName, allowOverwrite)) { } diff --git a/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs b/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs deleted file mode 100644 index 13ca58aad..000000000 --- a/LibGit2Sharp/Core/Handles/GitReferenceHandle.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; - -namespace LibGit2Sharp.Core.Handles -{ - internal unsafe class GitReferenceHandle : IDisposable - { - git_reference* ptr; - - internal GitReferenceHandle(git_reference* refPtr) - { - this.ptr = refPtr; - } - - internal GitReferenceHandle(IntPtr refPtr) - { - this.ptr = (git_reference*) refPtr.ToPointer(); - } - - ~GitReferenceHandle() - { - Dispose(); - } - - internal git_reference* ToPointer() - { - return ptr; - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - public void Dispose() - { - NativeMethods.git_reference_free(ptr); - ptr = null; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index 45bd99846..08a4866fc 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -6,13 +6,27 @@ namespace LibGit2Sharp.Core internal unsafe class TreeEntryHandle : IDisposable { - internal git_tree_entry* Handle { get; private set; } + git_tree_entry* ptr; + internal git_tree_entry* Handle + { + get + { + return ptr; + } + } + bool owned; bool disposed; public unsafe TreeEntryHandle(git_tree_entry* handle, bool owned) { - this.Handle = handle; + this.ptr = handle; + this.owned = owned; + } + + public unsafe TreeEntryHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_tree_entry*) ptr.ToPointer(); this.owned = owned; } @@ -21,13 +35,22 @@ public unsafe TreeEntryHandle(git_tree_entry* handle, bool owned) Dispose(false); } + internal bool IsNull + { + get + { + return ptr == null; + } + } + + void Dispose(bool disposing) { if (!disposed) { if (owned) { - NativeMethods.git_tree_entry_free(Handle); + NativeMethods.git_tree_entry_free(ptr); } } @@ -39,4 +62,64 @@ public void Dispose() Dispose(true); } } + + internal unsafe class ReferenceHandle : IDisposable + { + git_reference* ptr; + internal git_reference* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe ReferenceHandle(git_reference* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe ReferenceHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_reference*) ptr.ToPointer(); + this.owned = owned; + } + + ~ReferenceHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_reference_free(ptr); + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 2ca3ba917..3518e2837 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -13,10 +13,12 @@ namespace LibGit2Sharp.Core <# var cNames = new[] { "git_tree_entry", + "git_reference", }; var csNames = new[] { - "TreeEntryHandle" + "TreeEntryHandle", + "ReferenceHandle", }; for (var i = 0; i < cNames.Length; i++) @@ -24,13 +26,27 @@ for (var i = 0; i < cNames.Length; i++) #> internal unsafe class <#= csNames[i] #> : IDisposable { - internal <#= cNames[i] #>* Handle { get; private set; } + <#= cNames[i] #>* ptr; + internal <#= cNames[i] #>* Handle + { + get + { + return ptr; + } + } + bool owned; bool disposed; public unsafe <#= csNames[i] #>(<#= cNames[i] #>* handle, bool owned) { - this.Handle = handle; + this.ptr = handle; + this.owned = owned; + } + + public unsafe <#= csNames[i] #>(IntPtr ptr, bool owned) + { + this.ptr = (<#= cNames[i] #>*) ptr.ToPointer(); this.owned = owned; } @@ -39,13 +55,22 @@ for (var i = 0; i < cNames.Length; i++) Dispose(false); } + internal bool IsNull + { + get + { + return ptr == null; + } + } + + void Dispose(bool disposing) { if (!disposed) { if (owned) { - NativeMethods.<#= cNames[i] #>_free(Handle); + NativeMethods.<#= cNames[i] #>_free(ptr); } } @@ -57,6 +82,7 @@ for (var i = 0; i < cNames.Length; i++) Dispose(true); } } + <# } #> diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 96c83ff63..f593eb73e 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -190,7 +190,7 @@ public static bool git_blob_is_binary(GitObjectSafeHandle obj) #region git_branch_ - public static unsafe GitReferenceHandle git_branch_create_from_annotated(RepositorySafeHandle repo, string branch_name, string targetIdentifier, bool force) + public static unsafe ReferenceHandle git_branch_create_from_annotated(RepositorySafeHandle repo, string branch_name, string targetIdentifier, bool force) { git_reference* reference; @@ -200,12 +200,12 @@ public static unsafe GitReferenceHandle git_branch_create_from_annotated(Reposit Ensure.ZeroResult(res); } - return new GitReferenceHandle(reference); + return new ReferenceHandle(reference, true); } - public static unsafe void git_branch_delete(GitReferenceHandle reference) + public static unsafe void git_branch_delete(ReferenceHandle reference) { - int res = NativeMethods.git_branch_delete(reference.ToPointer()); + int res = NativeMethods.git_branch_delete(reference.Handle); Ensure.ZeroResult(res); } @@ -229,7 +229,7 @@ public static IEnumerable git_branch_iterator(Repository repo, GitBranch Ensure.ZeroResult(res); Reference reference; - using (var refHandle = new GitReferenceHandle(refPtr)) + using (var refHandle = new ReferenceHandle(refPtr, true)) { reference = Reference.BuildFromPtr(refHandle, repo); } @@ -247,12 +247,12 @@ public static void git_branch_iterator_free(IntPtr iter) NativeMethods.git_branch_iterator_free(iter); } - public static unsafe GitReferenceHandle git_branch_move(GitReferenceHandle reference, string new_branch_name, bool force) + public static unsafe ReferenceHandle git_branch_move(ReferenceHandle reference, string new_branch_name, bool force) { git_reference* ref_out; - int res = NativeMethods.git_branch_move(out ref_out, reference.ToPointer(), new_branch_name, force); + int res = NativeMethods.git_branch_move(out ref_out, reference.Handle, new_branch_name, force); Ensure.ZeroResult(res); - return new GitReferenceHandle(ref_out); + return new ReferenceHandle(ref_out, true); } public static string git_branch_remote_name(RepositorySafeHandle repo, string canonical_branch_name, bool shouldThrowIfNotFound) @@ -1165,11 +1165,11 @@ public static GitAnnotatedCommitHandle git_annotated_commit_lookup(RepositorySaf return their_head; } - public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositorySafeHandle repo, GitReferenceHandle reference) + public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositorySafeHandle repo, ReferenceHandle reference) { GitAnnotatedCommitHandle their_head; - int res = NativeMethods.git_annotated_commit_from_ref(out their_head, repo, reference.ToPointer()); + int res = NativeMethods.git_annotated_commit_from_ref(out their_head, repo, reference.Handle); Ensure.ZeroResult(res); @@ -1791,7 +1791,7 @@ public static void git_rebase_free(IntPtr rebase) #region git_reference_ - public static unsafe GitReferenceHandle git_reference_create( + public static unsafe ReferenceHandle git_reference_create( RepositorySafeHandle repo, string name, ObjectId targetId, @@ -1804,10 +1804,10 @@ public static unsafe GitReferenceHandle git_reference_create( int res = NativeMethods.git_reference_create(out handle, repo, name, ref oid, allowOverwrite, logMessage); Ensure.ZeroResult(res); - return new GitReferenceHandle(handle); + return new ReferenceHandle(handle, true); } - public static unsafe GitReferenceHandle git_reference_symbolic_create( + public static unsafe ReferenceHandle git_reference_symbolic_create( RepositorySafeHandle repo, string name, string target, @@ -1819,7 +1819,7 @@ public static unsafe GitReferenceHandle git_reference_symbolic_create( logMessage); Ensure.ZeroResult(res); - return new GitReferenceHandle(handle); + return new ReferenceHandle(handle, true); } public static ICollection git_reference_foreach_glob( @@ -1855,7 +1855,7 @@ public static IList git_reference_list(RepositorySafeHandle repo) } } - public static unsafe GitReferenceHandle git_reference_lookup(RepositorySafeHandle repo, string name, bool shouldThrowIfNotFound) + public static unsafe ReferenceHandle git_reference_lookup(RepositorySafeHandle repo, string name, bool shouldThrowIfNotFound) { git_reference* handle; int res = NativeMethods.git_reference_lookup(out handle, repo, name); @@ -1867,7 +1867,7 @@ public static unsafe GitReferenceHandle git_reference_lookup(RepositorySafeHandl Ensure.ZeroResult(res); - return new GitReferenceHandle(handle); + return new ReferenceHandle(handle, true); } public static unsafe string git_reference_name(git_reference* reference) @@ -1886,39 +1886,39 @@ public static unsafe ObjectId git_reference_target(git_reference* reference) return NativeMethods.git_reference_target(reference).MarshalAsObjectId(); } - public static unsafe GitReferenceHandle git_reference_rename( - GitReferenceHandle reference, + public static unsafe ReferenceHandle git_reference_rename( + ReferenceHandle reference, string newName, bool allowOverwrite, string logMessage) { git_reference* ref_out; - int res = NativeMethods.git_reference_rename(out ref_out, reference.ToPointer(), newName, allowOverwrite, logMessage); + int res = NativeMethods.git_reference_rename(out ref_out, reference.Handle, newName, allowOverwrite, logMessage); Ensure.ZeroResult(res); - return new GitReferenceHandle(ref_out); + return new ReferenceHandle(ref_out, true); } - public static unsafe GitReferenceHandle git_reference_set_target(GitReferenceHandle reference, ObjectId id, string logMessage) + public static unsafe ReferenceHandle git_reference_set_target(ReferenceHandle reference, ObjectId id, string logMessage) { GitOid oid = id.Oid; git_reference* ref_out; - int res = NativeMethods.git_reference_set_target(out ref_out, reference.ToPointer(), ref oid, logMessage); + int res = NativeMethods.git_reference_set_target(out ref_out, reference.Handle, ref oid, logMessage); Ensure.ZeroResult(res); - return new GitReferenceHandle(ref_out); + return new ReferenceHandle(ref_out, true); } - public static unsafe GitReferenceHandle git_reference_symbolic_set_target(GitReferenceHandle reference, string target, string logMessage) + public static unsafe ReferenceHandle git_reference_symbolic_set_target(ReferenceHandle reference, string target, string logMessage) { git_reference* ref_out; - int res = NativeMethods.git_reference_symbolic_set_target(out ref_out, reference.ToPointer(), target, logMessage); + int res = NativeMethods.git_reference_symbolic_set_target(out ref_out, reference.Handle, target, logMessage); Ensure.ZeroResult(res); - return new GitReferenceHandle(ref_out); + return new ReferenceHandle(ref_out, true); } public static unsafe string git_reference_symbolic_target(git_reference* reference) @@ -2598,7 +2598,7 @@ public static void git_revert( #region git_revparse_ - public static unsafe Tuple git_revparse_ext(RepositorySafeHandle repo, string objectish) + public static unsafe Tuple git_revparse_ext(RepositorySafeHandle repo, string objectish) { GitObjectSafeHandle obj; git_reference* reference; @@ -2618,7 +2618,7 @@ public static unsafe Tuple git_revparse break; } - return new Tuple(obj, new GitReferenceHandle(reference)); + return new Tuple(obj, new ReferenceHandle(reference, true)); } public static GitObjectSafeHandle git_revparse_single(RepositorySafeHandle repo, string objectish) diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 22da481d0..7d6a4c1ca 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -23,7 +23,6 @@ TRACE;DEBUG;NET40 prompt 4 - false true AllRules.ruleset bin\Debug\LibGit2Sharp.xml @@ -36,7 +35,6 @@ prompt 4 true - false bin\Release\LibGit2Sharp.xml @@ -73,7 +71,6 @@ - diff --git a/LibGit2Sharp/Rebase.cs b/LibGit2Sharp/Rebase.cs index 5e2019627..a7ea050d1 100644 --- a/LibGit2Sharp/Rebase.cs +++ b/LibGit2Sharp/Rebase.cs @@ -85,15 +85,15 @@ public virtual RebaseResult Start(Branch branch, Branch upstream, Branch onto, I this.repository.Info.CurrentOperation); } - Func RefHandleFromBranch = (Branch b) => + Func RefHandleFromBranch = (Branch b) => { return (b == null) ? null : this.repository.Refs.RetrieveReferencePtr(b.CanonicalName); }; - Func AnnotatedCommitHandleFromRefHandle = - (GitReferenceHandle refHandle) => + Func AnnotatedCommitHandleFromRefHandle = + (ReferenceHandle refHandle) => { return (refHandle == null) ? new GitAnnotatedCommitHandle() : @@ -108,9 +108,9 @@ public virtual RebaseResult Start(Branch branch, Branch upstream, Branch onto, I checkout_options = checkoutOptionsWrapper.Options, }; - using (GitReferenceHandle branchRefPtr = RefHandleFromBranch(branch)) - using (GitReferenceHandle upstreamRefPtr = RefHandleFromBranch(upstream)) - using (GitReferenceHandle ontoRefPtr = RefHandleFromBranch(onto)) + using (ReferenceHandle branchRefPtr = RefHandleFromBranch(branch)) + using (ReferenceHandle upstreamRefPtr = RefHandleFromBranch(upstream)) + using (ReferenceHandle ontoRefPtr = RefHandleFromBranch(onto)) using (GitAnnotatedCommitHandle annotatedBranchCommitHandle = AnnotatedCommitHandleFromRefHandle(branchRefPtr)) using (GitAnnotatedCommitHandle upstreamRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(upstreamRefPtr)) using (GitAnnotatedCommitHandle ontoRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(ontoRefPtr)) diff --git a/LibGit2Sharp/Reference.cs b/LibGit2Sharp/Reference.cs index 20da027a9..340ba5df3 100644 --- a/LibGit2Sharp/Reference.cs +++ b/LibGit2Sharp/Reference.cs @@ -37,9 +37,9 @@ internal Reference(IRepository repo, string canonicalName, string targetIdentifi } // This overload lets public-facing methods avoid having to use the pointers directly - internal static unsafe T BuildFromPtr(GitReferenceHandle handle, Repository repo) where T : Reference + internal static unsafe T BuildFromPtr(ReferenceHandle handle, Repository repo) where T : Reference { - return BuildFromPtr(handle.ToPointer(), repo); + return BuildFromPtr(handle.Handle, repo); } internal static unsafe T BuildFromPtr(git_reference* handle, Repository repo) where T : Reference diff --git a/LibGit2Sharp/ReferenceCollection.cs b/LibGit2Sharp/ReferenceCollection.cs index b8692f1f7..df098d261 100644 --- a/LibGit2Sharp/ReferenceCollection.cs +++ b/LibGit2Sharp/ReferenceCollection.cs @@ -124,7 +124,7 @@ public virtual Reference Add(string name, string canonicalRefNameOrObjectish, st if (refState == RefState.DoesNotExistButLooksValid && gitObject == null) { - using (GitReferenceHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, name, canonicalRefNameOrObjectish, allowOverwrite, + using (ReferenceHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, name, canonicalRefNameOrObjectish, allowOverwrite, logMessage)) { return Reference.BuildFromPtr(handle, repo); @@ -191,7 +191,7 @@ public virtual DirectReference Add(string name, ObjectId targetId, string logMes Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(targetId, "targetId"); - using (GitReferenceHandle handle = Proxy.git_reference_create(repo.Handle, name, targetId, allowOverwrite, logMessage)) + using (ReferenceHandle handle = Proxy.git_reference_create(repo.Handle, name, targetId, allowOverwrite, logMessage)) { return (DirectReference)Reference.BuildFromPtr(handle, repo); } @@ -245,7 +245,7 @@ public virtual SymbolicReference Add(string name, Reference targetRef, string lo Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(targetRef, "targetRef"); - using (GitReferenceHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, + using (ReferenceHandle handle = Proxy.git_reference_symbolic_create(repo.Handle, name, targetRef.CanonicalName, allowOverwrite, @@ -343,8 +343,8 @@ public virtual Reference Rename(Reference reference, string newName, string logM newName); } - using (GitReferenceHandle referencePtr = RetrieveReferencePtr(reference.CanonicalName)) - using (GitReferenceHandle handle = Proxy.git_reference_rename(referencePtr, newName, allowOverwrite, logMessage)) + using (ReferenceHandle referencePtr = RetrieveReferencePtr(reference.CanonicalName)) + using (ReferenceHandle handle = Proxy.git_reference_rename(referencePtr, newName, allowOverwrite, logMessage)) { return Reference.BuildFromPtr(handle, repo); } @@ -438,7 +438,7 @@ internal T Resolve(string name) where T : Reference { Ensure.ArgumentNotNullOrEmptyString(name, "name"); - using (GitReferenceHandle referencePtr = RetrieveReferencePtr(name, false)) + using (ReferenceHandle referencePtr = RetrieveReferencePtr(name, false)) { return referencePtr == null ? null @@ -468,8 +468,8 @@ public virtual Reference UpdateTarget(Reference directRef, ObjectId targetId, st private Reference UpdateDirectReferenceTarget(Reference directRef, ObjectId targetId, string logMessage) { - using (GitReferenceHandle referencePtr = RetrieveReferencePtr(directRef.CanonicalName)) - using (GitReferenceHandle handle = Proxy.git_reference_set_target(referencePtr, targetId, logMessage)) + using (ReferenceHandle referencePtr = RetrieveReferencePtr(directRef.CanonicalName)) + using (ReferenceHandle handle = Proxy.git_reference_set_target(referencePtr, targetId, logMessage)) { return Reference.BuildFromPtr(handle, repo); } @@ -594,8 +594,8 @@ public virtual Reference UpdateTarget(Reference symbolicRef, Reference targetRef private Reference UpdateSymbolicRefenceTarget(Reference symbolicRef, Reference targetRef, string logMessage) { - using (GitReferenceHandle referencePtr = RetrieveReferencePtr(symbolicRef.CanonicalName)) - using (GitReferenceHandle handle = Proxy.git_reference_symbolic_set_target(referencePtr, targetRef.CanonicalName, logMessage)) + using (ReferenceHandle referencePtr = RetrieveReferencePtr(symbolicRef.CanonicalName)) + using (ReferenceHandle handle = Proxy.git_reference_symbolic_set_target(referencePtr, targetRef.CanonicalName, logMessage)) { return Reference.BuildFromPtr(handle, repo); } @@ -671,9 +671,9 @@ internal Reference UpdateHeadTarget(string target, string logMessage) return repo.Refs.Head; } - internal GitReferenceHandle RetrieveReferencePtr(string referenceName, bool shouldThrowIfNotFound = true) + internal ReferenceHandle RetrieveReferencePtr(string referenceName, bool shouldThrowIfNotFound = true) { - GitReferenceHandle reference = Proxy.git_reference_lookup(repo.Handle, referenceName, shouldThrowIfNotFound); + ReferenceHandle reference = Proxy.git_reference_lookup(repo.Handle, referenceName, shouldThrowIfNotFound); return reference; } diff --git a/LibGit2Sharp/Repository.cs b/LibGit2Sharp/Repository.cs index 948daf7a5..6649e64be 100644 --- a/LibGit2Sharp/Repository.cs +++ b/LibGit2Sharp/Repository.cs @@ -1225,7 +1225,7 @@ public MergeResult Merge(Branch branch, Signature merger, MergeOptions options) options = options ?? new MergeOptions(); - using (GitReferenceHandle referencePtr = Refs.RetrieveReferencePtr(branch.CanonicalName)) + using (ReferenceHandle referencePtr = Refs.RetrieveReferencePtr(branch.CanonicalName)) using (GitAnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_from_ref(Handle, referencePtr)) { return Merge(new[] { annotatedCommitHandle }, merger, options); From c0cf2496da6b74f97589c4fe9416071a8f22b938 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 11:22:13 +0100 Subject: [PATCH 13/50] Get rid of OidSafeHandle --- LibGit2Sharp/Core/Handles/OidSafeHandle.cs | 25 ----------- LibGit2Sharp/Core/NativeMethods.cs | 26 ++++++------ LibGit2Sharp/Core/Proxy.cs | 49 +++++++++++----------- LibGit2Sharp/LibGit2Sharp.csproj | 1 - LibGit2Sharp/ObjectId.cs | 5 +++ 5 files changed, 43 insertions(+), 63 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/OidSafeHandle.cs diff --git a/LibGit2Sharp/Core/Handles/OidSafeHandle.cs b/LibGit2Sharp/Core/Handles/OidSafeHandle.cs deleted file mode 100644 index ced01e50a..000000000 --- a/LibGit2Sharp/Core/Handles/OidSafeHandle.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace LibGit2Sharp.Core.Handles -{ - internal class OidSafeHandle : NotOwnedSafeHandleBase - { - private GitOid? MarshalAsGitOid() - { - return IsZero || IsInvalid ? null : (GitOid?)MarshalAsGitOid(handle); - } - - private static GitOid MarshalAsGitOid(IntPtr data) - { - var gitOid = new GitOid { Id = new byte[GitOid.Size] }; - Marshal.Copy(data, gitOid.Id, 0, GitOid.Size); - return gitOid; - } - - public ObjectId MarshalAsObjectId() - { - return MarshalAsGitOid(); - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 03b4fe751..d5d2f4ffe 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -316,13 +316,13 @@ internal static extern int git_commit_create_from_ids( internal static extern string git_commit_message_encoding(GitObjectSafeHandle commit); [DllImport(libgit2)] - internal static extern OidSafeHandle git_commit_parent_id(GitObjectSafeHandle commit, uint n); + internal static extern unsafe git_oid* git_commit_parent_id(GitObjectSafeHandle commit, uint n); [DllImport(libgit2)] internal static extern uint git_commit_parentcount(GitObjectSafeHandle commit); [DllImport(libgit2)] - internal static extern OidSafeHandle git_commit_tree_id(GitObjectSafeHandle commit); + internal static extern unsafe git_oid* git_commit_tree_id(GitObjectSafeHandle commit); [DllImport(libgit2)] internal static extern int git_config_delete_entry( @@ -767,7 +767,7 @@ internal static extern int git_annotated_commit_lookup( ref GitOid id); [DllImport(libgit2)] - internal static extern OidSafeHandle git_annotated_commit_id( + internal static extern unsafe git_oid* git_annotated_commit_id( GitAnnotatedCommitHandle annotatedCommit); [DllImport(libgit2)] @@ -824,7 +824,7 @@ internal static extern int git_note_create( internal static extern string git_note_message(NoteSafeHandle note); [DllImport(libgit2)] - internal static extern OidSafeHandle git_note_id(NoteSafeHandle note); + internal static extern unsafe git_oid* git_note_id(NoteSafeHandle note); [DllImport(libgit2)] internal static extern int git_note_read( @@ -899,7 +899,7 @@ internal static extern int git_odb_foreach( internal static extern void git_odb_stream_free(IntPtr stream); [DllImport(libgit2)] - internal static extern OidSafeHandle git_object_id(GitObjectSafeHandle obj); + internal static extern unsafe git_oid* git_object_id(GitObjectSafeHandle obj); [DllImport(libgit2)] internal static extern int git_object_lookup(out GitObjectSafeHandle obj, RepositorySafeHandle repo, ref GitOid id, GitObjectType type); @@ -1038,7 +1038,7 @@ internal static extern int git_reference_remove( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern unsafe OidSafeHandle git_reference_target(git_reference* reference); + internal static extern unsafe git_oid* git_reference_target(git_reference* reference); [DllImport(libgit2)] internal static extern unsafe int git_reference_rename( @@ -1094,11 +1094,11 @@ internal static extern ReflogEntrySafeHandle git_reflog_entry_byindex( UIntPtr idx); [DllImport(libgit2)] - internal static extern OidSafeHandle git_reflog_entry_id_old( + internal static extern unsafe git_oid* git_reflog_entry_id_old( SafeHandle entry); [DllImport(libgit2)] - internal static extern OidSafeHandle git_reflog_entry_id_new( + internal static extern unsafe git_oid* git_reflog_entry_id_new( SafeHandle entry); [DllImport(libgit2)] @@ -1604,15 +1604,15 @@ internal static extern string git_submodule_url( SubmoduleSafeHandle submodule); [DllImport(libgit2)] - internal static extern OidSafeHandle git_submodule_index_id( + internal static extern unsafe git_oid* git_submodule_index_id( SubmoduleSafeHandle submodule); [DllImport(libgit2)] - internal static extern OidSafeHandle git_submodule_head_id( + internal static extern unsafe git_oid* git_submodule_head_id( SubmoduleSafeHandle submodule); [DllImport(libgit2)] - internal static extern OidSafeHandle git_submodule_wd_id( + internal static extern unsafe git_oid* git_submodule_wd_id( SubmoduleSafeHandle submodule); [DllImport(libgit2)] @@ -1693,7 +1693,7 @@ internal static extern int git_tag_delete( internal static extern IntPtr git_tag_tagger(GitObjectSafeHandle tag); [DllImport(libgit2)] - internal static extern OidSafeHandle git_tag_target_id(GitObjectSafeHandle tag); + internal static extern unsafe git_oid* git_tag_target_id(GitObjectSafeHandle tag); [DllImport(libgit2)] internal static extern GitObjectType git_tag_target_type(GitObjectSafeHandle tag); @@ -1750,7 +1750,7 @@ internal static extern unsafe int git_tree_entry_bypath( internal static extern unsafe void git_tree_entry_free(git_tree_entry* treeEntry); [DllImport(libgit2)] - internal static extern unsafe OidSafeHandle git_tree_entry_id(git_tree_entry* entry); + internal static extern unsafe git_oid* git_tree_entry_id(git_tree_entry* entry); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index f593eb73e..2b7006015 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -408,9 +408,9 @@ public static string git_commit_message_encoding(GitObjectSafeHandle obj) return NativeMethods.git_commit_message_encoding(obj); } - public static ObjectId git_commit_parent_id(GitObjectSafeHandle obj, uint i) + public static unsafe ObjectId git_commit_parent_id(GitObjectSafeHandle obj, uint i) { - return NativeMethods.git_commit_parent_id(obj, i).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_commit_parent_id(obj, i)); } public static int git_commit_parentcount(RepositorySafeHandle repo, ObjectId id) @@ -426,9 +426,9 @@ public static int git_commit_parentcount(ObjectSafeWrapper obj) return (int)NativeMethods.git_commit_parentcount(obj.ObjectPtr); } - public static ObjectId git_commit_tree_id(GitObjectSafeHandle obj) + public static unsafe ObjectId git_commit_tree_id(GitObjectSafeHandle obj) { - return NativeMethods.git_commit_tree_id(obj).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_commit_tree_id(obj)); } #endregion @@ -1187,9 +1187,9 @@ public static GitAnnotatedCommitHandle git_annotated_commit_from_revspec(Reposit return their_head; } - public static ObjectId git_annotated_commit_id(GitAnnotatedCommitHandle mergeHead) + public static unsafe ObjectId git_annotated_commit_id(GitAnnotatedCommitHandle mergeHead) { - return NativeMethods.git_annotated_commit_id(mergeHead).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_annotated_commit_id(mergeHead)); } public static void git_merge(RepositorySafeHandle repo, GitAnnotatedCommitHandle[] heads, GitMergeOpts mergeOptions, GitCheckoutOpts checkoutOptions) @@ -1308,9 +1308,9 @@ public static string git_note_message(NoteSafeHandle note) return NativeMethods.git_note_message(note); } - public static ObjectId git_note_id(NoteSafeHandle note) + public static unsafe ObjectId git_note_id(NoteSafeHandle note) { - return NativeMethods.git_note_id(note).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_note_id(note)); } public static NoteSafeHandle git_note_read(RepositorySafeHandle repo, string notes_ref, ObjectId id) @@ -1352,9 +1352,9 @@ public static void git_note_remove(RepositorySafeHandle repo, string notes_ref, #region git_object_ - public static ObjectId git_object_id(GitObjectSafeHandle obj) + public static unsafe ObjectId git_object_id(GitObjectSafeHandle obj) { - return NativeMethods.git_object_id(obj).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_object_id(obj)); } public static void git_object_free(IntPtr obj) @@ -1883,7 +1883,7 @@ public static void git_reference_remove(RepositorySafeHandle repo, string name) public static unsafe ObjectId git_reference_target(git_reference* reference) { - return NativeMethods.git_reference_target(reference).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_reference_target(reference)); } public static unsafe ReferenceHandle git_reference_rename( @@ -1966,14 +1966,14 @@ public static ReflogEntrySafeHandle git_reflog_entry_byindex(ReflogSafeHandle re return NativeMethods.git_reflog_entry_byindex(reflog, (UIntPtr)idx); } - public static ObjectId git_reflog_entry_id_old(SafeHandle entry) + public static unsafe ObjectId git_reflog_entry_id_old(SafeHandle entry) { - return NativeMethods.git_reflog_entry_id_old(entry).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_reflog_entry_id_old(entry)); } - public static ObjectId git_reflog_entry_id_new(SafeHandle entry) + public static unsafe ObjectId git_reflog_entry_id_new(SafeHandle entry) { - return NativeMethods.git_reflog_entry_id_new(entry).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_reflog_entry_id_new(entry)); } public static Signature git_reflog_entry_committer(SafeHandle entry) @@ -2938,19 +2938,20 @@ public static string git_submodule_url(SubmoduleSafeHandle submodule) return NativeMethods.git_submodule_url(submodule); } - public static ObjectId git_submodule_index_id(SubmoduleSafeHandle submodule) + public static unsafe ObjectId git_submodule_index_id(SubmoduleSafeHandle submodule) { - return NativeMethods.git_submodule_index_id(submodule).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_submodule_index_id(submodule)); } - public static ObjectId git_submodule_head_id(SubmoduleSafeHandle submodule) + public static unsafe ObjectId git_submodule_head_id(SubmoduleSafeHandle submodule) { - return NativeMethods.git_submodule_head_id(submodule).MarshalAsObjectId(); + Console.WriteLine("got git_oid for head {0}", NativeMethods.git_submodule_head_id(submodule) == null); + return ObjectId.BuildFromPtr(NativeMethods.git_submodule_head_id(submodule)); } - public static ObjectId git_submodule_wd_id(SubmoduleSafeHandle submodule) + public static unsafe ObjectId git_submodule_wd_id(SubmoduleSafeHandle submodule) { - return NativeMethods.git_submodule_wd_id(submodule).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_submodule_wd_id(submodule)); } public static SubmoduleIgnore git_submodule_ignore(SubmoduleSafeHandle submodule) @@ -3089,9 +3090,9 @@ public static Signature git_tag_tagger(GitObjectSafeHandle tag) return tagger; } - public static ObjectId git_tag_target_id(GitObjectSafeHandle tag) + public static unsafe ObjectId git_tag_target_id(GitObjectSafeHandle tag) { - return NativeMethods.git_tag_target_id(tag).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_tag_target_id(tag)); } public static GitObjectType git_tag_target_type(GitObjectSafeHandle tag) @@ -3190,7 +3191,7 @@ public static unsafe TreeEntryHandle git_tree_entry_bypath(RepositorySafeHandle public static unsafe ObjectId git_tree_entry_id(git_tree_entry* entry) { - return NativeMethods.git_tree_entry_id(entry).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_tree_entry_id(entry)); } public static unsafe string git_tree_entry_name(git_tree_entry* entry) diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 7d6a4c1ca..413b0bf22 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -281,7 +281,6 @@ - diff --git a/LibGit2Sharp/ObjectId.cs b/LibGit2Sharp/ObjectId.cs index 5c569e9fd..12051d066 100644 --- a/LibGit2Sharp/ObjectId.cs +++ b/LibGit2Sharp/ObjectId.cs @@ -57,6 +57,11 @@ public ObjectId(byte[] rawId) Ensure.ArgumentConformsTo(rawId, b => b.Length == rawSize, "rawId"); } + internal static unsafe ObjectId BuildFromPtr(git_oid* id) + { + return id == null ? null : new ObjectId(id->Id); + } + internal unsafe ObjectId(byte* rawId) { byte[] id = new byte[GitOid.Size]; From 70074f9ae29ea59f57a76fa774cc47a048bcdfaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 11:34:12 +0100 Subject: [PATCH 14/50] Get rid of GitRefSpecHandle --- LibGit2Sharp/Core/Handles/GitRefSpecHandle.cs | 6 ----- LibGit2Sharp/Core/NativeMethods.cs | 22 +++++++++---------- LibGit2Sharp/Core/Opaques.cs | 1 + LibGit2Sharp/Core/Proxy.cs | 14 ++++++------ LibGit2Sharp/LibGit2Sharp.csproj | 1 - LibGit2Sharp/RefSpec.cs | 10 ++++++--- LibGit2Sharp/RefSpecCollection.cs | 8 +++---- LibGit2Sharp/Remote.cs | 4 ++-- 8 files changed, 31 insertions(+), 35 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/GitRefSpecHandle.cs diff --git a/LibGit2Sharp/Core/Handles/GitRefSpecHandle.cs b/LibGit2Sharp/Core/Handles/GitRefSpecHandle.cs deleted file mode 100644 index a795472f6..000000000 --- a/LibGit2Sharp/Core/Handles/GitRefSpecHandle.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class GitRefSpecHandle : NotOwnedSafeHandleBase - { - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index d5d2f4ffe..ce6c693ab 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1110,31 +1110,31 @@ internal static extern IntPtr git_reflog_entry_committer( internal static extern string git_reflog_entry_message(SafeHandle entry); [DllImport(libgit2)] - internal static extern int git_refspec_rtransform( + internal static extern unsafe int git_refspec_rtransform( GitBuf buf, - GitRefSpecHandle refSpec, + git_refspec* refSpec, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_refspec_string( - GitRefSpecHandle refSpec); + internal static extern unsafe string git_refspec_string( + git_refspec* refSpec); [DllImport(libgit2)] - internal static extern RefSpecDirection git_refspec_direction(GitRefSpecHandle refSpec); + internal static extern unsafe RefSpecDirection git_refspec_direction(git_refspec* refSpec); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_refspec_dst( - GitRefSpecHandle refSpec); + internal static extern unsafe string git_refspec_dst( + git_refspec* refSpec); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_refspec_src( - GitRefSpecHandle refSpec); + internal static extern unsafe string git_refspec_src( + git_refspec* refSpec); [DllImport(libgit2)] - internal static extern bool git_refspec_force(GitRefSpecHandle refSpec); + internal static extern unsafe bool git_refspec_force(git_refspec* refSpec); [DllImport(libgit2)] internal static extern int git_remote_autotag(RemoteSafeHandle remote); @@ -1187,7 +1187,7 @@ internal static extern int git_remote_fetch( internal static extern int git_remote_get_fetch_refspecs(out GitStrArray array, RemoteSafeHandle remote); [DllImport(libgit2)] - internal static extern GitRefSpecHandle git_remote_get_refspec(RemoteSafeHandle remote, UIntPtr n); + internal static extern unsafe git_refspec* git_remote_get_refspec(RemoteSafeHandle remote, UIntPtr n); [DllImport(libgit2)] internal static extern int git_remote_get_push_refspecs(out GitStrArray array, RemoteSafeHandle remote); diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index 25f77be68..a1293ed24 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -4,5 +4,6 @@ namespace LibGit2Sharp.Core { internal struct git_tree_entry {} internal struct git_reference { } + internal struct git_refspec {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 2b7006015..b4c38178b 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -1990,7 +1990,7 @@ public static string git_reflog_entry_message(SafeHandle entry) #region git_refspec - public static string git_refspec_rtransform(GitRefSpecHandle refSpecPtr, string name) + public static unsafe string git_refspec_rtransform(git_refspec* refSpecPtr, string name) { using (var buf = new GitBuf()) { @@ -2001,27 +2001,27 @@ public static string git_refspec_rtransform(GitRefSpecHandle refSpecPtr, string } } - public static string git_refspec_string(GitRefSpecHandle refSpec) + public static unsafe string git_refspec_string(git_refspec* refSpec) { return NativeMethods.git_refspec_string(refSpec); } - public static string git_refspec_src(GitRefSpecHandle refSpec) + public static unsafe string git_refspec_src(git_refspec* refSpec) { return NativeMethods.git_refspec_src(refSpec); } - public static string git_refspec_dst(GitRefSpecHandle refSpec) + public static unsafe string git_refspec_dst(git_refspec* refSpec) { return NativeMethods.git_refspec_dst(refSpec); } - public static RefSpecDirection git_refspec_direction(GitRefSpecHandle refSpec) + public static unsafe RefSpecDirection git_refspec_direction(git_refspec* refSpec) { return NativeMethods.git_refspec_direction(refSpec); } - public static bool git_refspec_force(GitRefSpecHandle refSpec) + public static unsafe bool git_refspec_force(git_refspec* refSpec) { return NativeMethods.git_refspec_force(refSpec); } @@ -2089,7 +2089,7 @@ public static void git_remote_delete(RepositorySafeHandle repo, string name) Ensure.ZeroResult(res); } - public static GitRefSpecHandle git_remote_get_refspec(RemoteSafeHandle remote, int n) + public static unsafe git_refspec* git_remote_get_refspec(RemoteSafeHandle remote, int n) { return NativeMethods.git_remote_get_refspec(remote, (UIntPtr)n); } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 413b0bf22..1eadaa68b 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -192,7 +192,6 @@ - diff --git a/LibGit2Sharp/RefSpec.cs b/LibGit2Sharp/RefSpec.cs index 9c811c5f9..3d6fe5d18 100644 --- a/LibGit2Sharp/RefSpec.cs +++ b/LibGit2Sharp/RefSpec.cs @@ -1,4 +1,5 @@ -using System.Diagnostics; +using System; +using System.Diagnostics; using System.Globalization; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; @@ -30,9 +31,12 @@ private RefSpec(string refSpec, RefSpecDirection direction, string source, strin protected RefSpec() { } - internal static RefSpec BuildFromPtr(GitRefSpecHandle handle) + internal static unsafe RefSpec BuildFromPtr(git_refspec* handle) { - Ensure.ArgumentNotNull(handle, "handle"); + if (handle == null) + { + throw new ArgumentNullException("handle"); + } return new RefSpec(Proxy.git_refspec_string(handle), Proxy.git_refspec_direction(handle), Proxy.git_refspec_src(handle), Proxy.git_refspec_dst(handle), Proxy.git_refspec_force(handle)); diff --git a/LibGit2Sharp/RefSpecCollection.cs b/LibGit2Sharp/RefSpecCollection.cs index 163281a12..69c098107 100644 --- a/LibGit2Sharp/RefSpecCollection.cs +++ b/LibGit2Sharp/RefSpecCollection.cs @@ -29,17 +29,15 @@ internal RefSpecCollection(RemoteSafeHandle handle) refspecs = RetrieveRefSpecs(handle); } - static IList RetrieveRefSpecs(RemoteSafeHandle remoteHandle) + static unsafe IList RetrieveRefSpecs(RemoteSafeHandle remoteHandle) { int count = Proxy.git_remote_refspec_count(remoteHandle); List refSpecs = new List(); for (int i = 0; i < count; i++) { - using (GitRefSpecHandle handle = Proxy.git_remote_get_refspec(remoteHandle, i)) - { - refSpecs.Add(RefSpec.BuildFromPtr(handle)); - } + git_refspec* handle = Proxy.git_remote_get_refspec(remoteHandle, i); + refSpecs.Add(RefSpec.BuildFromPtr(handle)); } return refSpecs; diff --git a/LibGit2Sharp/Remote.cs b/LibGit2Sharp/Remote.cs index 137208198..a28457713 100644 --- a/LibGit2Sharp/Remote.cs +++ b/LibGit2Sharp/Remote.cs @@ -98,11 +98,11 @@ public virtual IEnumerable PushRefSpecs /// /// The reference to transform. /// The transformed reference. - internal string FetchSpecTransformToSource(string reference) + internal unsafe string FetchSpecTransformToSource(string reference) { using (RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, Name, true)) { - GitRefSpecHandle fetchSpecPtr = Proxy.git_remote_get_refspec(remoteHandle, 0); + git_refspec* fetchSpecPtr = Proxy.git_remote_get_refspec(remoteHandle, 0); return Proxy.git_refspec_rtransform(fetchSpecPtr, reference); } } From 8be1e389abc91b8deea36da4b87dbda2a26aa3b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 11:35:22 +0100 Subject: [PATCH 15/50] Remove unused TreeEntrySafeHandle --- LibGit2Sharp/Core/Handles/TreeEntrySafeHandle.cs | 6 ------ LibGit2Sharp/LibGit2Sharp.csproj | 1 - 2 files changed, 7 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/TreeEntrySafeHandle.cs diff --git a/LibGit2Sharp/Core/Handles/TreeEntrySafeHandle.cs b/LibGit2Sharp/Core/Handles/TreeEntrySafeHandle.cs deleted file mode 100644 index f621cb2ff..000000000 --- a/LibGit2Sharp/Core/Handles/TreeEntrySafeHandle.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class TreeEntrySafeHandle : NotOwnedSafeHandleBase - { - } -} diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 1eadaa68b..43a7b07f0 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -282,7 +282,6 @@ - From 86498c7155cadc136d8c3b20e532f684cd0dfd41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 12:30:43 +0100 Subject: [PATCH 16/50] Get rid of RepositorySafeHandle We add an implicit conversion from the handle to the pointer as there are a lot of places which rely on the equivalent functionality for the SafeHandle. --- LibGit2Sharp/BlameHunkCollection.cs | 2 +- LibGit2Sharp/Core/Handles/Objects.cs | 86 ++++ LibGit2Sharp/Core/Handles/Objects.tt | 11 + .../Core/Handles/RepositorySafeHandle.cs | 11 - LibGit2Sharp/Core/NativeMethods.cs | 380 +++++++++--------- LibGit2Sharp/Core/ObjectSafeWrapper.cs | 2 +- LibGit2Sharp/Core/Opaques.cs | 1 + LibGit2Sharp/Core/Proxy.cs | 304 +++++++------- LibGit2Sharp/LibGit2Sharp.csproj | 1 - LibGit2Sharp/Network.cs | 14 +- LibGit2Sharp/Repository.cs | 12 +- 11 files changed, 452 insertions(+), 372 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/RepositorySafeHandle.cs diff --git a/LibGit2Sharp/BlameHunkCollection.cs b/LibGit2Sharp/BlameHunkCollection.cs index 35b945523..143d598b1 100644 --- a/LibGit2Sharp/BlameHunkCollection.cs +++ b/LibGit2Sharp/BlameHunkCollection.cs @@ -20,7 +20,7 @@ public class BlameHunkCollection : IEnumerable /// protected BlameHunkCollection() { } - internal BlameHunkCollection(Repository repo, RepositorySafeHandle repoHandle, string path, BlameOptions options) + internal BlameHunkCollection(Repository repo, RepositoryHandle repoHandle, string path, BlameOptions options) { this.repo = repo; diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index 08a4866fc..cec9129af 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -43,6 +43,10 @@ internal bool IsNull } } + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } void Dispose(bool disposing) { @@ -61,6 +65,11 @@ public void Dispose() { Dispose(true); } + + public static implicit operator git_tree_entry*(TreeEntryHandle handle) + { + return handle.Handle; + } } internal unsafe class ReferenceHandle : IDisposable @@ -102,6 +111,10 @@ internal bool IsNull } } + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } void Dispose(bool disposing) { @@ -120,6 +133,79 @@ public void Dispose() { Dispose(true); } + + public static implicit operator git_reference*(ReferenceHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class RepositoryHandle : IDisposable + { + git_repository* ptr; + internal git_repository* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe RepositoryHandle(git_repository* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe RepositoryHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_repository*) ptr.ToPointer(); + this.owned = owned; + } + + ~RepositoryHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_repository_free(ptr); + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_repository*(RepositoryHandle handle) + { + return handle.Handle; + } } } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 3518e2837..1fc79dc4e 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -14,11 +14,13 @@ namespace LibGit2Sharp.Core var cNames = new[] { "git_tree_entry", "git_reference", + "git_repository", }; var csNames = new[] { "TreeEntryHandle", "ReferenceHandle", + "RepositoryHandle", }; for (var i = 0; i < cNames.Length; i++) @@ -63,6 +65,10 @@ for (var i = 0; i < cNames.Length; i++) } } + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } void Dispose(bool disposing) { @@ -81,6 +87,11 @@ for (var i = 0; i < cNames.Length; i++) { Dispose(true); } + + public static implicit operator <#= cNames[i] #>*(<#= csNames[i] #> handle) + { + return handle.Handle; + } } <# diff --git a/LibGit2Sharp/Core/Handles/RepositorySafeHandle.cs b/LibGit2Sharp/Core/Handles/RepositorySafeHandle.cs deleted file mode 100644 index 889a3022c..000000000 --- a/LibGit2Sharp/Core/Handles/RepositorySafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class RepositorySafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_repository_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index ce6c693ab..a2dfccc13 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -97,9 +97,9 @@ internal static extern IntPtr git_blame_get_hunk_byindex( BlameSafeHandle blame, UInt32 index); [DllImport(libgit2)] - internal static extern int git_blame_file( + internal static extern unsafe int git_blame_file( out BlameSafeHandle blame, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, GitBlameOptions options); @@ -107,15 +107,15 @@ internal static extern int git_blame_file( internal static extern void git_blame_free(IntPtr blame); [DllImport(libgit2)] - internal static extern int git_blob_create_fromdisk( + internal static extern unsafe int git_blob_create_fromdisk( ref GitOid id, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] - internal static extern int git_blob_create_fromworkdir( + internal static extern unsafe int git_blob_create_fromworkdir( ref GitOid id, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath relative_path); internal delegate int source_callback( @@ -124,9 +124,9 @@ internal delegate int source_callback( IntPtr data); [DllImport(libgit2)] - internal static extern int git_blob_create_fromchunks( + internal static extern unsafe int git_blob_create_fromchunks( ref GitOid oid, - RepositorySafeHandle repositoryPtr, + git_repository* repositoryPtr, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath hintpath, source_callback fileCallback, IntPtr data); @@ -147,7 +147,7 @@ internal static extern int git_blob_filtered_content( [DllImport(libgit2)] internal static extern unsafe int git_branch_create_from_annotated( out git_reference* ref_out, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string branch_name, GitAnnotatedCommitHandle target, [MarshalAs(UnmanagedType.Bool)] bool force); @@ -168,7 +168,7 @@ internal static extern void git_branch_iterator_free( [DllImport(libgit2)] internal static extern int git_branch_iterator_new( out IntPtr iter_out, - RepositorySafeHandle repo, + IntPtr repo, GitBranchType branch_type); [DllImport(libgit2)] @@ -185,24 +185,24 @@ internal static extern int git_branch_next( IntPtr iter); [DllImport(libgit2)] - internal static extern int git_branch_remote_name( + internal static extern unsafe int git_branch_remote_name( GitBuf buf, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string canonical_branch_name); [DllImport(libgit2)] - internal static extern int git_rebase_init( + internal static extern unsafe int git_rebase_init( out RebaseSafeHandle rebase, - RepositorySafeHandle repo, + git_repository* repo, GitAnnotatedCommitHandle branch, GitAnnotatedCommitHandle upstream, GitAnnotatedCommitHandle onto, GitRebaseOptions options); [DllImport(libgit2)] - internal static extern int git_rebase_open( + internal static extern unsafe int git_rebase_open( out RebaseSafeHandle rebase, - RepositorySafeHandle repo, + git_repository* repo, GitRebaseOptions options); [DllImport(libgit2)] @@ -246,9 +246,9 @@ internal static extern void git_rebase_free( IntPtr rebase); [DllImport(libgit2)] - internal static extern int git_remote_rename( + internal static extern unsafe int git_remote_rename( ref GitStrArray problems, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string old_name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string new_name); @@ -257,29 +257,29 @@ internal delegate int git_remote_rename_problem_cb( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_branch_upstream_name( + internal static extern unsafe int git_branch_upstream_name( GitBuf buf, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string referenceName); [DllImport(libgit2)] internal static extern void git_buf_free(GitBuf buf); [DllImport(libgit2)] - internal static extern int git_checkout_tree( - RepositorySafeHandle repo, + internal static extern unsafe int git_checkout_tree( + git_repository* repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts); [DllImport(libgit2)] - internal static extern int git_checkout_index( - RepositorySafeHandle repo, + internal static extern unsafe int git_checkout_index( + git_repository* repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts); [DllImport(libgit2)] - internal static extern int git_clone( - out RepositorySafeHandle repo, + internal static extern unsafe int git_clone( + out git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string origin_url, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath workdir_path, ref GitCloneOptions opts); @@ -291,9 +291,9 @@ internal static extern int git_clone( internal static extern IntPtr git_commit_committer(GitObjectSafeHandle commit); [DllImport(libgit2)] - internal static extern int git_commit_create_from_ids( + internal static extern unsafe int git_commit_create_from_ids( out GitOid id, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string updateRef, SignatureSafeHandle author, SignatureSafeHandle committer, @@ -478,17 +478,17 @@ internal static extern int git_describe_format( internal static extern void git_diff_free(IntPtr diff); [DllImport(libgit2)] - internal static extern int git_diff_tree_to_tree( + internal static extern unsafe int git_diff_tree_to_tree( out DiffSafeHandle diff, - RepositorySafeHandle repo, + git_repository* repo, GitObjectSafeHandle oldTree, GitObjectSafeHandle newTree, GitDiffOptions options); [DllImport(libgit2)] - internal static extern int git_diff_tree_to_index( + internal static extern unsafe int git_diff_tree_to_index( out DiffSafeHandle diff, - RepositorySafeHandle repo, + git_repository* repo, GitObjectSafeHandle oldTree, IndexSafeHandle index, GitDiffOptions options); @@ -499,16 +499,16 @@ internal static extern int git_diff_merge( DiffSafeHandle from); [DllImport(libgit2)] - internal static extern int git_diff_index_to_workdir( + internal static extern unsafe int git_diff_index_to_workdir( out DiffSafeHandle diff, - RepositorySafeHandle repo, + git_repository* repo, IndexSafeHandle index, GitDiffOptions options); [DllImport(libgit2)] - internal static extern int git_diff_tree_to_workdir( + internal static extern unsafe int git_diff_tree_to_workdir( out DiffSafeHandle diff, - RepositorySafeHandle repo, + git_repository* repo, GitObjectSafeHandle oldTree, GitDiffOptions options); @@ -529,9 +529,9 @@ internal delegate int git_diff_line_cb( IntPtr payload); internal delegate int git_diff_binary_cb( - [In] GitDiffDelta delta, - [In] GitDiffBinary binary, - IntPtr payload); + [In] GitDiffDelta delta, + [In] GitDiffBinary binary, + IntPtr payload); [DllImport(libgit2)] internal static extern int git_diff_blobs( @@ -601,26 +601,26 @@ internal static extern int git_libgit2_opts(int option, uint level, #endregion [DllImport(libgit2)] - internal static extern int git_graph_ahead_behind(out UIntPtr ahead, out UIntPtr behind, RepositorySafeHandle repo, ref GitOid one, ref GitOid two); + internal static extern unsafe int git_graph_ahead_behind(out UIntPtr ahead, out UIntPtr behind, git_repository* repo, ref GitOid one, ref GitOid two); [DllImport(libgit2)] - internal static extern int git_graph_descendant_of( - RepositorySafeHandle repo, + internal static extern unsafe int git_graph_descendant_of( + git_repository* repo, ref GitOid commit, ref GitOid ancestor); [DllImport(libgit2)] - internal static extern int git_ignore_add_rule( - RepositorySafeHandle repo, + internal static extern unsafe int git_ignore_add_rule( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string rules); [DllImport(libgit2)] - internal static extern int git_ignore_clear_internal_rules(RepositorySafeHandle repo); + internal static extern unsafe int git_ignore_clear_internal_rules(git_repository* repo); [DllImport(libgit2)] - internal static extern int git_ignore_path_is_ignored( + internal static extern unsafe int git_ignore_path_is_ignored( out int ignored, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] @@ -718,7 +718,7 @@ internal static extern IndexReucEntrySafeHandle git_index_reuc_get_bypath( internal static extern int git_index_write_tree(out GitOid treeOid, IndexSafeHandle index); [DllImport(libgit2)] - internal static extern int git_index_write_tree_to(out GitOid treeOid, IndexSafeHandle index, RepositorySafeHandle repo); + internal static extern unsafe int git_index_write_tree_to(out GitOid treeOid, IndexSafeHandle index, git_repository* repo); [DllImport(libgit2)] internal static extern int git_index_read_tree(IndexSafeHandle index, GitObjectSafeHandle tree); @@ -727,43 +727,43 @@ internal static extern IndexReucEntrySafeHandle git_index_reuc_get_bypath( internal static extern int git_index_clear(IndexSafeHandle index); [DllImport(libgit2)] - internal static extern int git_merge_base_many( + internal static extern unsafe int git_merge_base_many( out GitOid mergeBase, - RepositorySafeHandle repo, + git_repository* repo, int length, [In] GitOid[] input_array); [DllImport(libgit2)] - internal static extern int git_merge_base_octopus( + internal static extern unsafe int git_merge_base_octopus( out GitOid mergeBase, - RepositorySafeHandle repo, + git_repository* repo, int length, [In] GitOid[] input_array); [DllImport(libgit2)] internal static extern unsafe int git_annotated_commit_from_ref( out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, + git_repository* repo, git_reference* reference); [DllImport(libgit2)] - internal static extern int git_annotated_commit_from_fetchhead( + internal static extern unsafe int git_annotated_commit_from_fetchhead( out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string branch_name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote_url, ref GitOid oid); [DllImport(libgit2)] - internal static extern int git_annotated_commit_from_revspec( + internal static extern unsafe int git_annotated_commit_from_revspec( out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string revspec); [DllImport(libgit2)] - internal static extern int git_annotated_commit_lookup( + internal static extern unsafe int git_annotated_commit_lookup( out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, + git_repository* repo, ref GitOid id); [DllImport(libgit2)] @@ -771,26 +771,26 @@ internal static extern int git_annotated_commit_lookup( GitAnnotatedCommitHandle annotatedCommit); [DllImport(libgit2)] - internal static extern int git_merge( - RepositorySafeHandle repo, + internal static extern unsafe int git_merge( + git_repository* repo, [In] IntPtr[] their_heads, UIntPtr their_heads_len, ref GitMergeOpts merge_opts, ref GitCheckoutOpts checkout_opts); [DllImport(libgit2)] - internal static extern int git_merge_commits( + internal static extern unsafe int git_merge_commits( out IndexSafeHandle index, - RepositorySafeHandle repo, + git_repository* repo, GitObjectSafeHandle our_commit, GitObjectSafeHandle their_commit, ref GitMergeOpts merge_opts); [DllImport(libgit2)] - internal static extern int git_merge_analysis( + internal static extern unsafe int git_merge_analysis( out GitMergeAnalysis status_out, out GitMergePreference preference_out, - RepositorySafeHandle repo, + git_repository* repo, [In] IntPtr[] their_heads, int their_heads_len); @@ -806,9 +806,9 @@ internal static extern int git_message_prettify( sbyte comment_char); [DllImport(libgit2)] - internal static extern int git_note_create( + internal static extern unsafe int git_note_create( out GitOid noteOid, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, SignatureSafeHandle author, SignatureSafeHandle committer, @@ -827,24 +827,24 @@ internal static extern int git_note_create( internal static extern unsafe git_oid* git_note_id(NoteSafeHandle note); [DllImport(libgit2)] - internal static extern int git_note_read( + internal static extern unsafe int git_note_read( out NoteSafeHandle note, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, ref GitOid oid); [DllImport(libgit2)] - internal static extern int git_note_remove( - RepositorySafeHandle repo, + internal static extern unsafe int git_note_remove( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, SignatureSafeHandle author, SignatureSafeHandle committer, ref GitOid oid); [DllImport(libgit2)] - internal static extern int git_note_default_ref( + internal static extern unsafe int git_note_default_ref( GitBuf notes_ref, - RepositorySafeHandle repo); + git_repository* repo); internal delegate int git_note_foreach_cb( ref GitOid blob_id, @@ -852,8 +852,8 @@ internal delegate int git_note_foreach_cb( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_note_foreach( - RepositorySafeHandle repo, + internal static extern unsafe int git_note_foreach( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, git_note_foreach_cb cb, IntPtr payload); @@ -902,7 +902,7 @@ internal static extern int git_odb_foreach( internal static extern unsafe git_oid* git_object_id(GitObjectSafeHandle obj); [DllImport(libgit2)] - internal static extern int git_object_lookup(out GitObjectSafeHandle obj, RepositorySafeHandle repo, ref GitOid id, GitObjectType type); + internal static extern unsafe int git_object_lookup(out GitObjectSafeHandle obj, git_repository* repo, ref GitOid id, GitObjectType type); [DllImport(libgit2)] internal static extern int git_object_peel( @@ -964,7 +964,7 @@ internal static extern int git_packbuilder_insert_tree( ref GitOid id); [DllImport(libgit2)] - internal static extern int git_packbuilder_new(out PackBuilderSafeHandle packbuilder, RepositorySafeHandle repo); + internal static extern unsafe int git_packbuilder_new(out PackBuilderSafeHandle packbuilder, git_repository* repo); [DllImport(libgit2)] internal static extern UInt32 git_packbuilder_object_count(PackBuilderSafeHandle packbuilder); @@ -986,7 +986,7 @@ internal static extern int git_packbuilder_write( [DllImport(libgit2)] internal static extern unsafe int git_reference_create( out git_reference* reference, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, ref GitOid oid, [MarshalAs(UnmanagedType.Bool)] bool force, @@ -995,7 +995,7 @@ internal static extern unsafe int git_reference_create( [DllImport(libgit2)] internal static extern unsafe int git_reference_symbolic_create( out git_reference* reference, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string target, [MarshalAs(UnmanagedType.Bool)] bool force, @@ -1006,8 +1006,8 @@ internal delegate int ref_glob_callback( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_reference_foreach_glob( - RepositorySafeHandle repo, + internal static extern unsafe int git_reference_foreach_glob( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string glob, ref_glob_callback callback, IntPtr payload); @@ -1020,12 +1020,12 @@ internal static extern int git_reference_is_valid_name( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refname); [DllImport(libgit2)] - internal static extern int git_reference_list(out GitStrArray array, RepositorySafeHandle repo); + internal static extern unsafe int git_reference_list(out GitStrArray array, git_repository* repo); [DllImport(libgit2)] internal static extern unsafe int git_reference_lookup( out git_reference* reference, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] @@ -1033,8 +1033,8 @@ internal static extern unsafe int git_reference_lookup( internal static extern unsafe string git_reference_name(git_reference* reference); [DllImport(libgit2)] - internal static extern int git_reference_remove( - RepositorySafeHandle repo, + internal static extern unsafe int git_reference_remove( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] @@ -1070,8 +1070,8 @@ internal static extern unsafe int git_reference_symbolic_set_target( internal static extern unsafe GitReferenceType git_reference_type(git_reference* reference); [DllImport(libgit2)] - internal static extern int git_reference_ensure_log( - RepositorySafeHandle repo, + internal static extern unsafe int git_reference_ensure_log( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refname); [DllImport(libgit2)] @@ -1079,9 +1079,9 @@ internal static extern void git_reflog_free( IntPtr reflog); [DllImport(libgit2)] - internal static extern int git_reflog_read( + internal static extern unsafe int git_reflog_read( out ReflogSafeHandle ref_out, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] @@ -1147,30 +1147,30 @@ internal static extern int git_remote_connect( ref GitStrArray custom_headers); [DllImport(libgit2)] - internal static extern int git_remote_create( + internal static extern unsafe int git_remote_create( out RemoteSafeHandle remote, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] - internal static extern int git_remote_create_anonymous( + internal static extern unsafe int git_remote_create_anonymous( out RemoteSafeHandle remote, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] - internal static extern int git_remote_create_with_fetchspec( + internal static extern unsafe int git_remote_create_with_fetchspec( out RemoteSafeHandle remote, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refspec); [DllImport(libgit2)] - internal static extern int git_remote_delete( - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_delete( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] @@ -1208,26 +1208,26 @@ internal static extern int git_remote_push( internal static extern int git_remote_set_push_refspecs(RemoteSafeHandle remote, ref GitStrArray array); [DllImport(libgit2)] - internal static extern int git_remote_set_url( - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_set_url( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] - internal static extern int git_remote_add_fetch( - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_add_fetch( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] - internal static extern int git_remote_set_pushurl( - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_set_pushurl( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] - internal static extern int git_remote_add_push( - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_add_push( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); @@ -1236,12 +1236,12 @@ internal static extern int git_remote_is_valid_name( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote_name); [DllImport(libgit2)] - internal static extern int git_remote_list(out GitStrArray array, RepositorySafeHandle repo); + internal static extern unsafe int git_remote_list(out GitStrArray array, git_repository* repo); [DllImport(libgit2)] - internal static extern int git_remote_lookup( + internal static extern unsafe int git_remote_lookup( out RemoteSafeHandle remote, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] @@ -1260,8 +1260,8 @@ internal static extern int git_remote_lookup( internal static extern string git_remote_pushurl(RemoteSafeHandle remote); [DllImport(libgit2)] - internal static extern void git_remote_set_autotag( - RepositorySafeHandle repo, + internal static extern unsafe void git_remote_set_autotag( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, TagFetchMode option); @@ -1301,141 +1301,141 @@ internal delegate int git_repository_fetchhead_foreach_cb( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_repository_fetchhead_foreach( - RepositorySafeHandle repo, + internal static extern unsafe int git_repository_fetchhead_foreach( + git_repository* repo, git_repository_fetchhead_foreach_cb cb, IntPtr payload); [DllImport(libgit2)] - internal static extern void git_repository_free(IntPtr repo); + internal static extern unsafe void git_repository_free(git_repository* repo); [DllImport(libgit2)] - internal static extern int git_repository_head_detached(RepositorySafeHandle repo); + internal static extern unsafe int git_repository_head_detached(IntPtr repo); [DllImport(libgit2)] - internal static extern int git_repository_head_unborn(RepositorySafeHandle repo); + internal static extern unsafe int git_repository_head_unborn(IntPtr repo); [DllImport(libgit2)] - internal static extern int git_repository_ident( + internal static extern unsafe int git_repository_ident( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] out string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] out string email, - RepositorySafeHandle repo); + git_repository* repo); [DllImport(libgit2)] - internal static extern int git_repository_index(out IndexSafeHandle index, RepositorySafeHandle repo); + internal static extern unsafe int git_repository_index(out IndexSafeHandle index, git_repository* repo); [DllImport(libgit2)] - internal static extern int git_repository_init_ext( - out RepositorySafeHandle repository, + internal static extern unsafe int git_repository_init_ext( + out git_repository* repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, GitRepositoryInitOptions options); [DllImport(libgit2)] - internal static extern int git_repository_is_bare(RepositorySafeHandle handle); + internal static extern int git_repository_is_bare(IntPtr handle); [DllImport(libgit2)] - internal static extern int git_repository_is_shallow(RepositorySafeHandle repo); + internal static extern int git_repository_is_shallow(IntPtr repo); [DllImport(libgit2)] - internal static extern int git_repository_state_cleanup(RepositorySafeHandle repo); + internal static extern unsafe int git_repository_state_cleanup(git_repository* repo); internal delegate int git_repository_mergehead_foreach_cb( ref GitOid oid, IntPtr payload); [DllImport(libgit2)] - internal static extern int git_repository_mergehead_foreach( - RepositorySafeHandle repo, + internal static extern unsafe int git_repository_mergehead_foreach( + git_repository* repo, git_repository_mergehead_foreach_cb cb, IntPtr payload); [DllImport(libgit2)] - internal static extern int git_repository_message( + internal static extern unsafe int git_repository_message( GitBuf buf, - RepositorySafeHandle repository); + git_repository* repository); [DllImport(libgit2)] - internal static extern int git_repository_odb(out ObjectDatabaseSafeHandle odb, RepositorySafeHandle repo); + internal static extern unsafe int git_repository_odb(out ObjectDatabaseSafeHandle odb, git_repository* repo); [DllImport(libgit2)] - internal static extern int git_repository_open( - out RepositorySafeHandle repository, + internal static extern unsafe int git_repository_open( + out git_repository* repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] - internal static extern int git_repository_open_ext( - NullRepositorySafeHandle repository, + internal static extern unsafe int git_repository_open_ext( + out git_repository* repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, RepositoryOpenFlags flags, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath ceilingDirs); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxFilePathNoCleanupMarshaler))] - internal static extern FilePath git_repository_path(RepositorySafeHandle repository); + internal static extern unsafe FilePath git_repository_path(git_repository* repository); [DllImport(libgit2)] - internal static extern void git_repository_set_config( - RepositorySafeHandle repository, + internal static extern unsafe void git_repository_set_config( + git_repository* repository, ConfigurationSafeHandle config); [DllImport(libgit2)] - internal static extern int git_repository_set_ident( - RepositorySafeHandle repo, + internal static extern unsafe int git_repository_set_ident( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string email); [DllImport(libgit2)] - internal static extern void git_repository_set_index( - RepositorySafeHandle repository, + internal static extern unsafe void git_repository_set_index( + git_repository* repository, IndexSafeHandle index); [DllImport(libgit2)] - internal static extern int git_repository_set_workdir( - RepositorySafeHandle repository, + internal static extern unsafe int git_repository_set_workdir( + git_repository* repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath workdir, [MarshalAs(UnmanagedType.Bool)] bool update_gitlink); [DllImport(libgit2)] - internal static extern int git_repository_set_head_detached( - RepositorySafeHandle repo, + internal static extern unsafe int git_repository_set_head_detached( + git_repository* repo, ref GitOid commitish); [DllImport(libgit2)] - internal static extern int git_repository_set_head_detached_from_annotated( - RepositorySafeHandle repo, + internal static extern unsafe int git_repository_set_head_detached_from_annotated( + git_repository* repo, GitAnnotatedCommitHandle commit); [DllImport(libgit2)] - internal static extern int git_repository_set_head( - RepositorySafeHandle repo, + internal static extern unsafe int git_repository_set_head( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refname); [DllImport(libgit2)] - internal static extern int git_repository_state( - RepositorySafeHandle repository); + internal static extern unsafe int git_repository_state( + git_repository* repository); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxFilePathNoCleanupMarshaler))] - internal static extern FilePath git_repository_workdir(RepositorySafeHandle repository); + internal static extern unsafe FilePath git_repository_workdir(git_repository* repository); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxFilePathNoCleanupMarshaler))] - internal static extern FilePath git_repository_workdir(IntPtr repository); + internal static extern unsafe FilePath git_repository_workdir(IntPtr repository); [DllImport(libgit2)] - internal static extern int git_repository_new(out RepositorySafeHandle repo); + internal static extern unsafe int git_repository_new(out git_repository* repo); [DllImport(libgit2)] - internal static extern int git_reset( - RepositorySafeHandle repo, + internal static extern unsafe int git_reset( + git_repository* repo, GitObjectSafeHandle target, ResetMode reset_type, ref GitCheckoutOpts opts); [DllImport(libgit2)] - internal static extern int git_revert( - RepositorySafeHandle repo, + internal static extern unsafe int git_revert( + git_repository* repo, GitObjectSafeHandle commit, GitRevertOpts opts); @@ -1443,7 +1443,7 @@ internal static extern int git_revert( internal static extern unsafe int git_revparse_ext( out GitObjectSafeHandle obj, out git_reference* reference, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string spec); [DllImport(libgit2)] @@ -1453,7 +1453,7 @@ internal static extern unsafe int git_revparse_ext( internal static extern int git_revwalk_hide(RevWalkerSafeHandle walker, ref GitOid commit_id); [DllImport(libgit2)] - internal static extern int git_revwalk_new(out RevWalkerSafeHandle walker, RepositorySafeHandle repo); + internal static extern unsafe int git_revwalk_new(out RevWalkerSafeHandle walker, git_repository* repo); [DllImport(libgit2)] internal static extern int git_revwalk_next(out GitOid id, RevWalkerSafeHandle walker); @@ -1491,9 +1491,9 @@ internal static extern int git_signature_now( internal static extern int git_signature_dup(out IntPtr dest, IntPtr sig); [DllImport(libgit2)] - internal static extern int git_stash_save( + internal static extern unsafe int git_stash_save( out GitOid id, - RepositorySafeHandle repo, + git_repository* repo, SignatureSafeHandle stasher, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, StashModifiers flags); @@ -1505,37 +1505,37 @@ internal delegate int git_stash_cb( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_stash_foreach( - RepositorySafeHandle repo, + internal static extern unsafe int git_stash_foreach( + git_repository* repo, git_stash_cb callback, IntPtr payload); [DllImport(libgit2)] - internal static extern int git_stash_drop(RepositorySafeHandle repo, UIntPtr index); + internal static extern unsafe int git_stash_drop(git_repository* repo, UIntPtr index); [DllImport(libgit2)] - internal static extern int git_stash_apply( - RepositorySafeHandle repo, + internal static extern unsafe int git_stash_apply( + git_repository* repo, UIntPtr index, GitStashApplyOpts opts); [DllImport(libgit2)] - internal static extern int git_stash_pop( - RepositorySafeHandle repo, + internal static extern unsafe int git_stash_pop( + git_repository* repo, UIntPtr index, GitStashApplyOpts opts); [DllImport(libgit2)] - internal static extern int git_status_file( + internal static extern unsafe int git_status_file( out FileStatus statusflags, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath filepath); [DllImport(libgit2)] - internal static extern int git_status_list_new( + internal static extern unsafe int git_status_list_new( out StatusListSafeHandle git_status_list, - RepositorySafeHandle repo, + git_repository* repo, GitStatusOptions options); [DllImport(libgit2)] @@ -1556,15 +1556,15 @@ internal static extern void git_strarray_free( ref GitStrArray array); [DllImport(libgit2)] - internal static extern int git_submodule_lookup( + internal static extern unsafe int git_submodule_lookup( out SubmoduleSafeHandle reference, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath name); [DllImport(libgit2)] - internal static extern int git_submodule_resolve_url( + internal static extern unsafe int git_submodule_resolve_url( GitBuf buf, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] @@ -1579,8 +1579,8 @@ internal delegate int submodule_callback( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_submodule_foreach( - RepositorySafeHandle repo, + internal static extern unsafe int git_submodule_foreach( + git_repository* repo, submodule_callback callback, IntPtr payload); @@ -1633,9 +1633,9 @@ internal static extern int git_submodule_reload( [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] - internal static extern int git_submodule_status( + internal static extern unsafe int git_submodule_status( out SubmoduleStatus status, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath name, GitSubmoduleIgnore ignore); @@ -1645,18 +1645,18 @@ internal static extern int git_submodule_init( [MarshalAs(UnmanagedType.Bool)] bool overwrite); [DllImport(libgit2)] - internal static extern int git_tag_annotation_create( + internal static extern unsafe int git_tag_annotation_create( out GitOid oid, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, SignatureSafeHandle signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message); [DllImport(libgit2)] - internal static extern int git_tag_create( + internal static extern unsafe int git_tag_create( out GitOid oid, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, SignatureSafeHandle signature, @@ -1665,21 +1665,21 @@ internal static extern int git_tag_create( bool force); [DllImport(libgit2)] - internal static extern int git_tag_create_lightweight( + internal static extern unsafe int git_tag_create_lightweight( out GitOid oid, - RepositorySafeHandle repo, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] - internal static extern int git_tag_delete( - RepositorySafeHandle repo, + internal static extern unsafe int git_tag_delete( + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string tagName); [DllImport(libgit2)] - internal static extern int git_tag_list(out GitStrArray array, RepositorySafeHandle repo); + internal static extern unsafe int git_tag_list(out GitStrArray array, git_repository* repo); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] @@ -1763,7 +1763,7 @@ internal static extern unsafe int git_tree_entry_bypath( internal static extern UIntPtr git_tree_entrycount(GitObjectSafeHandle tree); [DllImport(libgit2)] - internal static extern int git_treebuilder_new(out TreeBuilderSafeHandle builder, RepositorySafeHandle repo, IntPtr src); + internal static extern unsafe int git_treebuilder_new(out TreeBuilderSafeHandle builder, git_repository* repo, IntPtr src); [DllImport(libgit2)] internal static extern int git_treebuilder_insert( @@ -1783,7 +1783,7 @@ internal static extern int git_treebuilder_insert( internal static extern int git_blob_is_binary(GitObjectSafeHandle blob); [DllImport(libgit2)] - internal static extern int git_cherrypick(RepositorySafeHandle repo, GitObjectSafeHandle commit, GitCherryPickOptions options); + internal static extern unsafe int git_cherrypick(git_repository* repo, GitObjectSafeHandle commit, GitCherryPickOptions options); } } // ReSharper restore InconsistentNaming diff --git a/LibGit2Sharp/Core/ObjectSafeWrapper.cs b/LibGit2Sharp/Core/ObjectSafeWrapper.cs index e7f610772..adbee7acc 100644 --- a/LibGit2Sharp/Core/ObjectSafeWrapper.cs +++ b/LibGit2Sharp/Core/ObjectSafeWrapper.cs @@ -7,7 +7,7 @@ internal class ObjectSafeWrapper : IDisposable { private readonly GitObjectSafeHandle objectPtr; - public ObjectSafeWrapper(ObjectId id, RepositorySafeHandle handle, bool allowNullObjectId = false) + public ObjectSafeWrapper(ObjectId id, RepositoryHandle handle, bool allowNullObjectId = false) { Ensure.ArgumentNotNull(handle, "handle"); diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index a1293ed24..8db63dccc 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -5,5 +5,6 @@ namespace LibGit2Sharp.Core internal struct git_tree_entry {} internal struct git_reference { } internal struct git_refspec {} + internal struct git_repository {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index b4c38178b..f6d908c5e 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -95,8 +95,8 @@ private static void BuildErrorMessageFromException(StringBuilder sb, int level, #region git_blame_ - public static BlameSafeHandle git_blame_file( - RepositorySafeHandle repo, + public static unsafe BlameSafeHandle git_blame_file( + RepositoryHandle repo, FilePath path, GitBlameOptions options) { @@ -120,7 +120,7 @@ public static void git_blame_free(IntPtr blame) #region git_blob_ - public static ObjectId git_blob_create_fromchunks(RepositorySafeHandle repo, FilePath hintpath, NativeMethods.source_callback fileCallback) + public static unsafe ObjectId git_blob_create_fromchunks(RepositoryHandle repo, FilePath hintpath, NativeMethods.source_callback fileCallback) { var oid = new GitOid(); int res = NativeMethods.git_blob_create_fromchunks(ref oid, repo, hintpath, fileCallback, IntPtr.Zero); @@ -135,7 +135,7 @@ public static ObjectId git_blob_create_fromchunks(RepositorySafeHandle repo, Fil return oid; } - public static ObjectId git_blob_create_fromdisk(RepositorySafeHandle repo, FilePath path) + public static unsafe ObjectId git_blob_create_fromdisk(RepositoryHandle repo, FilePath path) { var oid = new GitOid(); int res = NativeMethods.git_blob_create_fromdisk(ref oid, repo, path); @@ -144,7 +144,7 @@ public static ObjectId git_blob_create_fromdisk(RepositorySafeHandle repo, FileP return oid; } - public static ObjectId git_blob_create_fromfile(RepositorySafeHandle repo, FilePath path) + public static unsafe ObjectId git_blob_create_fromfile(RepositoryHandle repo, FilePath path) { var oid = new GitOid(); int res = NativeMethods.git_blob_create_fromworkdir(ref oid, repo, path); @@ -153,7 +153,7 @@ public static ObjectId git_blob_create_fromfile(RepositorySafeHandle repo, FileP return oid; } - public static UnmanagedMemoryStream git_blob_filtered_content_stream(RepositorySafeHandle repo, ObjectId id, FilePath path, bool check_for_binary_data) + public static UnmanagedMemoryStream git_blob_filtered_content_stream(RepositoryHandle repo, ObjectId id, FilePath path, bool check_for_binary_data) { var buf = new GitBuf(); var handle = new ObjectSafeWrapper(id, repo).ObjectPtr; @@ -167,7 +167,7 @@ public static UnmanagedMemoryStream git_blob_filtered_content_stream(RepositoryS new[] { buf }); } - public static UnmanagedMemoryStream git_blob_rawcontent_stream(RepositorySafeHandle repo, ObjectId id, Int64 size) + public static UnmanagedMemoryStream git_blob_rawcontent_stream(RepositoryHandle repo, ObjectId id, Int64 size) { var handle = new ObjectSafeWrapper(id, repo).ObjectPtr; return new RawContentStream(handle, NativeMethods.git_blob_rawcontent, h => size); @@ -190,7 +190,7 @@ public static bool git_blob_is_binary(GitObjectSafeHandle obj) #region git_branch_ - public static unsafe ReferenceHandle git_branch_create_from_annotated(RepositorySafeHandle repo, string branch_name, string targetIdentifier, bool force) + public static unsafe ReferenceHandle git_branch_create_from_annotated(RepositoryHandle repo, string branch_name, string targetIdentifier, bool force) { git_reference* reference; @@ -212,7 +212,7 @@ public static unsafe void git_branch_delete(ReferenceHandle reference) public static IEnumerable git_branch_iterator(Repository repo, GitBranchType branchType) { IntPtr iter; - var res = NativeMethods.git_branch_iterator_new(out iter, repo.Handle, branchType); + var res = NativeMethods.git_branch_iterator_new(out iter, repo.Handle.AsIntPtr(), branchType); Ensure.ZeroResult(res); try @@ -255,7 +255,7 @@ public static unsafe ReferenceHandle git_branch_move(ReferenceHandle reference, return new ReferenceHandle(ref_out, true); } - public static string git_branch_remote_name(RepositorySafeHandle repo, string canonical_branch_name, bool shouldThrowIfNotFound) + public static unsafe string git_branch_remote_name(RepositoryHandle repo, string canonical_branch_name, bool shouldThrowIfNotFound) { using (var buf = new GitBuf()) { @@ -272,7 +272,7 @@ public static string git_branch_remote_name(RepositorySafeHandle repo, string ca } } - public static string git_branch_upstream_name(RepositorySafeHandle handle, string canonicalReferenceName) + public static unsafe string git_branch_upstream_name(RepositoryHandle handle, string canonicalReferenceName) { using (var buf = new GitBuf()) { @@ -300,8 +300,8 @@ public static void git_buf_free(GitBuf buf) #region git_checkout_ - public static void git_checkout_tree( - RepositorySafeHandle repo, + public static unsafe void git_checkout_tree( + RepositoryHandle repo, ObjectId treeId, ref GitCheckoutOpts opts) { @@ -312,7 +312,7 @@ public static void git_checkout_tree( } } - public static void git_checkout_index(RepositorySafeHandle repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts) + public static unsafe void git_checkout_index(RepositoryHandle repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts) { int res = NativeMethods.git_checkout_index(repo, treeish, ref opts); Ensure.ZeroResult(res); @@ -322,7 +322,7 @@ public static void git_checkout_index(RepositorySafeHandle repo, GitObjectSafeHa #region git_cherry_pick_ - internal static void git_cherrypick(RepositorySafeHandle repo, ObjectId commit, GitCherryPickOptions options) + internal static unsafe void git_cherrypick(RepositoryHandle repo, ObjectId commit, GitCherryPickOptions options) { using (var nativeCommit = git_object_lookup(repo, commit, GitObjectType.Commit)) { @@ -334,15 +334,15 @@ internal static void git_cherrypick(RepositorySafeHandle repo, ObjectId commit, #region git_clone_ - public static RepositorySafeHandle git_clone( + public static unsafe RepositoryHandle git_clone( string url, string workdir, ref GitCloneOptions opts) { - RepositorySafeHandle repo; + git_repository *repo; int res = NativeMethods.git_clone(out repo, url, workdir, ref opts); Ensure.ZeroResult(res); - return repo; + return new RepositoryHandle(repo, true); } #endregion @@ -359,8 +359,8 @@ public static Signature git_commit_committer(GitObjectSafeHandle obj) return new Signature(NativeMethods.git_commit_committer(obj)); } - public static ObjectId git_commit_create( - RepositorySafeHandle repo, + public static unsafe ObjectId git_commit_create( + RepositoryHandle repo, string referenceName, Signature author, Signature committer, @@ -413,7 +413,7 @@ public static unsafe ObjectId git_commit_parent_id(GitObjectSafeHandle obj, uint return ObjectId.BuildFromPtr(NativeMethods.git_commit_parent_id(obj, i)); } - public static int git_commit_parentcount(RepositorySafeHandle repo, ObjectId id) + public static int git_commit_parentcount(RepositoryHandle repo, ObjectId id) { using (var obj = new ObjectSafeWrapper(id, repo)) { @@ -641,7 +641,7 @@ public static ConfigurationSafeHandle git_config_snapshot(ConfigurationSafeHandl #region git_describe_ public static string git_describe_commit( - RepositorySafeHandle repo, + RepositoryHandle repo, ObjectId committishId, DescribeOptions options) { @@ -701,7 +701,7 @@ public static void git_describe_free(IntPtr iter) #region git_diff_ public static void git_diff_blobs( - RepositorySafeHandle repo, + RepositoryHandle repo, ObjectId oldBlob, ObjectId newBlob, GitDiffOptions options, @@ -737,8 +737,8 @@ public static void git_diff_foreach( Ensure.ZeroResult(res); } - public static DiffSafeHandle git_diff_tree_to_index( - RepositorySafeHandle repo, + public static unsafe DiffSafeHandle git_diff_tree_to_index( + RepositoryHandle repo, IndexSafeHandle index, ObjectId oldTree, GitDiffOptions options) @@ -764,8 +764,8 @@ public static void git_diff_merge(DiffSafeHandle onto, DiffSafeHandle from) Ensure.ZeroResult(res); } - public static DiffSafeHandle git_diff_tree_to_tree( - RepositorySafeHandle repo, + public static unsafe DiffSafeHandle git_diff_tree_to_tree( + RepositoryHandle repo, ObjectId oldTree, ObjectId newTree, GitDiffOptions options) @@ -781,8 +781,8 @@ public static DiffSafeHandle git_diff_tree_to_tree( } } - public static DiffSafeHandle git_diff_index_to_workdir( - RepositorySafeHandle repo, + public static unsafe DiffSafeHandle git_diff_index_to_workdir( + RepositoryHandle repo, IndexSafeHandle index, GitDiffOptions options) { @@ -793,8 +793,8 @@ public static DiffSafeHandle git_diff_index_to_workdir( return diff; } - public static DiffSafeHandle git_diff_tree_to_workdir( - RepositorySafeHandle repo, + public static unsafe DiffSafeHandle git_diff_tree_to_workdir( + RepositoryHandle repo, ObjectId oldTree, GitDiffOptions options) { @@ -854,7 +854,7 @@ public static FilterMode git_filter_source_mode(IntPtr filterSource) #region git_graph_ - public static Tuple git_graph_ahead_behind(RepositorySafeHandle repo, Commit first, Commit second) + public static unsafe Tuple git_graph_ahead_behind(RepositoryHandle repo, Commit first, Commit second) { if (first == null || second == null) { @@ -874,7 +874,7 @@ public static FilterMode git_filter_source_mode(IntPtr filterSource) return new Tuple((int)ahead, (int)behind); } - public static bool git_graph_descendant_of(RepositorySafeHandle repo, ObjectId commitId, ObjectId ancestorId) + public static unsafe bool git_graph_descendant_of(RepositoryHandle repo, ObjectId commitId, ObjectId ancestorId) { GitOid oid1 = commitId.Oid; GitOid oid2 = ancestorId.Oid; @@ -889,19 +889,19 @@ public static bool git_graph_descendant_of(RepositorySafeHandle repo, ObjectId c #region git_ignore_ - public static void git_ignore_add_rule(RepositorySafeHandle repo, string rules) + public static unsafe void git_ignore_add_rule(RepositoryHandle repo, string rules) { int res = NativeMethods.git_ignore_add_rule(repo, rules); Ensure.ZeroResult(res); } - public static void git_ignore_clear_internal_rules(RepositorySafeHandle repo) + public static unsafe void git_ignore_clear_internal_rules(RepositoryHandle repo) { int res = NativeMethods.git_ignore_clear_internal_rules(repo); Ensure.ZeroResult(res); } - public static bool git_ignore_path_is_ignored(RepositorySafeHandle repo, string path) + public static unsafe bool git_ignore_path_is_ignored(RepositoryHandle repo, string path) { int ignored; int res = NativeMethods.git_ignore_path_is_ignored(out ignored, repo, path); @@ -1079,7 +1079,7 @@ public static ObjectId git_index_write_tree(IndexSafeHandle index) return treeOid; } - public static ObjectId git_index_write_tree_to(IndexSafeHandle index, RepositorySafeHandle repo) + public static unsafe ObjectId git_index_write_tree_to(IndexSafeHandle index, RepositoryHandle repo) { GitOid treeOid; int res = NativeMethods.git_index_write_tree_to(out treeOid, index, repo); @@ -1104,7 +1104,7 @@ public static void git_index_clear(Index index) #region git_merge_ - public static IndexSafeHandle git_merge_commits(RepositorySafeHandle repo, GitObjectSafeHandle ourCommit, GitObjectSafeHandle theirCommit, GitMergeOpts opts) + public static unsafe IndexSafeHandle git_merge_commits(RepositoryHandle repo, GitObjectSafeHandle ourCommit, GitObjectSafeHandle theirCommit, GitMergeOpts opts) { IndexSafeHandle index; int res = NativeMethods.git_merge_commits(out index, repo, ourCommit, theirCommit, ref opts); @@ -1113,7 +1113,7 @@ public static IndexSafeHandle git_merge_commits(RepositorySafeHandle repo, GitOb return index; } - public static ObjectId git_merge_base_many(RepositorySafeHandle repo, GitOid[] commitIds) + public static unsafe ObjectId git_merge_base_many(RepositoryHandle repo, GitOid[] commitIds) { GitOid ret; int res = NativeMethods.git_merge_base_many(out ret, repo, commitIds.Length, commitIds); @@ -1128,7 +1128,7 @@ public static ObjectId git_merge_base_many(RepositorySafeHandle repo, GitOid[] c return ret; } - public static ObjectId git_merge_base_octopus(RepositorySafeHandle repo, GitOid[] commitIds) + public static unsafe ObjectId git_merge_base_octopus(RepositoryHandle repo, GitOid[] commitIds) { GitOid ret; int res = NativeMethods.git_merge_base_octopus(out ret, repo, commitIds.Length, commitIds); @@ -1143,7 +1143,7 @@ public static ObjectId git_merge_base_octopus(RepositorySafeHandle repo, GitOid[ return ret; } - public static GitAnnotatedCommitHandle git_annotated_commit_from_fetchhead(RepositorySafeHandle repo, string branchName, string remoteUrl, GitOid oid) + public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_fetchhead(RepositoryHandle repo, string branchName, string remoteUrl, GitOid oid) { GitAnnotatedCommitHandle merge_head; @@ -1154,7 +1154,7 @@ public static GitAnnotatedCommitHandle git_annotated_commit_from_fetchhead(Repos return merge_head; } - public static GitAnnotatedCommitHandle git_annotated_commit_lookup(RepositorySafeHandle repo, GitOid oid) + public static unsafe GitAnnotatedCommitHandle git_annotated_commit_lookup(RepositoryHandle repo, GitOid oid) { GitAnnotatedCommitHandle their_head; @@ -1165,7 +1165,7 @@ public static GitAnnotatedCommitHandle git_annotated_commit_lookup(RepositorySaf return their_head; } - public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositorySafeHandle repo, ReferenceHandle reference) + public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositoryHandle repo, ReferenceHandle reference) { GitAnnotatedCommitHandle their_head; @@ -1176,7 +1176,7 @@ public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_ref(Repo return their_head; } - public static GitAnnotatedCommitHandle git_annotated_commit_from_revspec(RepositorySafeHandle repo, string revspec) + public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_revspec(RepositoryHandle repo, string revspec) { GitAnnotatedCommitHandle their_head; @@ -1192,7 +1192,7 @@ public static unsafe ObjectId git_annotated_commit_id(GitAnnotatedCommitHandle m return ObjectId.BuildFromPtr(NativeMethods.git_annotated_commit_id(mergeHead)); } - public static void git_merge(RepositorySafeHandle repo, GitAnnotatedCommitHandle[] heads, GitMergeOpts mergeOptions, GitCheckoutOpts checkoutOptions) + public static unsafe void git_merge(RepositoryHandle repo, GitAnnotatedCommitHandle[] heads, GitMergeOpts mergeOptions, GitCheckoutOpts checkoutOptions) { IntPtr[] their_heads = heads.Select(head => head.DangerousGetHandle()).ToArray(); @@ -1205,8 +1205,8 @@ public static void git_merge(RepositorySafeHandle repo, GitAnnotatedCommitHandle Ensure.ZeroResult(res); } - public static void git_merge_analysis( - RepositorySafeHandle repo, + public static unsafe void git_merge_analysis( + RepositoryHandle repo, GitAnnotatedCommitHandle[] heads, out GitMergeAnalysis analysis_out, out GitMergePreference preference_out) @@ -1257,8 +1257,8 @@ public static string git_message_prettify(string message, char? commentChar) #region git_note_ - public static ObjectId git_note_create( - RepositorySafeHandle repo, + public static unsafe ObjectId git_note_create( + RepositoryHandle repo, string notes_ref, Signature author, Signature committer, @@ -1279,7 +1279,7 @@ public static ObjectId git_note_create( } } - public static string git_note_default_ref(RepositorySafeHandle repo) + public static unsafe string git_note_default_ref(RepositoryHandle repo) { using (var buf = new GitBuf()) { @@ -1290,7 +1290,7 @@ public static string git_note_default_ref(RepositorySafeHandle repo) } } - public static ICollection git_note_foreach(RepositorySafeHandle repo, string notes_ref, Func resultSelector) + public static unsafe ICollection git_note_foreach(RepositoryHandle repo, string notes_ref, Func resultSelector) { return git_foreach(resultSelector, c => NativeMethods.git_note_foreach(repo, notes_ref, @@ -1313,7 +1313,7 @@ public static unsafe ObjectId git_note_id(NoteSafeHandle note) return ObjectId.BuildFromPtr(NativeMethods.git_note_id(note)); } - public static NoteSafeHandle git_note_read(RepositorySafeHandle repo, string notes_ref, ObjectId id) + public static unsafe NoteSafeHandle git_note_read(RepositoryHandle repo, string notes_ref, ObjectId id) { GitOid oid = id.Oid; NoteSafeHandle note; @@ -1330,7 +1330,7 @@ public static NoteSafeHandle git_note_read(RepositorySafeHandle repo, string not return note; } - public static void git_note_remove(RepositorySafeHandle repo, string notes_ref, Signature author, Signature committer, ObjectId targetId) + public static unsafe void git_note_remove(RepositoryHandle repo, string notes_ref, Signature author, Signature committer, ObjectId targetId) { using (SignatureSafeHandle authorHandle = author.BuildHandle()) using (SignatureSafeHandle committerHandle = committer.BuildHandle()) @@ -1362,7 +1362,7 @@ public static void git_object_free(IntPtr obj) NativeMethods.git_object_free(obj); } - public static GitObjectSafeHandle git_object_lookup(RepositorySafeHandle repo, ObjectId id, GitObjectType type) + public static unsafe GitObjectSafeHandle git_object_lookup(RepositoryHandle repo, ObjectId id, GitObjectType type) { GitObjectSafeHandle handle; GitOid oid = id.Oid; @@ -1381,7 +1381,7 @@ public static GitObjectSafeHandle git_object_lookup(RepositorySafeHandle repo, O return handle; } - public static GitObjectSafeHandle git_object_peel(RepositorySafeHandle repo, ObjectId id, GitObjectType type, bool throwsIfCanNotPeel) + public static GitObjectSafeHandle git_object_peel(RepositoryHandle repo, ObjectId id, GitObjectType type, bool throwsIfCanNotPeel) { GitObjectSafeHandle peeled; int res; @@ -1402,7 +1402,7 @@ public static GitObjectSafeHandle git_object_peel(RepositorySafeHandle repo, Obj return peeled; } - public static string git_object_short_id(RepositorySafeHandle repo, ObjectId id) + public static string git_object_short_id(RepositoryHandle repo, ObjectId id) { using (var obj = new ObjectSafeWrapper(id, repo)) using (var buf = new GitBuf()) @@ -1557,7 +1557,7 @@ public static void git_packbuilder_free(IntPtr packbuilder) NativeMethods.git_packbuilder_free(packbuilder); } - public static PackBuilderSafeHandle git_packbuilder_new(RepositorySafeHandle repo) + public static unsafe PackBuilderSafeHandle git_packbuilder_new(RepositoryHandle repo) { PackBuilderSafeHandle handle; @@ -1623,8 +1623,8 @@ public static uint git_packbuilder_written(PackBuilderSafeHandle packbuilder) #region git_rebase - public static RebaseSafeHandle git_rebase_init( - RepositorySafeHandle repo, + public static unsafe RebaseSafeHandle git_rebase_init( + RepositoryHandle repo, GitAnnotatedCommitHandle branch, GitAnnotatedCommitHandle upstream, GitAnnotatedCommitHandle onto, @@ -1638,7 +1638,7 @@ public static RebaseSafeHandle git_rebase_init( return rebase; } - public static RebaseSafeHandle git_rebase_open(RepositorySafeHandle repo, GitRebaseOptions options) + public static unsafe RebaseSafeHandle git_rebase_open(RepositoryHandle repo, GitRebaseOptions options) { RebaseSafeHandle rebase = null; @@ -1792,7 +1792,7 @@ public static void git_rebase_free(IntPtr rebase) #region git_reference_ public static unsafe ReferenceHandle git_reference_create( - RepositorySafeHandle repo, + RepositoryHandle repo, string name, ObjectId targetId, bool allowOverwrite, @@ -1808,7 +1808,7 @@ public static unsafe ReferenceHandle git_reference_create( } public static unsafe ReferenceHandle git_reference_symbolic_create( - RepositorySafeHandle repo, + RepositoryHandle repo, string name, string target, bool allowOverwrite, @@ -1822,8 +1822,8 @@ public static unsafe ReferenceHandle git_reference_symbolic_create( return new ReferenceHandle(handle, true); } - public static ICollection git_reference_foreach_glob( - RepositorySafeHandle repo, + public static unsafe ICollection git_reference_foreach_glob( + RepositoryHandle repo, string glob, Func resultSelector) { @@ -1838,7 +1838,7 @@ public static bool git_reference_is_valid_name(string refname) return (res == 1); } - public static IList git_reference_list(RepositorySafeHandle repo) + public static unsafe IList git_reference_list(RepositoryHandle repo) { var array = new GitStrArrayNative(); @@ -1855,7 +1855,7 @@ public static IList git_reference_list(RepositorySafeHandle repo) } } - public static unsafe ReferenceHandle git_reference_lookup(RepositorySafeHandle repo, string name, bool shouldThrowIfNotFound) + public static unsafe ReferenceHandle git_reference_lookup(RepositoryHandle repo, string name, bool shouldThrowIfNotFound) { git_reference* handle; int res = NativeMethods.git_reference_lookup(out handle, repo, name); @@ -1875,7 +1875,7 @@ public static unsafe string git_reference_name(git_reference* reference) return NativeMethods.git_reference_name(reference); } - public static void git_reference_remove(RepositorySafeHandle repo, string name) + public static unsafe void git_reference_remove(RepositoryHandle repo, string name) { int res = NativeMethods.git_reference_remove(repo, name); Ensure.ZeroResult(res); @@ -1931,7 +1931,7 @@ public static unsafe GitReferenceType git_reference_type(git_reference* referenc return NativeMethods.git_reference_type(reference); } - public static void git_reference_ensure_log(RepositorySafeHandle repo, string refname) + public static unsafe void git_reference_ensure_log(RepositoryHandle repo, string refname) { int res = NativeMethods.git_reference_ensure_log(repo, refname); Ensure.ZeroResult(res); @@ -1946,7 +1946,7 @@ public static void git_reflog_free(IntPtr reflog) NativeMethods.git_reflog_free(reflog); } - public static ReflogSafeHandle git_reflog_read(RepositorySafeHandle repo, string canonicalName) + public static unsafe ReflogSafeHandle git_reflog_read(RepositoryHandle repo, string canonicalName) { ReflogSafeHandle reflog_out; @@ -2035,7 +2035,7 @@ public static TagFetchMode git_remote_autotag(RemoteSafeHandle remote) return (TagFetchMode)NativeMethods.git_remote_autotag(remote); } - public static RemoteSafeHandle git_remote_create(RepositorySafeHandle repo, string name, string url) + public static unsafe RemoteSafeHandle git_remote_create(RepositoryHandle repo, string name, string url) { RemoteSafeHandle handle; int res = NativeMethods.git_remote_create(out handle, repo, name, url); @@ -2044,7 +2044,7 @@ public static RemoteSafeHandle git_remote_create(RepositorySafeHandle repo, stri return handle; } - public static RemoteSafeHandle git_remote_create_with_fetchspec(RepositorySafeHandle repo, string name, string url, string refspec) + public static unsafe RemoteSafeHandle git_remote_create_with_fetchspec(RepositoryHandle repo, string name, string url, string refspec) { RemoteSafeHandle handle; int res = NativeMethods.git_remote_create_with_fetchspec(out handle, repo, name, url, refspec); @@ -2053,7 +2053,7 @@ public static RemoteSafeHandle git_remote_create_with_fetchspec(RepositorySafeHa return handle; } - public static RemoteSafeHandle git_remote_create_anonymous(RepositorySafeHandle repo, string url) + public static unsafe RemoteSafeHandle git_remote_create_anonymous(RepositoryHandle repo, string url) { RemoteSafeHandle handle; int res = NativeMethods.git_remote_create_anonymous(out handle, repo, url); @@ -2077,7 +2077,7 @@ public static void git_remote_connect(RemoteSafeHandle remote, GitDirection dire } } - public static void git_remote_delete(RepositorySafeHandle repo, string name) + public static unsafe void git_remote_delete(RepositoryHandle repo, string name) { int res = NativeMethods.git_remote_delete(repo, name); @@ -2150,25 +2150,25 @@ public static void git_remote_push(RemoteSafeHandle remote, IEnumerable } } - public static void git_remote_set_url(RepositorySafeHandle repo, string remote, string url) + public static unsafe void git_remote_set_url(RepositoryHandle repo, string remote, string url) { int res = NativeMethods.git_remote_set_url(repo, remote, url); Ensure.ZeroResult(res); } - public static void git_remote_add_fetch(RepositorySafeHandle repo, string remote, string url) + public static unsafe void git_remote_add_fetch(RepositoryHandle repo, string remote, string url) { int res = NativeMethods.git_remote_add_fetch(repo, remote, url); Ensure.ZeroResult(res); } - public static void git_remote_set_pushurl(RepositorySafeHandle repo, string remote, string url) + public static unsafe void git_remote_set_pushurl(RepositoryHandle repo, string remote, string url) { int res = NativeMethods.git_remote_set_pushurl(repo, remote, url); Ensure.ZeroResult(res); } - public static void git_remote_add_push(RepositorySafeHandle repo, string remote, string url) + public static unsafe void git_remote_add_push(RepositoryHandle repo, string remote, string url) { int res = NativeMethods.git_remote_add_push(repo, remote, url); Ensure.ZeroResult(res); @@ -2206,7 +2206,7 @@ public static bool git_remote_is_valid_name(string refname) return (res == 1); } - public static IList git_remote_list(RepositorySafeHandle repo) + public static unsafe IList git_remote_list(RepositoryHandle repo) { var array = new GitStrArrayNative(); @@ -2276,7 +2276,7 @@ public static unsafe IEnumerable git_remote_ls(Repository repository, return refs; } - public static RemoteSafeHandle git_remote_lookup(RepositorySafeHandle repo, string name, bool throwsIfNotFound) + public static unsafe RemoteSafeHandle git_remote_lookup(RepositoryHandle repo, string name, bool throwsIfNotFound) { RemoteSafeHandle handle; int res = NativeMethods.git_remote_lookup(out handle, repo, name); @@ -2295,7 +2295,7 @@ public static string git_remote_name(RemoteSafeHandle remote) return NativeMethods.git_remote_name(remote); } - public static void git_remote_rename(RepositorySafeHandle repo, string name, string new_name, RemoteRenameFailureHandler callback) + public static unsafe void git_remote_rename(RepositoryHandle repo, string name, string new_name, RemoteRenameFailureHandler callback) { if (callback == null) { @@ -2329,7 +2329,7 @@ public static void git_remote_rename(RepositorySafeHandle repo, string name, str } } - public static void git_remote_set_autotag(RepositorySafeHandle repo, string remote, TagFetchMode value) + public static unsafe void git_remote_set_autotag(RepositoryHandle repo, string remote, TagFetchMode value) { NativeMethods.git_remote_set_autotag(repo, remote, value); } @@ -2353,13 +2353,13 @@ public static FilePath git_repository_discover(FilePath start_path) return ConvertPath(buf => NativeMethods.git_repository_discover(buf, start_path, false, null)); } - public static bool git_repository_head_detached(RepositorySafeHandle repo) + public static unsafe bool git_repository_head_detached(RepositoryHandle repo) { return RepositoryStateChecker(repo, NativeMethods.git_repository_head_detached); } - public static ICollection git_repository_fetchhead_foreach( - RepositorySafeHandle repo, + public static unsafe ICollection git_repository_fetchhead_foreach( + RepositoryHandle repo, Func resultSelector) { return git_foreach(resultSelector, @@ -2370,17 +2370,12 @@ public static ICollection git_repository_fetchhead_foreach( GitErrorCode.NotFound); } - public static void git_repository_free(IntPtr repo) - { - NativeMethods.git_repository_free(repo); - } - - public static bool git_repository_head_unborn(RepositorySafeHandle repo) + public static bool git_repository_head_unborn(RepositoryHandle repo) { return RepositoryStateChecker(repo, NativeMethods.git_repository_head_unborn); } - public static IndexSafeHandle git_repository_index(RepositorySafeHandle repo) + public static unsafe IndexSafeHandle git_repository_index(RepositoryHandle repo) { IndexSafeHandle handle; int res = NativeMethods.git_repository_index(out handle, repo); @@ -2389,39 +2384,39 @@ public static IndexSafeHandle git_repository_index(RepositorySafeHandle repo) return handle; } - public static RepositorySafeHandle git_repository_init_ext( + public static unsafe RepositoryHandle git_repository_init_ext( FilePath workdirPath, FilePath gitdirPath, bool isBare) { using (var opts = GitRepositoryInitOptions.BuildFrom(workdirPath, isBare)) { - RepositorySafeHandle repo; + git_repository* repo; int res = NativeMethods.git_repository_init_ext(out repo, gitdirPath, opts); Ensure.ZeroResult(res); - return repo; + return new RepositoryHandle(repo, true); } } - public static bool git_repository_is_bare(RepositorySafeHandle repo) + public static unsafe bool git_repository_is_bare(RepositoryHandle repo) { return RepositoryStateChecker(repo, NativeMethods.git_repository_is_bare); } - public static bool git_repository_is_shallow(RepositorySafeHandle repo) + public static unsafe bool git_repository_is_shallow(RepositoryHandle repo) { return RepositoryStateChecker(repo, NativeMethods.git_repository_is_shallow); } - public static void git_repository_state_cleanup(RepositorySafeHandle repo) + public static unsafe void git_repository_state_cleanup(RepositoryHandle repo) { int res = NativeMethods.git_repository_state_cleanup(repo); Ensure.ZeroResult(res); } - public static ICollection git_repository_mergehead_foreach( - RepositorySafeHandle repo, + public static unsafe ICollection git_repository_mergehead_foreach( + RepositoryHandle repo, Func resultSelector) { return git_foreach(resultSelector, @@ -2430,7 +2425,7 @@ public static ICollection git_repository_mergehead_foreach( GitErrorCode.NotFound); } - public static string git_repository_message(RepositorySafeHandle repo) + public static unsafe string git_repository_message(RepositoryHandle repo) { using (var buf = new GitBuf()) { @@ -2445,7 +2440,7 @@ public static string git_repository_message(RepositorySafeHandle repo) } } - public static ObjectDatabaseSafeHandle git_repository_odb(RepositorySafeHandle repo) + public static unsafe ObjectDatabaseSafeHandle git_repository_odb(RepositoryHandle repo) { ObjectDatabaseSafeHandle handle; int res = NativeMethods.git_repository_odb(out handle, repo); @@ -2454,9 +2449,9 @@ public static ObjectDatabaseSafeHandle git_repository_odb(RepositorySafeHandle r return handle; } - public static RepositorySafeHandle git_repository_open(string path) + public static unsafe RepositoryHandle git_repository_open(string path) { - RepositorySafeHandle repo; + git_repository* repo; int res = NativeMethods.git_repository_open(out repo, path); if (res == (int)GitErrorCode.NotFound) @@ -2467,27 +2462,26 @@ public static RepositorySafeHandle git_repository_open(string path) Ensure.ZeroResult(res); - return repo; + return new RepositoryHandle(repo, true); } - public static RepositorySafeHandle git_repository_new() + public static unsafe RepositoryHandle git_repository_new() { - RepositorySafeHandle repo; + git_repository* repo; int res = NativeMethods.git_repository_new(out repo); Ensure.ZeroResult(res); - return repo; + return new RepositoryHandle(repo, true); } - public static void git_repository_open_ext(string path, RepositoryOpenFlags flags, string ceilingDirs) + public static unsafe void git_repository_open_ext(string path, RepositoryOpenFlags flags, string ceilingDirs) { int res; + git_repository *repo; - using (var repo = new NullRepositorySafeHandle()) - { - res = NativeMethods.git_repository_open_ext(repo, path, flags, ceilingDirs); - } + res = NativeMethods.git_repository_open_ext(out repo, path, flags, ceilingDirs); + NativeMethods.git_repository_free(repo); if (res == (int)GitErrorCode.NotFound) { @@ -2498,41 +2492,41 @@ public static void git_repository_open_ext(string path, RepositoryOpenFlags flag Ensure.ZeroResult(res); } - public static FilePath git_repository_path(RepositorySafeHandle repo) + public static unsafe FilePath git_repository_path(RepositoryHandle repo) { return NativeMethods.git_repository_path(repo); } - public static void git_repository_set_config(RepositorySafeHandle repo, ConfigurationSafeHandle config) + public static unsafe void git_repository_set_config(RepositoryHandle repo, ConfigurationSafeHandle config) { NativeMethods.git_repository_set_config(repo, config); } - public static void git_repository_set_ident(RepositorySafeHandle repo, string name, string email) + public static unsafe void git_repository_set_ident(RepositoryHandle repo, string name, string email) { int res = NativeMethods.git_repository_set_ident(repo, name, email); Ensure.ZeroResult(res); } - public static void git_repository_set_index(RepositorySafeHandle repo, IndexSafeHandle index) + public static unsafe void git_repository_set_index(RepositoryHandle repo, IndexSafeHandle index) { NativeMethods.git_repository_set_index(repo, index); } - public static void git_repository_set_workdir(RepositorySafeHandle repo, FilePath workdir) + public static unsafe void git_repository_set_workdir(RepositoryHandle repo, FilePath workdir) { int res = NativeMethods.git_repository_set_workdir(repo, workdir, false); Ensure.ZeroResult(res); } - public static CurrentOperation git_repository_state(RepositorySafeHandle repo) + public static unsafe CurrentOperation git_repository_state(RepositoryHandle repo) { int res = NativeMethods.git_repository_state(repo); Ensure.Int32Result(res); return (CurrentOperation)res; } - public static FilePath git_repository_workdir(RepositorySafeHandle repo) + public static unsafe FilePath git_repository_workdir(RepositoryHandle repo) { return NativeMethods.git_repository_workdir(repo); } @@ -2542,20 +2536,20 @@ public static FilePath git_repository_workdir(IntPtr repo) return NativeMethods.git_repository_workdir(repo); } - public static void git_repository_set_head_detached(RepositorySafeHandle repo, ObjectId commitish) + public static unsafe void git_repository_set_head_detached(RepositoryHandle repo, ObjectId commitish) { GitOid oid = commitish.Oid; int res = NativeMethods.git_repository_set_head_detached(repo, ref oid); Ensure.ZeroResult(res); } - public static void git_repository_set_head_detached_from_annotated(RepositorySafeHandle repo, GitAnnotatedCommitHandle commit) + public static unsafe void git_repository_set_head_detached_from_annotated(RepositoryHandle repo, GitAnnotatedCommitHandle commit) { int res = NativeMethods.git_repository_set_head_detached_from_annotated(repo, commit); Ensure.ZeroResult(res); } - public static void git_repository_set_head(RepositorySafeHandle repo, string refname) + public static unsafe void git_repository_set_head(RepositoryHandle repo, string refname) { int res = NativeMethods.git_repository_set_head(repo, refname); Ensure.ZeroResult(res); @@ -2565,8 +2559,8 @@ public static void git_repository_set_head(RepositorySafeHandle repo, string ref #region git_reset_ - public static void git_reset( - RepositorySafeHandle repo, + public static unsafe void git_reset( + RepositoryHandle repo, ObjectId committishId, ResetMode resetKind, ref GitCheckoutOpts checkoutOptions) @@ -2582,8 +2576,8 @@ public static void git_reset( #region git_revert_ - public static void git_revert( - RepositorySafeHandle repo, + public static unsafe void git_revert( + RepositoryHandle repo, ObjectId commit, GitRevertOpts opts) { @@ -2598,7 +2592,7 @@ public static void git_revert( #region git_revparse_ - public static unsafe Tuple git_revparse_ext(RepositorySafeHandle repo, string objectish) + public static unsafe Tuple git_revparse_ext(RepositoryHandle repo, string objectish) { GitObjectSafeHandle obj; git_reference* reference; @@ -2621,7 +2615,7 @@ public static unsafe Tuple git_revparse_ex return new Tuple(obj, new ReferenceHandle(reference, true)); } - public static GitObjectSafeHandle git_revparse_single(RepositorySafeHandle repo, string objectish) + public static GitObjectSafeHandle git_revparse_single(RepositoryHandle repo, string objectish) { var handles = git_revparse_ext(repo, objectish); @@ -2651,7 +2645,7 @@ public static void git_revwalk_hide(RevWalkerSafeHandle walker, ObjectId commit_ Ensure.ZeroResult(res); } - public static RevWalkerSafeHandle git_revwalk_new(RepositorySafeHandle repo) + public static unsafe RevWalkerSafeHandle git_revwalk_new(RepositoryHandle repo) { RevWalkerSafeHandle handle; int res = NativeMethods.git_revwalk_new(out handle, repo); @@ -2738,8 +2732,8 @@ public static IntPtr git_signature_dup(IntPtr sig) #region git_stash_ - public static ObjectId git_stash_save( - RepositorySafeHandle repo, + public static unsafe ObjectId git_stash_save( + RepositoryHandle repo, Signature stasher, string prettifiedMessage, StashModifiers options) @@ -2761,8 +2755,8 @@ public static ObjectId git_stash_save( } } - public static ICollection git_stash_foreach( - RepositorySafeHandle repo, + public static unsafe ICollection git_stash_foreach( + RepositoryHandle repo, Func resultSelector) { return git_foreach(resultSelector, @@ -2773,7 +2767,7 @@ public static ICollection git_stash_foreach( GitErrorCode.NotFound); } - public static void git_stash_drop(RepositorySafeHandle repo, int index) + public static unsafe void git_stash_drop(RepositoryHandle repo, int index) { int res = NativeMethods.git_stash_drop(repo, (UIntPtr)index); Ensure.BooleanResult(res); @@ -2800,16 +2794,16 @@ private static StashApplyStatus get_stash_status(int res) return StashApplyStatus.Applied; } - public static StashApplyStatus git_stash_apply( - RepositorySafeHandle repo, + public static unsafe StashApplyStatus git_stash_apply( + RepositoryHandle repo, int index, GitStashApplyOpts opts) { return get_stash_status(NativeMethods.git_stash_apply(repo, (UIntPtr)index, opts)); } - public static StashApplyStatus git_stash_pop( - RepositorySafeHandle repo, + public static unsafe StashApplyStatus git_stash_pop( + RepositoryHandle repo, int index, GitStashApplyOpts opts) { @@ -2820,7 +2814,7 @@ public static StashApplyStatus git_stash_pop( #region git_status_ - public static FileStatus git_status_file(RepositorySafeHandle repo, FilePath path) + public static unsafe FileStatus git_status_file(RepositoryHandle repo, FilePath path) { FileStatus status; int res = NativeMethods.git_status_file(out status, repo, path); @@ -2844,7 +2838,7 @@ public static FileStatus git_status_file(RepositorySafeHandle repo, FilePath pat return status; } - public static StatusListSafeHandle git_status_list_new(RepositorySafeHandle repo, GitStatusOptions options) + public static unsafe StatusListSafeHandle git_status_list_new(RepositoryHandle repo, GitStatusOptions options) { StatusListSafeHandle handle; int res = NativeMethods.git_status_list_new(out handle, repo, options); @@ -2877,7 +2871,7 @@ public static void git_status_list_free(IntPtr statusList) /// Returns a handle to the corresponding submodule, /// or an invalid handle if a submodule is not found. /// - public static SubmoduleSafeHandle git_submodule_lookup(RepositorySafeHandle repo, FilePath name) + public static unsafe SubmoduleSafeHandle git_submodule_lookup(RepositoryHandle repo, FilePath name) { SubmoduleSafeHandle reference; var res = NativeMethods.git_submodule_lookup(out reference, repo, name); @@ -2895,7 +2889,7 @@ public static SubmoduleSafeHandle git_submodule_lookup(RepositorySafeHandle repo } } - public static string git_submodule_resolve_url(RepositorySafeHandle repo, string url) + public static unsafe string git_submodule_resolve_url(RepositoryHandle repo, string url) { using (var buf = new GitBuf()) { @@ -2906,7 +2900,7 @@ public static string git_submodule_resolve_url(RepositorySafeHandle repo, string } } - public static ICollection git_submodule_foreach(RepositorySafeHandle repo, Func resultSelector) + public static unsafe ICollection git_submodule_foreach(RepositoryHandle repo, Func resultSelector) { return git_foreach(resultSelector, c => NativeMethods.git_submodule_foreach(repo, (x, y, p) => c(x, y, p), IntPtr.Zero)); } @@ -2975,7 +2969,7 @@ public static void git_submodule_reload(SubmoduleSafeHandle submodule) Ensure.ZeroResult(res); } - public static SubmoduleStatus git_submodule_status(RepositorySafeHandle repo, string name) + public static unsafe SubmoduleStatus git_submodule_status(RepositoryHandle repo, string name) { SubmoduleStatus status; var res = NativeMethods.git_submodule_status(out status, repo, name, GitSubmoduleIgnore.Unspecified); @@ -2993,8 +2987,8 @@ public static void git_submodule_init(SubmoduleSafeHandle submodule, bool overwr #region git_tag_ - public static ObjectId git_tag_annotation_create( - RepositorySafeHandle repo, + public static unsafe ObjectId git_tag_annotation_create( + RepositoryHandle repo, string name, GitObject target, Signature tagger, @@ -3011,8 +3005,8 @@ public static ObjectId git_tag_annotation_create( } } - public static ObjectId git_tag_create( - RepositorySafeHandle repo, + public static unsafe ObjectId git_tag_create( + RepositoryHandle repo, string name, GitObject target, Signature tagger, @@ -3030,7 +3024,7 @@ public static ObjectId git_tag_create( } } - public static ObjectId git_tag_create_lightweight(RepositorySafeHandle repo, string name, GitObject target, bool allowOverwrite) + public static unsafe ObjectId git_tag_create_lightweight(RepositoryHandle repo, string name, GitObject target, bool allowOverwrite) { using (var objectPtr = new ObjectSafeWrapper(target.Id, repo)) { @@ -3042,13 +3036,13 @@ public static ObjectId git_tag_create_lightweight(RepositorySafeHandle repo, str } } - public static void git_tag_delete(RepositorySafeHandle repo, string name) + public static unsafe void git_tag_delete(RepositoryHandle repo, string name) { int res = NativeMethods.git_tag_delete(repo, name); Ensure.ZeroResult(res); } - public static IList git_tag_list(RepositorySafeHandle repo) + public static unsafe IList git_tag_list(RepositoryHandle repo) { var array = new GitStrArrayNative(); @@ -3171,7 +3165,7 @@ public static unsafe TreeEntryHandle git_tree_entry_byindex(GitObjectSafeHandle return new TreeEntryHandle(handle, false); } - public static unsafe TreeEntryHandle git_tree_entry_bypath(RepositorySafeHandle repo, ObjectId id, FilePath treeentry_path) + public static unsafe TreeEntryHandle git_tree_entry_bypath(RepositoryHandle repo, ObjectId id, FilePath treeentry_path) { using (var obj = new ObjectSafeWrapper(id, repo)) { @@ -3213,7 +3207,7 @@ public static int git_tree_entrycount(GitObjectSafeHandle tree) #region git_treebuilder_ - public static TreeBuilderSafeHandle git_treebuilder_new(RepositorySafeHandle repo) + public static unsafe TreeBuilderSafeHandle git_treebuilder_new(RepositoryHandle repo) { TreeBuilderSafeHandle builder; int res = NativeMethods.git_treebuilder_new(out builder, repo, IntPtr.Zero); @@ -3398,9 +3392,9 @@ private static ICollection git_foreach( return result; } - private static bool RepositoryStateChecker(RepositorySafeHandle repo, Func checker) + private static unsafe bool RepositoryStateChecker(RepositoryHandle repo, Func checker) { - int res = checker(repo); + int res = checker(repo.AsIntPtr()); Ensure.BooleanResult(res); return (res == 1); diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 43a7b07f0..b4694dbb9 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -339,7 +339,6 @@ - diff --git a/LibGit2Sharp/Network.cs b/LibGit2Sharp/Network.cs index 851edb535..611db7395 100644 --- a/LibGit2Sharp/Network.cs +++ b/LibGit2Sharp/Network.cs @@ -130,20 +130,20 @@ private IEnumerable ListReferencesInternal(string url, CredentialsHan } } - static RemoteSafeHandle BuildRemoteSafeHandle(RepositorySafeHandle repoHandle, Remote remote) + static RemoteSafeHandle BuildRemoteSafeHandle(RepositoryHandle repoHandle, Remote remote) { - Debug.Assert(repoHandle != null && !repoHandle.IsClosed && !repoHandle.IsInvalid); + Debug.Assert(repoHandle != null && !repoHandle.IsNull); Debug.Assert(remote != null && remote.Name != null); RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repoHandle, remote.Name, true); - Debug.Assert(remoteHandle != null && !(remoteHandle.IsClosed || remoteHandle.IsInvalid)); + Debug.Assert(remoteHandle != null && !(remoteHandle.IsInvalid || remoteHandle.IsInvalid)); return remoteHandle; } - static RemoteSafeHandle BuildRemoteSafeHandle(RepositorySafeHandle repoHandle, string url) + static RemoteSafeHandle BuildRemoteSafeHandle(RepositoryHandle repoHandle, string url) { - Debug.Assert(repoHandle != null && !repoHandle.IsClosed && !repoHandle.IsInvalid); + Debug.Assert(repoHandle != null && !repoHandle.IsNull); Debug.Assert(url != null); RemoteSafeHandle remoteHandle = Proxy.git_remote_create_anonymous(repoHandle, url); @@ -153,7 +153,7 @@ static RemoteSafeHandle BuildRemoteSafeHandle(RepositorySafeHandle repoHandle, s } static void DoFetch( - RepositorySafeHandle repoHandle, + RepositoryHandle repoHandle, Remote remote, FetchOptions options, string logMessage, @@ -166,7 +166,7 @@ static void DoFetch( } static void DoFetch( - RepositorySafeHandle repoHandle, + RepositoryHandle repoHandle, string url, FetchOptions options, string logMessage, diff --git a/LibGit2Sharp/Repository.cs b/LibGit2Sharp/Repository.cs index 6649e64be..3554fcf43 100644 --- a/LibGit2Sharp/Repository.cs +++ b/LibGit2Sharp/Repository.cs @@ -21,7 +21,7 @@ public sealed class Repository : IRepository private readonly BranchCollection branches; private readonly CommitLog commits; private readonly Lazy config; - private readonly RepositorySafeHandle handle; + private readonly RepositoryHandle handle; private readonly Lazy index; private readonly ReferenceCollection refs; private readonly TagCollection tags; @@ -204,7 +204,7 @@ private void EagerlyLoadComponentsWithSpecifiedPaths(RepositoryOptions options) } } - internal RepositorySafeHandle Handle + internal RepositoryHandle Handle { get { return handle; } } @@ -404,7 +404,7 @@ public static string Init(string path, bool isBare) { Ensure.ArgumentNotNullOrEmptyString(path, "path"); - using (RepositorySafeHandle repo = Proxy.git_repository_init_ext(null, path, isBare)) + using (RepositoryHandle repo = Proxy.git_repository_init_ext(null, path, isBare)) { FilePath repoPath = Proxy.git_repository_path(repo); return repoPath.Native; @@ -429,7 +429,7 @@ public static string Init(string workingDirectoryPath, string gitDirectoryPath) // TODO: Shouldn't we ensure that the working folder isn't under the gitDir? - using (RepositorySafeHandle repo = Proxy.git_repository_init_ext(wd, gitDirectoryPath, false)) + using (RepositoryHandle repo = Proxy.git_repository_init_ext(wd, gitDirectoryPath, false)) { FilePath repoPath = Proxy.git_repository_path(repo); return repoPath.Native; @@ -583,7 +583,7 @@ public static IEnumerable ListRemoteReferences(string url, Credential { Ensure.ArgumentNotNull(url, "url"); - using (RepositorySafeHandle repositoryHandle = Proxy.git_repository_new()) + using (RepositoryHandle repositoryHandle = Proxy.git_repository_new()) using (RemoteSafeHandle remoteHandle = Proxy.git_remote_create_anonymous(repositoryHandle, url)) { var gitCallbacks = new GitRemoteCallbacks { version = 1 }; @@ -691,7 +691,7 @@ public static string Clone(string sourceUrl, string workdirPath, { cloneOpts.CheckoutBranch = StrictUtf8Marshaler.FromManaged(options.BranchName); - using (RepositorySafeHandle repo = Proxy.git_clone(sourceUrl, workdirPath, ref cloneOpts)) + using (RepositoryHandle repo = Proxy.git_clone(sourceUrl, workdirPath, ref cloneOpts)) { clonedRepoPath = Proxy.git_repository_path(repo).Native; } From b2d9e44f677d4ee54ef45f9245ab1b2169d1d887 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 20:59:08 +0100 Subject: [PATCH 17/50] Set the pointer to null upon disposing --- LibGit2Sharp/Core/Handles/Objects.cs | 3 +++ LibGit2Sharp/Core/Handles/Objects.tt | 1 + 2 files changed, 4 insertions(+) diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index cec9129af..e25e6fbcc 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -55,6 +55,7 @@ void Dispose(bool disposing) if (owned) { NativeMethods.git_tree_entry_free(ptr); + ptr = null; } } @@ -123,6 +124,7 @@ void Dispose(bool disposing) if (owned) { NativeMethods.git_reference_free(ptr); + ptr = null; } } @@ -191,6 +193,7 @@ void Dispose(bool disposing) if (owned) { NativeMethods.git_repository_free(ptr); + ptr = null; } } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 1fc79dc4e..af4a4d99b 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -77,6 +77,7 @@ for (var i = 0; i < cNames.Length; i++) if (owned) { NativeMethods.<#= cNames[i] #>_free(ptr); + ptr = null; } } From 707bbc7f616f14684a055fd8ee2bf6cdcdf5c3cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 21:49:23 +0100 Subject: [PATCH 18/50] Get rid of IndexNameEntrySafeHandle and IndexReucEntrySafeHandle --- LibGit2Sharp/Core/GitIndexNameEntry.cs | 8 ++++---- LibGit2Sharp/Core/GitIndexReucEntry.cs | 10 +++++----- .../Core/Handles/IndexNameEntrySafeHandle.cs | 10 ---------- .../Core/Handles/IndexReucEntrySafeHandle.cs | 10 ---------- LibGit2Sharp/Core/NativeMethods.cs | 6 +++--- LibGit2Sharp/Core/Proxy.cs | 6 +++--- LibGit2Sharp/IndexNameEntry.cs | 18 ++++++++--------- LibGit2Sharp/IndexNameEntryCollection.cs | 4 ++-- LibGit2Sharp/IndexReucEntry.cs | 20 +++++++++---------- LibGit2Sharp/IndexReucEntryCollection.cs | 8 ++++---- LibGit2Sharp/LibGit2Sharp.csproj | 2 -- 11 files changed, 38 insertions(+), 64 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/IndexNameEntrySafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/IndexReucEntrySafeHandle.cs diff --git a/LibGit2Sharp/Core/GitIndexNameEntry.cs b/LibGit2Sharp/Core/GitIndexNameEntry.cs index 251a00791..47a9b1bcb 100644 --- a/LibGit2Sharp/Core/GitIndexNameEntry.cs +++ b/LibGit2Sharp/Core/GitIndexNameEntry.cs @@ -4,10 +4,10 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitIndexNameEntry + internal unsafe struct git_index_name_entry { - public IntPtr Ancestor; - public IntPtr Ours; - public IntPtr Theirs; + public char* ancestor; + public char* ours; + public char* theirs; } } diff --git a/LibGit2Sharp/Core/GitIndexReucEntry.cs b/LibGit2Sharp/Core/GitIndexReucEntry.cs index dfd684edb..bc98d50df 100644 --- a/LibGit2Sharp/Core/GitIndexReucEntry.cs +++ b/LibGit2Sharp/Core/GitIndexReucEntry.cs @@ -4,14 +4,14 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitIndexReucEntry + internal unsafe struct git_index_reuc_entry { public uint AncestorMode; public uint OurMode; public uint TheirMode; - public GitOid AncestorId; - public GitOid OurId; - public GitOid TheirId; - public IntPtr Path; + public git_oid AncestorId; + public git_oid OurId; + public git_oid TheirId; + public char* Path; } } diff --git a/LibGit2Sharp/Core/Handles/IndexNameEntrySafeHandle.cs b/LibGit2Sharp/Core/Handles/IndexNameEntrySafeHandle.cs deleted file mode 100644 index 9c5421a58..000000000 --- a/LibGit2Sharp/Core/Handles/IndexNameEntrySafeHandle.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class IndexNameEntrySafeHandle : NotOwnedSafeHandleBase - { - public GitIndexNameEntry MarshalAsGitIndexNameEntry() - { - return handle.MarshalAs(); - } - } -} diff --git a/LibGit2Sharp/Core/Handles/IndexReucEntrySafeHandle.cs b/LibGit2Sharp/Core/Handles/IndexReucEntrySafeHandle.cs deleted file mode 100644 index 5150081d1..000000000 --- a/LibGit2Sharp/Core/Handles/IndexReucEntrySafeHandle.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class IndexReucEntrySafeHandle : NotOwnedSafeHandleBase - { - public GitIndexReucEntry MarshalAsGitIndexReucEntry() - { - return handle.MarshalAs(); - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index a2dfccc13..622066bc0 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -682,7 +682,7 @@ internal static extern void git_index_conflict_iterator_free( internal static extern UIntPtr git_index_name_entrycount(IndexSafeHandle handle); [DllImport(libgit2)] - internal static extern IndexNameEntrySafeHandle git_index_name_get_byindex(IndexSafeHandle handle, UIntPtr n); + internal static extern unsafe git_index_name_entry* git_index_name_get_byindex(IndexSafeHandle handle, UIntPtr n); [DllImport(libgit2)] internal static extern int git_index_open( @@ -704,10 +704,10 @@ internal static extern int git_index_remove_bypath( internal static extern UIntPtr git_index_reuc_entrycount(IndexSafeHandle handle); [DllImport(libgit2)] - internal static extern IndexReucEntrySafeHandle git_index_reuc_get_byindex(IndexSafeHandle handle, UIntPtr n); + internal static extern unsafe git_index_reuc_entry* git_index_reuc_get_byindex(IndexSafeHandle handle, UIntPtr n); [DllImport(libgit2)] - internal static extern IndexReucEntrySafeHandle git_index_reuc_get_bypath( + internal static extern unsafe git_index_reuc_entry* git_index_reuc_get_bypath( IndexSafeHandle handle, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index f6d908c5e..e44abecc2 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -1022,7 +1022,7 @@ public static int git_index_name_entrycount(IndexSafeHandle index) .ConvertToInt(); } - public static IndexNameEntrySafeHandle git_index_name_get_byindex(IndexSafeHandle index, UIntPtr n) + public static unsafe git_index_name_entry* git_index_name_get_byindex(IndexSafeHandle index, UIntPtr n) { return NativeMethods.git_index_name_get_byindex(index, n); } @@ -1054,12 +1054,12 @@ public static int git_index_reuc_entrycount(IndexSafeHandle index) .ConvertToInt(); } - public static IndexReucEntrySafeHandle git_index_reuc_get_byindex(IndexSafeHandle index, UIntPtr n) + public static unsafe git_index_reuc_entry* git_index_reuc_get_byindex(IndexSafeHandle index, UIntPtr n) { return NativeMethods.git_index_reuc_get_byindex(index, n); } - public static IndexReucEntrySafeHandle git_index_reuc_get_bypath(IndexSafeHandle index, string path) + public static unsafe git_index_reuc_entry* git_index_reuc_get_bypath(IndexSafeHandle index, string path) { return NativeMethods.git_index_reuc_get_bypath(index, path); } diff --git a/LibGit2Sharp/IndexNameEntry.cs b/LibGit2Sharp/IndexNameEntry.cs index 5ba24f9c3..8cc4f5396 100644 --- a/LibGit2Sharp/IndexNameEntry.cs +++ b/LibGit2Sharp/IndexNameEntry.cs @@ -22,23 +22,21 @@ public class IndexNameEntry : IEquatable protected IndexNameEntry() { } - internal static IndexNameEntry BuildFromPtr(IndexNameEntrySafeHandle handle) + internal static unsafe IndexNameEntry BuildFromPtr(git_index_name_entry* entry) { - if (handle == null || handle.IsZero) + if (entry == null) { return null; } - GitIndexNameEntry entry = handle.MarshalAsGitIndexNameEntry(); - - string ancestor = entry.Ancestor != IntPtr.Zero - ? LaxFilePathMarshaler.FromNative(entry.Ancestor).Native + string ancestor = entry->ancestor != null + ? LaxFilePathMarshaler.FromNative(entry->ancestor) : null; - string ours = entry.Ours != IntPtr.Zero - ? LaxFilePathMarshaler.FromNative(entry.Ours).Native + string ours = entry->ours != null + ? LaxFilePathMarshaler.FromNative(entry->ours) : null; - string theirs = entry.Theirs != IntPtr.Zero - ? LaxFilePathMarshaler.FromNative(entry.Theirs).Native + string theirs = entry->theirs != null + ? LaxFilePathMarshaler.FromNative(entry->theirs) : null; return new IndexNameEntry diff --git a/LibGit2Sharp/IndexNameEntryCollection.cs b/LibGit2Sharp/IndexNameEntryCollection.cs index 2896f9124..a75bedd71 100644 --- a/LibGit2Sharp/IndexNameEntryCollection.cs +++ b/LibGit2Sharp/IndexNameEntryCollection.cs @@ -26,11 +26,11 @@ internal IndexNameEntryCollection(Index index) this.index = index; } - private IndexNameEntry this[int idx] + private unsafe IndexNameEntry this[int idx] { get { - IndexNameEntrySafeHandle entryHandle = Proxy.git_index_name_get_byindex(index.Handle, (UIntPtr)idx); + git_index_name_entry* entryHandle = Proxy.git_index_name_get_byindex(index.Handle, (UIntPtr)idx); return IndexNameEntry.BuildFromPtr(entryHandle); } } diff --git a/LibGit2Sharp/IndexReucEntry.cs b/LibGit2Sharp/IndexReucEntry.cs index 144e5c3c9..583df95ba 100644 --- a/LibGit2Sharp/IndexReucEntry.cs +++ b/LibGit2Sharp/IndexReucEntry.cs @@ -25,26 +25,24 @@ public class IndexReucEntry : IEquatable protected IndexReucEntry() { } - internal static IndexReucEntry BuildFromPtr(IndexReucEntrySafeHandle handle) + internal static unsafe IndexReucEntry BuildFromPtr(git_index_reuc_entry* entry) { - if (handle == null || handle.IsZero) + if (entry == null) { return null; } - GitIndexReucEntry entry = handle.MarshalAsGitIndexReucEntry(); - - FilePath path = LaxFilePathMarshaler.FromNative(entry.Path); + FilePath path = LaxUtf8Marshaler.FromNative(entry->Path); return new IndexReucEntry { Path = path.Native, - AncestorId = entry.AncestorId, - AncestorMode = (Mode)entry.AncestorMode, - OurId = entry.OurId, - OurMode = (Mode)entry.OurMode, - TheirId = entry.TheirId, - TheirMode = (Mode)entry.TheirMode, + AncestorId = ObjectId.BuildFromPtr(&entry->AncestorId), + AncestorMode = (Mode)entry->AncestorMode, + OurId = ObjectId.BuildFromPtr(&entry->OurId), + OurMode = (Mode)entry->OurMode, + TheirId = ObjectId.BuildFromPtr(&entry->TheirId), + TheirMode = (Mode)entry->TheirMode, }; } diff --git a/LibGit2Sharp/IndexReucEntryCollection.cs b/LibGit2Sharp/IndexReucEntryCollection.cs index 8402a285a..61af48b18 100644 --- a/LibGit2Sharp/IndexReucEntryCollection.cs +++ b/LibGit2Sharp/IndexReucEntryCollection.cs @@ -29,22 +29,22 @@ internal IndexReucEntryCollection(Index index) /// /// Gets the with the specified relative path. /// - public virtual IndexReucEntry this[string path] + public virtual unsafe IndexReucEntry this[string path] { get { Ensure.ArgumentNotNullOrEmptyString(path, "path"); - IndexReucEntrySafeHandle entryHandle = Proxy.git_index_reuc_get_bypath(index.Handle, path); + git_index_reuc_entry* entryHandle = Proxy.git_index_reuc_get_bypath(index.Handle, path); return IndexReucEntry.BuildFromPtr(entryHandle); } } - private IndexReucEntry this[int idx] + private unsafe IndexReucEntry this[int idx] { get { - IndexReucEntrySafeHandle entryHandle = Proxy.git_index_reuc_get_byindex(index.Handle, (UIntPtr)idx); + git_index_reuc_entry* entryHandle = Proxy.git_index_reuc_get_byindex(index.Handle, (UIntPtr)idx); return IndexReucEntry.BuildFromPtr(entryHandle); } } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index b4694dbb9..7138a6244 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -85,8 +85,6 @@ - - From 1f50a0f8cdf3c9b3f5a8cab2316d311fca504572 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 13 Jan 2016 22:45:37 +0100 Subject: [PATCH 19/50] Get rid of StatusEntrySafeHandle This includes using pointers for some diff entries, which this uses. --- LibGit2Sharp/ContentChanges.cs | 10 ++--- LibGit2Sharp/Core/GitDiff.cs | 20 +++++----- LibGit2Sharp/Core/GitDiffExtensions.cs | 10 ----- LibGit2Sharp/Core/GitStatusEntry.cs | 8 ++-- .../Core/Handles/StatusEntrySafeHandle.cs | 23 ----------- LibGit2Sharp/Core/NativeMethods.cs | 20 +++++----- LibGit2Sharp/Core/Proxy.cs | 6 +-- LibGit2Sharp/LibGit2Sharp.csproj | 2 - LibGit2Sharp/Patch.cs | 14 +++---- LibGit2Sharp/PatchStats.cs | 4 +- LibGit2Sharp/RepositoryStatus.cs | 38 ++++++------------- LibGit2Sharp/TreeChanges.cs | 6 +-- LibGit2Sharp/TreeEntryChanges.cs | 22 +++++------ 13 files changed, 67 insertions(+), 116 deletions(-) delete mode 100644 LibGit2Sharp/Core/GitDiffExtensions.cs delete mode 100644 LibGit2Sharp/Core/Handles/StatusEntrySafeHandle.cs diff --git a/LibGit2Sharp/ContentChanges.cs b/LibGit2Sharp/ContentChanges.cs index dee15abee..221c99efa 100644 --- a/LibGit2Sharp/ContentChanges.cs +++ b/LibGit2Sharp/ContentChanges.cs @@ -20,7 +20,7 @@ public class ContentChanges protected ContentChanges() { } - internal ContentChanges(Repository repo, Blob oldBlob, Blob newBlob, GitDiffOptions options) + internal unsafe ContentChanges(Repository repo, Blob oldBlob, Blob newBlob, GitDiffOptions options) { Proxy.git_diff_blobs(repo.Handle, oldBlob != null ? oldBlob.Id : null, @@ -64,9 +64,9 @@ public virtual string Patch /// public virtual bool IsBinaryComparison { get; private set; } - private int FileCallback(GitDiffDelta delta, float progress, IntPtr payload) + private unsafe int FileCallback(git_diff_delta* delta, float progress, IntPtr payload) { - IsBinaryComparison = delta.IsBinary(); + IsBinaryComparison = delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY); if (!IsBinaryComparison) { @@ -78,7 +78,7 @@ private int FileCallback(GitDiffDelta delta, float progress, IntPtr payload) return 0; } - private int HunkCallback(GitDiffDelta delta, GitDiffHunk hunk, IntPtr payload) + private unsafe int HunkCallback(git_diff_delta* delta, GitDiffHunk hunk, IntPtr payload) { string decodedContent = LaxUtf8Marshaler.FromBuffer(hunk.Header, (int)hunk.HeaderLen); @@ -86,7 +86,7 @@ private int HunkCallback(GitDiffDelta delta, GitDiffHunk hunk, IntPtr payload) return 0; } - private int LineCallback(GitDiffDelta delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload) + private unsafe int LineCallback(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload) { string decodedContent = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen); diff --git a/LibGit2Sharp/Core/GitDiff.cs b/LibGit2Sharp/Core/GitDiff.cs index 4d1e9768f..f2ec89eed 100644 --- a/LibGit2Sharp/Core/GitDiff.cs +++ b/LibGit2Sharp/Core/GitDiff.cs @@ -235,24 +235,24 @@ internal enum GitDiffFlags } [StructLayout(LayoutKind.Sequential)] - internal class GitDiffFile + internal unsafe struct git_diff_file { - public GitOid Id; - public IntPtr Path; + public git_oid Id; + public char* Path; public Int64 Size; public GitDiffFlags Flags; public UInt16 Mode; } [StructLayout(LayoutKind.Sequential)] - internal class GitDiffDelta + internal unsafe struct git_diff_delta { - public ChangeKind Status; - public GitDiffFlags Flags; - public UInt16 Similarity; - public UInt16 NumberOfFiles; - public GitDiffFile OldFile; - public GitDiffFile NewFile; + public ChangeKind status; + public GitDiffFlags flags; + public UInt16 similarity; + public UInt16 nfiles; + public git_diff_file old_file; + public git_diff_file new_file; } [StructLayout(LayoutKind.Sequential)] diff --git a/LibGit2Sharp/Core/GitDiffExtensions.cs b/LibGit2Sharp/Core/GitDiffExtensions.cs deleted file mode 100644 index a131d2091..000000000 --- a/LibGit2Sharp/Core/GitDiffExtensions.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace LibGit2Sharp.Core -{ - internal static class GitDiffExtensions - { - public static bool IsBinary(this GitDiffDelta delta) - { - return delta.Flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY); - } - } -} diff --git a/LibGit2Sharp/Core/GitStatusEntry.cs b/LibGit2Sharp/Core/GitStatusEntry.cs index 3e46c7b23..73e6547a8 100644 --- a/LibGit2Sharp/Core/GitStatusEntry.cs +++ b/LibGit2Sharp/Core/GitStatusEntry.cs @@ -7,21 +7,21 @@ namespace LibGit2Sharp.Core /// A status entry from libgit2. /// [StructLayout(LayoutKind.Sequential)] - internal class GitStatusEntry + internal unsafe struct git_status_entry { /// /// Calculated status of a filepath in the working directory considering the current and the . /// - public FileStatus Status; + public FileStatus status; /// /// The difference between the and . /// - public IntPtr HeadToIndexPtr; + public git_diff_delta* head_to_index; /// /// The difference between the and the working directory. /// - public IntPtr IndexToWorkDirPtr; + public git_diff_delta* index_to_workdir; } } diff --git a/LibGit2Sharp/Core/Handles/StatusEntrySafeHandle.cs b/LibGit2Sharp/Core/Handles/StatusEntrySafeHandle.cs deleted file mode 100644 index 45b6eacd4..000000000 --- a/LibGit2Sharp/Core/Handles/StatusEntrySafeHandle.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace LibGit2Sharp.Core.Handles -{ - internal class StatusEntrySafeHandle : NotOwnedSafeHandleBase - { - public StatusEntrySafeHandle() - : base() - { - } - - public StatusEntrySafeHandle(IntPtr handle) - : base() - { - this.SetHandle(handle); - } - - public GitStatusEntry MarshalAsGitStatusEntry() - { - return handle.MarshalAs(); - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 622066bc0..1024a8bbe 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -512,24 +512,24 @@ internal static extern unsafe int git_diff_tree_to_workdir( GitObjectSafeHandle oldTree, GitDiffOptions options); - internal delegate int git_diff_file_cb( - [In] GitDiffDelta delta, + internal unsafe delegate int git_diff_file_cb( + [In] git_diff_delta* delta, float progress, IntPtr payload); - internal delegate int git_diff_hunk_cb( - [In] GitDiffDelta delta, + internal unsafe delegate int git_diff_hunk_cb( + [In] git_diff_delta* delta, [In] GitDiffHunk hunk, IntPtr payload); - internal delegate int git_diff_line_cb( - [In] GitDiffDelta delta, + internal unsafe delegate int git_diff_line_cb( + [In] git_diff_delta* delta, [In] GitDiffHunk hunk, [In] GitDiffLine line, IntPtr payload); - internal delegate int git_diff_binary_cb( - [In] GitDiffDelta delta, + internal unsafe delegate int git_diff_binary_cb( + [In] git_diff_delta* delta, [In] GitDiffBinary binary, IntPtr payload); @@ -564,7 +564,7 @@ internal static extern int git_diff_find_similar( internal static extern UIntPtr git_diff_num_deltas(DiffSafeHandle diff); [DllImport(libgit2)] - internal static extern IntPtr git_diff_get_delta(DiffSafeHandle diff, UIntPtr idx); + internal static extern unsafe git_diff_delta* git_diff_get_delta(DiffSafeHandle diff, UIntPtr idx); [DllImport(libgit2)] internal static extern int git_filter_register( @@ -1543,7 +1543,7 @@ internal static extern int git_status_list_entrycount( StatusListSafeHandle statusList); [DllImport(libgit2)] - internal static extern StatusEntrySafeHandle git_status_byindex( + internal static extern unsafe git_status_entry* git_status_byindex( StatusListSafeHandle list, UIntPtr idx); diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index e44abecc2..53ad0b8a0 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -819,9 +819,9 @@ public static int git_diff_num_deltas(DiffSafeHandle diff) return (int)NativeMethods.git_diff_num_deltas(diff); } - public static GitDiffDelta git_diff_get_delta(DiffSafeHandle diff, int idx) + public static unsafe git_diff_delta* git_diff_get_delta(DiffSafeHandle diff, int idx) { - return NativeMethods.git_diff_get_delta(diff, (UIntPtr)idx).MarshalAs(false); + return NativeMethods.git_diff_get_delta(diff, (UIntPtr)idx); } #endregion @@ -2853,7 +2853,7 @@ public static int git_status_list_entrycount(StatusListSafeHandle list) return res; } - public static StatusEntrySafeHandle git_status_byindex(StatusListSafeHandle list, long idx) + public static unsafe git_status_entry* git_status_byindex(StatusListSafeHandle list, long idx) { return NativeMethods.git_status_byindex(list, (UIntPtr)idx); } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 7138a6244..1f4515124 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -158,7 +158,6 @@ - @@ -267,7 +266,6 @@ - diff --git a/LibGit2Sharp/Patch.cs b/LibGit2Sharp/Patch.cs index fce96e105..423ba78e3 100644 --- a/LibGit2Sharp/Patch.cs +++ b/LibGit2Sharp/Patch.cs @@ -30,7 +30,7 @@ public class Patch : IEnumerable, IDiffResult protected Patch() { } - internal Patch(DiffSafeHandle diff) + internal unsafe Patch(DiffSafeHandle diff) { int count = Proxy.git_diff_num_deltas(diff); for (int i = 0; i < count; i++) @@ -44,22 +44,22 @@ internal Patch(DiffSafeHandle diff) } } - private void AddFileChange(GitDiffDelta delta) + private unsafe void AddFileChange(git_diff_delta* delta) { var treeEntryChanges = new TreeEntryChanges(delta); - changes.Add(treeEntryChanges.Path, new PatchEntryChanges(delta.IsBinary(), treeEntryChanges)); + changes.Add(treeEntryChanges.Path, new PatchEntryChanges(delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY), treeEntryChanges)); } - private int PrintCallBack(GitDiffDelta delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload) + private unsafe int PrintCallBack(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload) { string patchPart = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen); // Deleted files mean no "new file" path - var pathPtr = delta.NewFile.Path != IntPtr.Zero - ? delta.NewFile.Path - : delta.OldFile.Path; + var pathPtr = delta->new_file.Path != null + ? delta->new_file.Path + : delta->old_file.Path; var filePath = LaxFilePathMarshaler.FromNative(pathPtr); PatchEntryChanges currentChange = this[filePath]; diff --git a/LibGit2Sharp/PatchStats.cs b/LibGit2Sharp/PatchStats.cs index fc16d303d..cd03d9ca3 100644 --- a/LibGit2Sharp/PatchStats.cs +++ b/LibGit2Sharp/PatchStats.cs @@ -25,7 +25,7 @@ public class PatchStats : IEnumerable, IDiffResult protected PatchStats() { } - internal PatchStats(DiffSafeHandle diff) + internal unsafe PatchStats(DiffSafeHandle diff) { int count = Proxy.git_diff_num_deltas(diff); for (int i = 0; i < count; i++) @@ -33,7 +33,7 @@ internal PatchStats(DiffSafeHandle diff) using (var patch = Proxy.git_patch_from_diff(diff, i)) { var delta = Proxy.git_diff_get_delta(diff, i); - var pathPtr = delta.NewFile.Path != IntPtr.Zero ? delta.NewFile.Path : delta.OldFile.Path; + var pathPtr = delta->new_file.Path != null ? delta->new_file.Path : delta->old_file.Path; var newFilePath = LaxFilePathMarshaler.FromNative(pathPtr); var stats = Proxy.git_patch_line_stats(patch); diff --git a/LibGit2Sharp/RepositoryStatus.cs b/LibGit2Sharp/RepositoryStatus.cs index 8a6b2e0f6..2105598e7 100644 --- a/LibGit2Sharp/RepositoryStatus.cs +++ b/LibGit2Sharp/RepositoryStatus.cs @@ -53,7 +53,7 @@ private static IDictionary> Bu protected RepositoryStatus() { } - internal RepositoryStatus(Repository repo, StatusOptions options) + internal unsafe RepositoryStatus(Repository repo, StatusOptions options) { statusEntries = new List(); @@ -64,22 +64,8 @@ internal RepositoryStatus(Repository repo, StatusOptions options) for (int i = 0; i < count; i++) { - StatusEntrySafeHandle e = Proxy.git_status_byindex(list, i); - GitStatusEntry entry = e.MarshalAsGitStatusEntry(); - - GitDiffDelta deltaHeadToIndex = null; - GitDiffDelta deltaIndexToWorkDir = null; - - if (entry.HeadToIndexPtr != IntPtr.Zero) - { - deltaHeadToIndex = entry.HeadToIndexPtr.MarshalAs(); - } - if (entry.IndexToWorkDirPtr != IntPtr.Zero) - { - deltaIndexToWorkDir = entry.IndexToWorkDirPtr.MarshalAs(); - } - - AddStatusEntryForDelta(entry.Status, deltaHeadToIndex, deltaIndexToWorkDir); + git_status_entry *entry = Proxy.git_status_byindex(list, i); + AddStatusEntryForDelta(entry->status, entry->head_to_index, entry->index_to_workdir); } isDirty = statusEntries.Any(entry => entry.State != FileStatus.Ignored && entry.State != FileStatus.Unaltered); @@ -144,7 +130,7 @@ private static GitStatusOptions CreateStatusOptions(StatusOptions options) return coreOptions; } - private void AddStatusEntryForDelta(FileStatus gitStatus, GitDiffDelta deltaHeadToIndex, GitDiffDelta deltaIndexToWorkDir) + private unsafe void AddStatusEntryForDelta(FileStatus gitStatus, git_diff_delta* deltaHeadToIndex, git_diff_delta* deltaIndexToWorkDir) { RenameDetails headToIndexRenameDetails = null; RenameDetails indexToWorkDirRenameDetails = null; @@ -152,22 +138,22 @@ private void AddStatusEntryForDelta(FileStatus gitStatus, GitDiffDelta deltaHead if ((gitStatus & FileStatus.RenamedInIndex) == FileStatus.RenamedInIndex) { headToIndexRenameDetails = - new RenameDetails(LaxFilePathMarshaler.FromNative(deltaHeadToIndex.OldFile.Path).Native, - LaxFilePathMarshaler.FromNative(deltaHeadToIndex.NewFile.Path).Native, - (int)deltaHeadToIndex.Similarity); + new RenameDetails(LaxFilePathMarshaler.FromNative(deltaHeadToIndex->old_file.Path), + LaxFilePathMarshaler.FromNative(deltaHeadToIndex->new_file.Path), + (int)deltaHeadToIndex->similarity); } if ((gitStatus & FileStatus.RenamedInWorkdir) == FileStatus.RenamedInWorkdir) { indexToWorkDirRenameDetails = - new RenameDetails(LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir.OldFile.Path).Native, - LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir.NewFile.Path).Native, - (int)deltaIndexToWorkDir.Similarity); + new RenameDetails(LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->old_file.Path), + LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->new_file.Path), + (int)deltaIndexToWorkDir->similarity); } var filePath = (deltaIndexToWorkDir != null) - ? LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir.NewFile.Path).Native - : LaxFilePathMarshaler.FromNative(deltaHeadToIndex.NewFile.Path).Native; + ? LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->new_file.Path) + : LaxFilePathMarshaler.FromNative(deltaHeadToIndex->new_file.Path); StatusEntry statusEntry = new StatusEntry(filePath, gitStatus, headToIndexRenameDetails, indexToWorkDirRenameDetails); diff --git a/LibGit2Sharp/TreeChanges.cs b/LibGit2Sharp/TreeChanges.cs index dcf788556..bd81328f6 100644 --- a/LibGit2Sharp/TreeChanges.cs +++ b/LibGit2Sharp/TreeChanges.cs @@ -50,18 +50,18 @@ private static IDictionary> Bu protected TreeChanges() { } - internal TreeChanges(DiffSafeHandle diff) + internal unsafe TreeChanges(DiffSafeHandle diff) { Proxy.git_diff_foreach(diff, FileCallback, null, null); } - private int FileCallback(GitDiffDelta delta, float progress, IntPtr payload) + private unsafe int FileCallback(git_diff_delta* delta, float progress, IntPtr payload) { AddFileChange(delta); return 0; } - private void AddFileChange(GitDiffDelta delta) + private unsafe void AddFileChange(git_diff_delta* delta) { var treeEntryChanges = new TreeEntryChanges(delta); diff --git a/LibGit2Sharp/TreeEntryChanges.cs b/LibGit2Sharp/TreeEntryChanges.cs index 4d57b8e50..4fdf83fea 100644 --- a/LibGit2Sharp/TreeEntryChanges.cs +++ b/LibGit2Sharp/TreeEntryChanges.cs @@ -16,21 +16,21 @@ public class TreeEntryChanges protected TreeEntryChanges() { } - internal TreeEntryChanges(GitDiffDelta delta) + internal unsafe TreeEntryChanges(git_diff_delta* delta) { - Path = LaxFilePathMarshaler.FromNative(delta.NewFile.Path).Native; - OldPath = LaxFilePathMarshaler.FromNative(delta.OldFile.Path).Native; + Path = LaxFilePathMarshaler.FromNative(delta->new_file.Path); + OldPath = LaxFilePathMarshaler.FromNative(delta->old_file.Path); - Mode = (Mode)delta.NewFile.Mode; - OldMode = (Mode)delta.OldFile.Mode; - Oid = delta.NewFile.Id; - OldOid = delta.OldFile.Id; - Exists = (delta.NewFile.Flags & GitDiffFlags.GIT_DIFF_FLAG_EXISTS) != 0; - OldExists = (delta.OldFile.Flags & GitDiffFlags.GIT_DIFF_FLAG_EXISTS) != 0; + Mode = (Mode)delta->new_file.Mode; + OldMode = (Mode)delta->old_file.Mode; + Oid = ObjectId.BuildFromPtr(&delta->new_file.Id); + OldOid = ObjectId.BuildFromPtr(&delta->old_file.Id); + Exists = (delta->new_file.Flags & GitDiffFlags.GIT_DIFF_FLAG_EXISTS) != 0; + OldExists = (delta->old_file.Flags & GitDiffFlags.GIT_DIFF_FLAG_EXISTS) != 0; - Status = (delta.Status == ChangeKind.Untracked || delta.Status == ChangeKind.Ignored) + Status = (delta->status == ChangeKind.Untracked || delta->status == ChangeKind.Ignored) ? ChangeKind.Added - : delta.Status; + : delta->status; } /// From 4c5c088e8f9b1bb494ed1c088f5838f8d67031d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Thu, 14 Jan 2016 04:35:28 +0100 Subject: [PATCH 20/50] Get rid of SignatureSafeHandle --- LibGit2Sharp/BlameHunk.cs | 6 +- LibGit2Sharp/Core/GitBlame.cs | 6 +- LibGit2Sharp/Core/GitSignature.cs | 8 +-- LibGit2Sharp/Core/GitTime.cs | 6 +- LibGit2Sharp/Core/Handles/Objects.cs | 69 +++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 2 + .../Core/Handles/SignatureSafeHandle.cs | 11 --- LibGit2Sharp/Core/NativeMethods.cs | 48 ++++++------- LibGit2Sharp/Core/Proxy.cs | 63 ++++++++--------- LibGit2Sharp/Identity.cs | 6 +- LibGit2Sharp/LibGit2Sharp.csproj | 1 - LibGit2Sharp/Signature.cs | 16 ++--- 12 files changed, 147 insertions(+), 95 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/SignatureSafeHandle.cs diff --git a/LibGit2Sharp/BlameHunk.cs b/LibGit2Sharp/BlameHunk.cs index 93d711c7a..10d0d1b0e 100644 --- a/LibGit2Sharp/BlameHunk.cs +++ b/LibGit2Sharp/BlameHunk.cs @@ -20,7 +20,7 @@ public class BlameHunk : IEquatable x => x.InitialCommit); - internal BlameHunk(IRepository repository, GitBlameHunk rawHunk) + internal unsafe BlameHunk(IRepository repository, GitBlameHunk rawHunk) { finalCommit = new Lazy(() => repository.Lookup(rawHunk.FinalCommitId)); origCommit = new Lazy(() => repository.Lookup(rawHunk.OrigCommitId)); @@ -36,12 +36,12 @@ internal BlameHunk(IRepository repository, GitBlameHunk rawHunk) InitialStartLineNumber = rawHunk.OrigStartLineNumber - 1; // Signature objects need to have ownership of their native pointers - if (rawHunk.FinalSignature != IntPtr.Zero) + if (rawHunk.FinalSignature != null) { FinalSignature = new Signature(Proxy.git_signature_dup(rawHunk.FinalSignature)); } - if (rawHunk.OrigSignature != IntPtr.Zero) + if (rawHunk.OrigSignature != null) { InitialSignature = new Signature(Proxy.git_signature_dup(rawHunk.OrigSignature)); } diff --git a/LibGit2Sharp/Core/GitBlame.cs b/LibGit2Sharp/Core/GitBlame.cs index 9db27d25e..4f6fc52ca 100644 --- a/LibGit2Sharp/Core/GitBlame.cs +++ b/LibGit2Sharp/Core/GitBlame.cs @@ -53,18 +53,18 @@ internal class GitBlameOptions } [StructLayout(LayoutKind.Sequential)] - internal class GitBlameHunk + internal unsafe class GitBlameHunk { public ushort LinesInHunk; public GitOid FinalCommitId; public ushort FinalStartLineNumber; - public IntPtr FinalSignature; + public git_signature* FinalSignature; public GitOid OrigCommitId; public IntPtr OrigPath; public ushort OrigStartLineNumber; - public IntPtr OrigSignature; + public git_signature* OrigSignature; public byte Boundary; } diff --git a/LibGit2Sharp/Core/GitSignature.cs b/LibGit2Sharp/Core/GitSignature.cs index 3261d4c57..5641af368 100644 --- a/LibGit2Sharp/Core/GitSignature.cs +++ b/LibGit2Sharp/Core/GitSignature.cs @@ -4,10 +4,10 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitSignature + internal unsafe struct git_signature { - public IntPtr Name; - public IntPtr Email; - public GitTime When; + public char* name; + public char* email; + public git_time when; } } diff --git a/LibGit2Sharp/Core/GitTime.cs b/LibGit2Sharp/Core/GitTime.cs index 304500d0c..e8051048e 100644 --- a/LibGit2Sharp/Core/GitTime.cs +++ b/LibGit2Sharp/Core/GitTime.cs @@ -3,9 +3,9 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitTime + internal unsafe struct git_time { - public long Time; - public int Offset; + public long time; + public int offset; } } diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index e25e6fbcc..2d600cb1e 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -211,4 +211,73 @@ public void Dispose() } } + internal unsafe class SignatureHandle : IDisposable + { + git_signature* ptr; + internal git_signature* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe SignatureHandle(git_signature* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe SignatureHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_signature*) ptr.ToPointer(); + this.owned = owned; + } + + ~SignatureHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_signature_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_signature*(SignatureHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index af4a4d99b..18839e084 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -15,12 +15,14 @@ var cNames = new[] { "git_tree_entry", "git_reference", "git_repository", + "git_signature", }; var csNames = new[] { "TreeEntryHandle", "ReferenceHandle", "RepositoryHandle", + "SignatureHandle", }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/Handles/SignatureSafeHandle.cs b/LibGit2Sharp/Core/Handles/SignatureSafeHandle.cs deleted file mode 100644 index 51f745ae9..000000000 --- a/LibGit2Sharp/Core/Handles/SignatureSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class SignatureSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_signature_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 1024a8bbe..387d2711e 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -224,11 +224,11 @@ internal static extern int git_rebase_next( RebaseSafeHandle rebase); [DllImport(libgit2)] - internal static extern int git_rebase_commit( + internal static extern unsafe int git_rebase_commit( ref GitOid id, RebaseSafeHandle rebase, - SignatureSafeHandle author, - SignatureSafeHandle committer, + git_signature* author, + git_signature* committer, IntPtr message_encoding, IntPtr message); @@ -237,9 +237,9 @@ internal static extern int git_rebase_abort( RebaseSafeHandle rebase); [DllImport(libgit2)] - internal static extern int git_rebase_finish( + internal static extern unsafe int git_rebase_finish( RebaseSafeHandle repo, - SignatureSafeHandle signature); + git_signature* signature); [DllImport(libgit2)] internal static extern void git_rebase_free( @@ -285,18 +285,18 @@ internal static extern unsafe int git_clone( ref GitCloneOptions opts); [DllImport(libgit2)] - internal static extern IntPtr git_commit_author(GitObjectSafeHandle commit); + internal static extern unsafe git_signature* git_commit_author(GitObjectSafeHandle commit); [DllImport(libgit2)] - internal static extern IntPtr git_commit_committer(GitObjectSafeHandle commit); + internal static extern unsafe git_signature* git_commit_committer(GitObjectSafeHandle commit); [DllImport(libgit2)] internal static extern unsafe int git_commit_create_from_ids( out GitOid id, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string updateRef, - SignatureSafeHandle author, - SignatureSafeHandle committer, + git_signature* author, + git_signature* committer, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string encoding, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, ref GitOid tree, @@ -810,8 +810,8 @@ internal static extern unsafe int git_note_create( out GitOid noteOid, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, - SignatureSafeHandle author, - SignatureSafeHandle committer, + git_signature* author, + git_signature* committer, ref GitOid oid, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string note, int force); @@ -837,8 +837,8 @@ internal static extern unsafe int git_note_read( internal static extern unsafe int git_note_remove( git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, - SignatureSafeHandle author, - SignatureSafeHandle committer, + git_signature* author, + git_signature* committer, ref GitOid oid); [DllImport(libgit2)] @@ -1102,7 +1102,7 @@ internal static extern ReflogEntrySafeHandle git_reflog_entry_byindex( SafeHandle entry); [DllImport(libgit2)] - internal static extern IntPtr git_reflog_entry_committer( + internal static extern unsafe git_signature* git_reflog_entry_committer( SafeHandle entry); [DllImport(libgit2)] @@ -1471,30 +1471,30 @@ internal static extern unsafe int git_revparse_ext( internal static extern void git_revwalk_simplify_first_parent(RevWalkerSafeHandle walk); [DllImport(libgit2)] - internal static extern void git_signature_free(IntPtr signature); + internal static extern unsafe void git_signature_free(git_signature* signature); [DllImport(libgit2)] - internal static extern int git_signature_new( - out SignatureSafeHandle signature, + internal static extern unsafe int git_signature_new( + out git_signature* signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string email, long time, int offset); [DllImport(libgit2)] - internal static extern int git_signature_now( - out SignatureSafeHandle signature, + internal static extern unsafe int git_signature_now( + out git_signature* signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string email); [DllImport(libgit2)] - internal static extern int git_signature_dup(out IntPtr dest, IntPtr sig); + internal static extern unsafe int git_signature_dup(out git_signature* dest, git_signature* sig); [DllImport(libgit2)] internal static extern unsafe int git_stash_save( out GitOid id, git_repository* repo, - SignatureSafeHandle stasher, + git_signature* stasher, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, StashModifiers flags); @@ -1650,7 +1650,7 @@ internal static extern unsafe int git_tag_annotation_create( git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, - SignatureSafeHandle signature, + git_signature* signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message); [DllImport(libgit2)] @@ -1659,7 +1659,7 @@ internal static extern unsafe int git_tag_create( git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, - SignatureSafeHandle signature, + git_signature* signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, [MarshalAs(UnmanagedType.Bool)] bool force); @@ -1690,7 +1690,7 @@ internal static extern unsafe int git_tag_delete( internal static extern string git_tag_name(GitObjectSafeHandle tag); [DllImport(libgit2)] - internal static extern IntPtr git_tag_tagger(GitObjectSafeHandle tag); + internal static extern unsafe git_signature* git_tag_tagger(GitObjectSafeHandle tag); [DllImport(libgit2)] internal static extern unsafe git_oid* git_tag_target_id(GitObjectSafeHandle tag); diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 53ad0b8a0..dc7e94f14 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -349,12 +349,12 @@ public static unsafe RepositoryHandle git_clone( #region git_commit_ - public static Signature git_commit_author(GitObjectSafeHandle obj) + public static unsafe Signature git_commit_author(GitObjectSafeHandle obj) { return new Signature(NativeMethods.git_commit_author(obj)); } - public static Signature git_commit_committer(GitObjectSafeHandle obj) + public static unsafe Signature git_commit_committer(GitObjectSafeHandle obj) { return new Signature(NativeMethods.git_commit_committer(obj)); } @@ -368,8 +368,8 @@ public static unsafe ObjectId git_commit_create( Tree tree, GitOid[] parentIds) { - using (SignatureSafeHandle authorHandle = author.BuildHandle()) - using (SignatureSafeHandle committerHandle = committer.BuildHandle()) + using (SignatureHandle authorHandle = author.BuildHandle()) + using (SignatureHandle committerHandle = committer.BuildHandle()) using (var parentPtrs = new ArrayMarshaler(parentIds)) { GitOid commitOid; @@ -1266,8 +1266,8 @@ public static unsafe ObjectId git_note_create( string note, bool force) { - using (SignatureSafeHandle authorHandle = author.BuildHandle()) - using (SignatureSafeHandle committerHandle = committer.BuildHandle()) + using (SignatureHandle authorHandle = author.BuildHandle()) + using (SignatureHandle committerHandle = committer.BuildHandle()) { GitOid noteOid; GitOid oid = targetId.Oid; @@ -1332,8 +1332,8 @@ public static unsafe NoteSafeHandle git_note_read(RepositoryHandle repo, string public static unsafe void git_note_remove(RepositoryHandle repo, string notes_ref, Signature author, Signature committer, ObjectId targetId) { - using (SignatureSafeHandle authorHandle = author.BuildHandle()) - using (SignatureSafeHandle committerHandle = committer.BuildHandle()) + using (SignatureHandle authorHandle = author.BuildHandle()) + using (SignatureHandle committerHandle = committer.BuildHandle()) { GitOid oid = targetId.Oid; @@ -1713,7 +1713,7 @@ public static GitRebaseOperation git_rebase_next(RebaseSafeHandle rebase) return operation; } - public static GitRebaseCommitResult git_rebase_commit( + public static unsafe GitRebaseCommitResult git_rebase_commit( RebaseSafeHandle rebase, Identity author, Identity committer) @@ -1721,8 +1721,8 @@ public static GitRebaseCommitResult git_rebase_commit( Ensure.ArgumentNotNull(rebase, "rebase"); Ensure.ArgumentNotNull(committer, "committer"); - using (SignatureSafeHandle committerHandle = committer.BuildNowSignatureHandle()) - using (SignatureSafeHandle authorHandle = author.SafeBuildNowSignatureHandle()) + using (SignatureHandle committerHandle = committer.BuildNowSignatureHandle()) + using (SignatureHandle authorHandle = author.SafeBuildNowSignatureHandle()) { GitRebaseCommitResult commitResult = new GitRebaseCommitResult(); @@ -1768,7 +1768,7 @@ public static void git_rebase_abort( Ensure.ZeroResult(result); } - public static void git_rebase_finish( + public static unsafe void git_rebase_finish( RebaseSafeHandle rebase, Identity committer) { @@ -1976,7 +1976,7 @@ public static unsafe ObjectId git_reflog_entry_id_new(SafeHandle entry) return ObjectId.BuildFromPtr(NativeMethods.git_reflog_entry_id_new(entry)); } - public static Signature git_reflog_entry_committer(SafeHandle entry) + public static unsafe Signature git_reflog_entry_committer(SafeHandle entry) { return new Signature(NativeMethods.git_reflog_entry_committer(entry)); } @@ -2695,34 +2695,29 @@ public static void git_revwalk_simplify_first_parent(RevWalkerSafeHandle walker) #region git_signature_ - public static void git_signature_free(IntPtr signature) + public static unsafe SignatureHandle git_signature_new(string name, string email, DateTimeOffset when) { - NativeMethods.git_signature_free(signature); - } - - public static SignatureSafeHandle git_signature_new(string name, string email, DateTimeOffset when) - { - SignatureSafeHandle handle; + git_signature* ptr; - int res = NativeMethods.git_signature_new(out handle, name, email, when.ToSecondsSinceEpoch(), + int res = NativeMethods.git_signature_new(out ptr, name, email, when.ToSecondsSinceEpoch(), (int)when.Offset.TotalMinutes); Ensure.ZeroResult(res); - return handle; + return new SignatureHandle(ptr, true); } - public static SignatureSafeHandle git_signature_now(string name, string email) + public static unsafe SignatureHandle git_signature_now(string name, string email) { - SignatureSafeHandle handle; - int res = NativeMethods.git_signature_now(out handle, name, email); + git_signature* ptr; + int res = NativeMethods.git_signature_now(out ptr, name, email); Ensure.ZeroResult(res); - return handle; + return new SignatureHandle(ptr, true); } - public static IntPtr git_signature_dup(IntPtr sig) + public static unsafe git_signature* git_signature_dup(git_signature* sig) { - IntPtr handle; + git_signature* handle; int res = NativeMethods.git_signature_dup(out handle, sig); Ensure.ZeroResult(res); return handle; @@ -2738,7 +2733,7 @@ public static unsafe ObjectId git_stash_save( string prettifiedMessage, StashModifiers options) { - using (SignatureSafeHandle sigHandle = stasher.BuildHandle()) + using (SignatureHandle sigHandle = stasher.BuildHandle()) { GitOid stashOid; @@ -2995,7 +2990,7 @@ public static unsafe ObjectId git_tag_annotation_create( string message) { using (var objectPtr = new ObjectSafeWrapper(target.Id, repo)) - using (SignatureSafeHandle sigHandle = tagger.BuildHandle()) + using (SignatureHandle sigHandle = tagger.BuildHandle()) { GitOid oid; int res = NativeMethods.git_tag_annotation_create(out oid, repo, name, objectPtr.ObjectPtr, sigHandle, message); @@ -3014,7 +3009,7 @@ public static unsafe ObjectId git_tag_create( bool allowOverwrite) { using (var objectPtr = new ObjectSafeWrapper(target.Id, repo)) - using (SignatureSafeHandle sigHandle = tagger.BuildHandle()) + using (SignatureHandle sigHandle = tagger.BuildHandle()) { GitOid oid; int res = NativeMethods.git_tag_create(out oid, repo, name, objectPtr.ObjectPtr, sigHandle, message, allowOverwrite); @@ -3069,14 +3064,14 @@ public static string git_tag_name(GitObjectSafeHandle tag) return NativeMethods.git_tag_name(tag); } - public static Signature git_tag_tagger(GitObjectSafeHandle tag) + public static unsafe Signature git_tag_tagger(GitObjectSafeHandle tag) { - IntPtr taggerHandle = NativeMethods.git_tag_tagger(tag); + git_signature* taggerHandle = NativeMethods.git_tag_tagger(tag); // Not all tags have a tagger signature - we need to handle // this case. Signature tagger = null; - if (taggerHandle != IntPtr.Zero) + if (taggerHandle != null) { tagger = new Signature(taggerHandle); } diff --git a/LibGit2Sharp/Identity.cs b/LibGit2Sharp/Identity.cs index e3ebd9ff7..faa4ec884 100644 --- a/LibGit2Sharp/Identity.cs +++ b/LibGit2Sharp/Identity.cs @@ -43,7 +43,7 @@ public string Name get { return _name; } } - internal SignatureSafeHandle BuildNowSignatureHandle() + internal SignatureHandle BuildNowSignatureHandle() { return Proxy.git_signature_now(Name, Email); } @@ -57,11 +57,11 @@ internal static class IdentityHelpers /// /// /// - public static SignatureSafeHandle SafeBuildNowSignatureHandle(this Identity identity) + public static unsafe SignatureHandle SafeBuildNowSignatureHandle(this Identity identity) { if (identity == null) { - return new SignatureSafeHandle(); + return new SignatureHandle(null, false); } return identity.BuildNowSignatureHandle(); diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 1f4515124..70f2307f1 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -277,7 +277,6 @@ - diff --git a/LibGit2Sharp/Signature.cs b/LibGit2Sharp/Signature.cs index 149ce0aa2..003abd629 100644 --- a/LibGit2Sharp/Signature.cs +++ b/LibGit2Sharp/Signature.cs @@ -17,13 +17,11 @@ public sealed class Signature : IEquatable private static readonly LambdaEqualityHelper equalityHelper = new LambdaEqualityHelper(x => x.Name, x => x.Email, x => x.When); - internal Signature(IntPtr signaturePtr) + internal unsafe Signature(git_signature* sig) { - var handle = signaturePtr.MarshalAs(); - - name = LaxUtf8Marshaler.FromNative(handle.Name); - email = LaxUtf8Marshaler.FromNative(handle.Email); - when = Epoch.ToDateTimeOffset(handle.When.Time, handle.When.Offset); + name = LaxUtf8Marshaler.FromNative(sig->name); + email = LaxUtf8Marshaler.FromNative(sig->email); + when = Epoch.ToDateTimeOffset(sig->when.time, sig->when.offset); } /// @@ -58,7 +56,7 @@ public Signature(Identity identity, DateTimeOffset when) this.when = when; } - internal SignatureSafeHandle BuildHandle() + internal SignatureHandle BuildHandle() { return Proxy.git_signature_new(name, email, when); } @@ -156,11 +154,11 @@ internal static class SignatureHelpers /// /// /// - public static SignatureSafeHandle SafeBuildHandle(this Signature signature) + public static unsafe SignatureHandle SafeBuildHandle(this Signature signature) { if (signature == null) { - return new SignatureSafeHandle(); + return new SignatureHandle(null, false); } return signature.BuildHandle(); From d3622c339fef4731993874d6b97f501e800bf96e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Thu, 14 Jan 2016 04:49:06 +0100 Subject: [PATCH 21/50] Get rid of StatusListSafeHandle --- LibGit2Sharp/Core/Handles/Objects.cs | 69 +++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 2 + .../Core/Handles/StatusListSafeHandle.cs | 11 --- LibGit2Sharp/Core/NativeMethods.cs | 12 ++-- LibGit2Sharp/Core/Opaques.cs | 1 + LibGit2Sharp/Core/Proxy.cs | 17 ++--- LibGit2Sharp/LibGit2Sharp.csproj | 1 - LibGit2Sharp/RepositoryStatus.cs | 2 +- 8 files changed, 85 insertions(+), 30 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/StatusListSafeHandle.cs diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index 2d600cb1e..952b08220 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -280,4 +280,73 @@ public void Dispose() } } + internal unsafe class StatusListHandle : IDisposable + { + git_status_list* ptr; + internal git_status_list* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe StatusListHandle(git_status_list* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe StatusListHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_status_list*) ptr.ToPointer(); + this.owned = owned; + } + + ~StatusListHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_status_list_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_status_list*(StatusListHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 18839e084..fdadb9f00 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -16,6 +16,7 @@ var cNames = new[] { "git_reference", "git_repository", "git_signature", + "git_status_list", }; var csNames = new[] { @@ -23,6 +24,7 @@ var csNames = new[] { "ReferenceHandle", "RepositoryHandle", "SignatureHandle", + "StatusListHandle", }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/Handles/StatusListSafeHandle.cs b/LibGit2Sharp/Core/Handles/StatusListSafeHandle.cs deleted file mode 100644 index 3a51cd7b5..000000000 --- a/LibGit2Sharp/Core/Handles/StatusListSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class StatusListSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_status_list_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 387d2711e..7023f1dfe 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1534,22 +1534,22 @@ internal static extern unsafe int git_status_file( [DllImport(libgit2)] internal static extern unsafe int git_status_list_new( - out StatusListSafeHandle git_status_list, + out git_status_list* git_status_list, git_repository* repo, GitStatusOptions options); [DllImport(libgit2)] - internal static extern int git_status_list_entrycount( - StatusListSafeHandle statusList); + internal static extern unsafe int git_status_list_entrycount( + git_status_list* statusList); [DllImport(libgit2)] internal static extern unsafe git_status_entry* git_status_byindex( - StatusListSafeHandle list, + git_status_list* list, UIntPtr idx); [DllImport(libgit2)] - internal static extern void git_status_list_free( - IntPtr statusList); + internal static extern unsafe void git_status_list_free( + git_status_list* statusList); [DllImport(libgit2)] internal static extern void git_strarray_free( diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index 8db63dccc..38cbc0fc2 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -6,5 +6,6 @@ internal struct git_tree_entry {} internal struct git_reference { } internal struct git_refspec {} internal struct git_repository {} + internal struct git_status_list {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index dc7e94f14..ed48a89d4 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -2833,31 +2833,26 @@ public static unsafe FileStatus git_status_file(RepositoryHandle repo, FilePath return status; } - public static unsafe StatusListSafeHandle git_status_list_new(RepositoryHandle repo, GitStatusOptions options) + public static unsafe StatusListHandle git_status_list_new(RepositoryHandle repo, GitStatusOptions options) { - StatusListSafeHandle handle; - int res = NativeMethods.git_status_list_new(out handle, repo, options); + git_status_list* ptr; + int res = NativeMethods.git_status_list_new(out ptr, repo, options); Ensure.ZeroResult(res); - return handle; + return new StatusListHandle(ptr, true); } - public static int git_status_list_entrycount(StatusListSafeHandle list) + public static unsafe int git_status_list_entrycount(StatusListHandle list) { int res = NativeMethods.git_status_list_entrycount(list); Ensure.Int32Result(res); return res; } - public static unsafe git_status_entry* git_status_byindex(StatusListSafeHandle list, long idx) + public static unsafe git_status_entry* git_status_byindex(StatusListHandle list, long idx) { return NativeMethods.git_status_byindex(list, (UIntPtr)idx); } - public static void git_status_list_free(IntPtr statusList) - { - NativeMethods.git_status_list_free(statusList); - } - #endregion #region git_submodule_ diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 70f2307f1..00ab721d3 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -158,7 +158,6 @@ - diff --git a/LibGit2Sharp/RepositoryStatus.cs b/LibGit2Sharp/RepositoryStatus.cs index 2105598e7..9a8e662c9 100644 --- a/LibGit2Sharp/RepositoryStatus.cs +++ b/LibGit2Sharp/RepositoryStatus.cs @@ -58,7 +58,7 @@ internal unsafe RepositoryStatus(Repository repo, StatusOptions options) statusEntries = new List(); using (GitStatusOptions coreOptions = CreateStatusOptions(options ?? new StatusOptions())) - using (StatusListSafeHandle list = Proxy.git_status_list_new(repo.Handle, coreOptions)) + using (StatusListHandle list = Proxy.git_status_list_new(repo.Handle, coreOptions)) { int count = Proxy.git_status_list_entrycount(list); From b55cd1c4bd89833595e4bf2a13cb514df4471115 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Thu, 14 Jan 2016 07:46:31 +0100 Subject: [PATCH 22/50] Get rid of the rest of MarshalAs This removes the last of the instances where we copy the C struct into a managed struct, where we're just going to copy it to another managed struct. Instead copy straight from the unmanaged to memanged memory just once. --- LibGit2Sharp/BlameHunk.cs | 29 ++++---- LibGit2Sharp/BlameHunkCollection.cs | 19 ++++-- LibGit2Sharp/CertificateSsh.cs | 26 ++++++-- LibGit2Sharp/CertificateX509.cs | 9 +-- LibGit2Sharp/Core/GitBlame.cs | 32 ++++----- LibGit2Sharp/Core/GitCertificate.cs | 2 +- LibGit2Sharp/Core/GitCertificateSsh.cs | 8 +-- LibGit2Sharp/Core/GitCertificateX509.cs | 4 +- LibGit2Sharp/Core/GitFilter.cs | 8 +-- LibGit2Sharp/Core/GitPushUpdate.cs | 10 +-- LibGit2Sharp/Core/GitRebaseOperation.cs | 6 +- LibGit2Sharp/Core/Handles/BlameSafeHandle.cs | 11 ---- LibGit2Sharp/Core/Handles/Objects.cs | 69 ++++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 2 + LibGit2Sharp/Core/IntPtrExtensions.cs | 17 ----- LibGit2Sharp/Core/NativeMethods.cs | 22 +++---- LibGit2Sharp/Core/Opaques.cs | 1 + LibGit2Sharp/Core/Proxy.cs | 55 +++++++--------- LibGit2Sharp/FilterSource.cs | 23 +++++-- LibGit2Sharp/LibGit2Sharp.csproj | 2 - LibGit2Sharp/ObjectDatabase.cs | 5 +- LibGit2Sharp/ObjectId.cs | 5 ++ LibGit2Sharp/PushUpdate.cs | 11 ++-- LibGit2Sharp/Rebase.cs | 30 ++++----- LibGit2Sharp/RebaseOperationImpl.cs | 18 ++--- LibGit2Sharp/RemoteCallbacks.cs | 14 ++-- 26 files changed, 253 insertions(+), 185 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/BlameSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/IntPtrExtensions.cs diff --git a/LibGit2Sharp/BlameHunk.cs b/LibGit2Sharp/BlameHunk.cs index 10d0d1b0e..c7d6bd228 100644 --- a/LibGit2Sharp/BlameHunk.cs +++ b/LibGit2Sharp/BlameHunk.cs @@ -19,31 +19,34 @@ public class BlameHunk : IEquatable x => x.InitialSignature, x => x.InitialCommit); - - internal unsafe BlameHunk(IRepository repository, GitBlameHunk rawHunk) + internal unsafe BlameHunk(IRepository repository, git_blame_hunk* rawHunk) { - finalCommit = new Lazy(() => repository.Lookup(rawHunk.FinalCommitId)); - origCommit = new Lazy(() => repository.Lookup(rawHunk.OrigCommitId)); + var origId = ObjectId.BuildFromPtr(&rawHunk->orig_commit_id); + var finalId = ObjectId.BuildFromPtr(&rawHunk->final_commit_id); + + finalCommit = new Lazy(() => repository.Lookup(finalId)); + origCommit = new Lazy(() => repository.Lookup(origId)); + - if (rawHunk.OrigPath != IntPtr.Zero) + if (rawHunk->orig_path != null) { - InitialPath = LaxUtf8Marshaler.FromNative(rawHunk.OrigPath); + InitialPath = LaxUtf8Marshaler.FromNative(rawHunk->orig_path); } - LineCount = rawHunk.LinesInHunk; + LineCount = rawHunk->lines_in_hunk; // Libgit2's line numbers are 1-based - FinalStartLineNumber = rawHunk.FinalStartLineNumber - 1; - InitialStartLineNumber = rawHunk.OrigStartLineNumber - 1; + FinalStartLineNumber = rawHunk->final_start_line_number - 1; + InitialStartLineNumber = rawHunk->orig_start_line_number - 1; // Signature objects need to have ownership of their native pointers - if (rawHunk.FinalSignature != null) + if (rawHunk->final_signature != null) { - FinalSignature = new Signature(Proxy.git_signature_dup(rawHunk.FinalSignature)); + FinalSignature = new Signature(rawHunk->final_signature); } - if (rawHunk.OrigSignature != null) + if (rawHunk->orig_signature != null) { - InitialSignature = new Signature(Proxy.git_signature_dup(rawHunk.OrigSignature)); + InitialSignature = new Signature(rawHunk->orig_signature); } } diff --git a/LibGit2Sharp/BlameHunkCollection.cs b/LibGit2Sharp/BlameHunkCollection.cs index 143d598b1..e3c458bae 100644 --- a/LibGit2Sharp/BlameHunkCollection.cs +++ b/LibGit2Sharp/BlameHunkCollection.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Runtime.InteropServices; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; @@ -20,26 +21,32 @@ public class BlameHunkCollection : IEnumerable /// protected BlameHunkCollection() { } - internal BlameHunkCollection(Repository repo, RepositoryHandle repoHandle, string path, BlameOptions options) + internal unsafe BlameHunkCollection(Repository repo, RepositoryHandle repoHandle, string path, BlameOptions options) { this.repo = repo; - var rawopts = new GitBlameOptions + var rawopts = new git_blame_options { version = 1, flags = options.Strategy.ToGitBlameOptionFlags(), - MinLine = (uint)options.MinLine, - MaxLine = (uint)options.MaxLine, + min_line = (uint)options.MinLine, + max_line = (uint)options.MaxLine, }; if (options.StartingAt != null) { - rawopts.NewestCommit = repo.Committish(options.StartingAt).Oid; + fixed (byte* p = rawopts.newest_commit.Id) + { + Marshal.Copy(repo.Committish(options.StartingAt).Oid.Id, 0, new IntPtr(p), git_oid.Size); + } } if (options.StoppingAt != null) { - rawopts.OldestCommit = repo.Committish(options.StoppingAt).Oid; + fixed (byte* p = rawopts.oldest_commit.Id) + { + Marshal.Copy(repo.Committish(options.StoppingAt).Oid.Id, 0, new IntPtr(p), git_oid.Size); + } } using (var blameHandle = Proxy.git_blame_file(repoHandle, path, rawopts)) diff --git a/LibGit2Sharp/CertificateSsh.cs b/LibGit2Sharp/CertificateSsh.cs index 01510ae68..a1b497c8a 100644 --- a/LibGit2Sharp/CertificateSsh.cs +++ b/LibGit2Sharp/CertificateSsh.cs @@ -1,4 +1,6 @@ -using LibGit2Sharp.Core; +using System; +using System.Runtime.InteropServices; +using LibGit2Sharp.Core; namespace LibGit2Sharp { @@ -37,17 +39,29 @@ protected CertificateSsh() /// True if we have the SHA1 hostkey hash from the server /// public readonly bool HasSHA1; - internal CertificateSsh(GitCertificateSsh cert) + internal unsafe CertificateSsh(git_certificate_ssh* cert) { - HasMD5 = cert.type.HasFlag(GitCertificateSshType.MD5); - HasSHA1 = cert.type.HasFlag(GitCertificateSshType.SHA1); + HasMD5 = cert->type.HasFlag(GitCertificateSshType.MD5); + HasSHA1 = cert->type.HasFlag(GitCertificateSshType.SHA1); HashMD5 = new byte[16]; - cert.HashMD5.CopyTo(HashMD5, 0); + fixed (byte* p = &HashMD5[0]) + { + for (var i = 0; i < HashMD5.Length; i++) + { + HashMD5[i] = p[i]; + } + } HashSHA1 = new byte[20]; - cert.HashSHA1.CopyTo(HashSHA1, 0); + fixed (byte* p = &HashSHA1[0]) + { + for (var i = 0; i < HashSHA1.Length; i++) + { + HashMD5[i] = p[i]; + } + } } } } diff --git a/LibGit2Sharp/CertificateX509.cs b/LibGit2Sharp/CertificateX509.cs index 6ffed937c..02d52ecd8 100644 --- a/LibGit2Sharp/CertificateX509.cs +++ b/LibGit2Sharp/CertificateX509.cs @@ -1,4 +1,5 @@ -using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using LibGit2Sharp.Core; @@ -21,11 +22,11 @@ protected CertificateX509() /// public virtual X509Certificate Certificate { get; private set; } - internal CertificateX509(GitCertificateX509 cert) + internal unsafe CertificateX509(git_certificate_x509* cert) { - int len = checked((int) cert.len.ToUInt32()); + int len = checked((int) cert->len.ToUInt32()); byte[] data = new byte[len]; - Marshal.Copy(cert.data, data, 0, len); + Marshal.Copy(new IntPtr(cert->data), data, 0, len); Certificate = new X509Certificate(data); } } diff --git a/LibGit2Sharp/Core/GitBlame.cs b/LibGit2Sharp/Core/GitBlame.cs index 4f6fc52ca..8082e7a63 100644 --- a/LibGit2Sharp/Core/GitBlame.cs +++ b/LibGit2Sharp/Core/GitBlame.cs @@ -41,32 +41,32 @@ internal enum GitBlameOptionFlags } [StructLayout(LayoutKind.Sequential)] - internal class GitBlameOptions + internal class git_blame_options { public uint version = 1; public GitBlameOptionFlags flags; - public UInt16 MinMatchCharacters; - public GitOid NewestCommit; - public GitOid OldestCommit; - public uint MinLine; - public uint MaxLine; + public UInt16 min_match_characters; + public git_oid newest_commit; + public git_oid oldest_commit; + public uint min_line; + public uint max_line; } [StructLayout(LayoutKind.Sequential)] - internal unsafe class GitBlameHunk + internal unsafe struct git_blame_hunk { - public ushort LinesInHunk; + public ushort lines_in_hunk; - public GitOid FinalCommitId; - public ushort FinalStartLineNumber; - public git_signature* FinalSignature; + public git_oid final_commit_id; + public ushort final_start_line_number; + public git_signature* final_signature; - public GitOid OrigCommitId; - public IntPtr OrigPath; - public ushort OrigStartLineNumber; - public git_signature* OrigSignature; + public git_oid orig_commit_id; + public char* orig_path; + public ushort orig_start_line_number; + public git_signature* orig_signature; - public byte Boundary; + public byte boundary; } internal static class BlameStrategyExtensions diff --git a/LibGit2Sharp/Core/GitCertificate.cs b/LibGit2Sharp/Core/GitCertificate.cs index 2a237fb22..9b0eafd1c 100644 --- a/LibGit2Sharp/Core/GitCertificate.cs +++ b/LibGit2Sharp/Core/GitCertificate.cs @@ -3,7 +3,7 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal struct GitCertificate + internal struct git_certificate { public GitCertificateType type; } diff --git a/LibGit2Sharp/Core/GitCertificateSsh.cs b/LibGit2Sharp/Core/GitCertificateSsh.cs index 4bb88a0d1..b1b9d7940 100644 --- a/LibGit2Sharp/Core/GitCertificateSsh.cs +++ b/LibGit2Sharp/Core/GitCertificateSsh.cs @@ -3,7 +3,7 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal struct GitCertificateSsh + internal unsafe struct git_certificate_ssh { public GitCertificateType cert_type; public GitCertificateSshType type; @@ -11,13 +11,11 @@ internal struct GitCertificateSsh /// /// The MD5 hash (if appropriate) /// - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] HashMD5; + public unsafe fixed byte HashMD5[16]; /// /// The MD5 hash (if appropriate) /// - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - public byte[] HashSHA1; + public unsafe fixed byte HashSHA1[20]; } } diff --git a/LibGit2Sharp/Core/GitCertificateX509.cs b/LibGit2Sharp/Core/GitCertificateX509.cs index 36df3c3ca..2ed13b74c 100644 --- a/LibGit2Sharp/Core/GitCertificateX509.cs +++ b/LibGit2Sharp/Core/GitCertificateX509.cs @@ -4,7 +4,7 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal struct GitCertificateX509 + internal unsafe struct git_certificate_x509 { /// /// Type of the certificate, in this case, GitCertificateType.X509 @@ -13,7 +13,7 @@ internal struct GitCertificateX509 /// /// Pointer to the X509 certificate data /// - public IntPtr data; + public byte* data; /// /// The size of the certificate data /// diff --git a/LibGit2Sharp/Core/GitFilter.cs b/LibGit2Sharp/Core/GitFilter.cs index 648cf47ec..1ca228e79 100644 --- a/LibGit2Sharp/Core/GitFilter.cs +++ b/LibGit2Sharp/Core/GitFilter.cs @@ -110,12 +110,12 @@ public delegate int git_filter_stream_fn( /// The file source being filtered /// [StructLayout(LayoutKind.Sequential)] - internal class GitFilterSource + internal unsafe struct git_filter_source { - public IntPtr repository; + public git_repository* repository; - public IntPtr path; + public char* path; - public GitOid oid; + public git_oid oid; } } diff --git a/LibGit2Sharp/Core/GitPushUpdate.cs b/LibGit2Sharp/Core/GitPushUpdate.cs index 5e5246622..ef0ba827a 100644 --- a/LibGit2Sharp/Core/GitPushUpdate.cs +++ b/LibGit2Sharp/Core/GitPushUpdate.cs @@ -4,11 +4,11 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal struct GitPushUpdate + internal unsafe struct git_push_update { - public IntPtr src_refname; - public IntPtr dst_refname; - public GitOid src; - public GitOid dst; + public char* src_refname; + public char* dst_refname; + public git_oid src; + public git_oid dst; } } diff --git a/LibGit2Sharp/Core/GitRebaseOperation.cs b/LibGit2Sharp/Core/GitRebaseOperation.cs index 660676edb..4db167a49 100644 --- a/LibGit2Sharp/Core/GitRebaseOperation.cs +++ b/LibGit2Sharp/Core/GitRebaseOperation.cs @@ -4,10 +4,10 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitRebaseOperation + internal unsafe struct git_rebase_operation { internal RebaseStepOperation type; - internal GitOid id; - internal IntPtr exec; + internal git_oid id; + internal char* exec; } } diff --git a/LibGit2Sharp/Core/Handles/BlameSafeHandle.cs b/LibGit2Sharp/Core/Handles/BlameSafeHandle.cs deleted file mode 100644 index e8218e3da..000000000 --- a/LibGit2Sharp/Core/Handles/BlameSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class BlameSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_blame_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index 952b08220..c1a4619e3 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -349,4 +349,73 @@ public void Dispose() } } + internal unsafe class BlameHandle : IDisposable + { + git_blame* ptr; + internal git_blame* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe BlameHandle(git_blame* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe BlameHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_blame*) ptr.ToPointer(); + this.owned = owned; + } + + ~BlameHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_blame_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_blame*(BlameHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index fdadb9f00..5e573a228 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -17,6 +17,7 @@ var cNames = new[] { "git_repository", "git_signature", "git_status_list", + "git_blame", }; var csNames = new[] { @@ -25,6 +26,7 @@ var csNames = new[] { "RepositoryHandle", "SignatureHandle", "StatusListHandle", + "BlameHandle", }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/IntPtrExtensions.cs b/LibGit2Sharp/Core/IntPtrExtensions.cs deleted file mode 100644 index 314a16834..000000000 --- a/LibGit2Sharp/Core/IntPtrExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace LibGit2Sharp.Core -{ - internal static class IntPtrExtensions - { - public static T MarshalAs(this IntPtr ptr, bool throwWhenNull = true) - { - if (!throwWhenNull && ptr == IntPtr.Zero) - { - return default(T); - } - return (T)Marshal.PtrToStructure(ptr, typeof(T)); - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 7023f1dfe..54f068856 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -90,21 +90,21 @@ internal static extern void giterr_set_str( internal static extern void giterr_set_oom(); [DllImport(libgit2)] - internal static extern UInt32 git_blame_get_hunk_count(BlameSafeHandle blame); + internal static extern unsafe UInt32 git_blame_get_hunk_count(git_blame* blame); [DllImport(libgit2)] - internal static extern IntPtr git_blame_get_hunk_byindex( - BlameSafeHandle blame, UInt32 index); + internal static extern unsafe git_blame_hunk* git_blame_get_hunk_byindex( + git_blame* blame, UInt32 index); [DllImport(libgit2)] internal static extern unsafe int git_blame_file( - out BlameSafeHandle blame, + out git_blame* blame, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, - GitBlameOptions options); + git_blame_options options); [DllImport(libgit2)] - internal static extern void git_blame_free(IntPtr blame); + internal static extern unsafe void git_blame_free(git_blame* blame); [DllImport(libgit2)] internal static extern unsafe int git_blob_create_fromdisk( @@ -214,13 +214,13 @@ internal static extern UIntPtr git_rebase_operation_current( RebaseSafeHandle rebase); [DllImport(libgit2)] - internal static extern IntPtr git_rebase_operation_byindex( + internal static extern unsafe git_rebase_operation* git_rebase_operation_byindex( RebaseSafeHandle rebase, UIntPtr index); [DllImport(libgit2)] - internal static extern int git_rebase_next( - out IntPtr operation, + internal static extern unsafe int git_rebase_next( + out git_rebase_operation* operation, RebaseSafeHandle rebase); [DllImport(libgit2)] @@ -576,7 +576,7 @@ internal static extern int git_filter_unregister( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))]string name); [DllImport(libgit2)] - internal static extern int git_filter_source_mode(IntPtr source); + internal static extern unsafe int git_filter_source_mode(git_filter_source* source); [DllImport(libgit2)] internal static extern int git_libgit2_features(); @@ -1716,7 +1716,7 @@ internal static extern unsafe int git_tag_delete( internal delegate int git_transport_cb(out IntPtr transport, IntPtr remote, IntPtr payload); - internal delegate int git_transport_certificate_check_cb(IntPtr cert, int valid, IntPtr hostname, IntPtr payload); + internal unsafe delegate int git_transport_certificate_check_cb(git_certificate* cert, int valid, IntPtr hostname, IntPtr payload); [DllImport(libgit2)] internal static extern int git_transport_register( diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index 38cbc0fc2..312d1ef92 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -7,5 +7,6 @@ internal struct git_reference { } internal struct git_refspec {} internal struct git_repository {} internal struct git_status_list {} + internal struct git_blame {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index ed48a89d4..42804408c 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -95,25 +95,20 @@ private static void BuildErrorMessageFromException(StringBuilder sb, int level, #region git_blame_ - public static unsafe BlameSafeHandle git_blame_file( + public static unsafe BlameHandle git_blame_file( RepositoryHandle repo, FilePath path, - GitBlameOptions options) + git_blame_options options) { - BlameSafeHandle handle; - int res = NativeMethods.git_blame_file(out handle, repo, path, options); + git_blame* ptr; + int res = NativeMethods.git_blame_file(out ptr, repo, path, options); Ensure.ZeroResult(res); - return handle; - } - - public static GitBlameHunk git_blame_get_hunk_byindex(BlameSafeHandle blame, uint idx) - { - return NativeMethods.git_blame_get_hunk_byindex(blame, idx).MarshalAs(false); + return new BlameHandle(ptr, true); } - public static void git_blame_free(IntPtr blame) + public static unsafe git_blame_hunk* git_blame_get_hunk_byindex(BlameHandle blame, uint idx) { - NativeMethods.git_blame_free(blame); + return NativeMethods.git_blame_get_hunk_byindex(blame, idx); } #endregion @@ -844,7 +839,7 @@ public static void git_filter_unregister(string name) Ensure.ZeroResult(res); } - public static FilterMode git_filter_source_mode(IntPtr filterSource) + public static unsafe FilterMode git_filter_source_mode(git_filter_source* filterSource) { var res = NativeMethods.git_filter_source_mode(filterSource); return (FilterMode)res; @@ -1465,14 +1460,17 @@ public static GitObjectMetadata git_odb_read_header(ObjectDatabaseSafeHandle odb return new GitObjectMetadata((long)length, objectType); } - public static ICollection git_odb_foreach( - ObjectDatabaseSafeHandle odb, - Func resultSelector) + public static unsafe ICollection git_odb_foreach(ObjectDatabaseSafeHandle odb) { - return git_foreach(resultSelector, - c => NativeMethods.git_odb_foreach(odb, - (x, p) => c(x, p), - IntPtr.Zero)); + var list = new List(); + + NativeMethods.git_odb_foreach(odb, (p, _data) => + { + list.Add(ObjectId.BuildFromPtr(p)); + return 0; + }, IntPtr.Zero); + + return list; } public static OdbStreamSafeHandle git_odb_open_wstream(ObjectDatabaseSafeHandle odb, long size, GitObjectType type) @@ -1680,15 +1678,12 @@ private static UIntPtr GIT_REBASE_NO_OPERATION public const long RebaseNoOperation = -1; - public static GitRebaseOperation git_rebase_operation_byindex( + public static unsafe git_rebase_operation* git_rebase_operation_byindex( RebaseSafeHandle rebase, long index) { Debug.Assert(index >= 0); - IntPtr ptr = NativeMethods.git_rebase_operation_byindex(rebase, ((UIntPtr)index)); - GitRebaseOperation operation = ptr.MarshalAs(); - - return operation; + return NativeMethods.git_rebase_operation_byindex(rebase, ((UIntPtr)index)); } /// @@ -1696,10 +1691,9 @@ public static GitRebaseOperation git_rebase_operation_byindex( /// /// /// - public static GitRebaseOperation git_rebase_next(RebaseSafeHandle rebase) + public static unsafe git_rebase_operation* git_rebase_next(RebaseSafeHandle rebase) { - GitRebaseOperation operation = null; - IntPtr ptr; + git_rebase_operation* ptr; int result = NativeMethods.git_rebase_next(out ptr, rebase); if (result == (int)GitErrorCode.IterOver) { @@ -1707,10 +1701,7 @@ public static GitRebaseOperation git_rebase_next(RebaseSafeHandle rebase) } Ensure.ZeroResult(result); - // If successsful, then marshal native struct to managed struct. - operation = ptr.MarshalAs(); - - return operation; + return ptr; } public static unsafe GitRebaseCommitResult git_rebase_commit( diff --git a/LibGit2Sharp/FilterSource.cs b/LibGit2Sharp/FilterSource.cs index 0843e6221..ed551aba8 100644 --- a/LibGit2Sharp/FilterSource.cs +++ b/LibGit2Sharp/FilterSource.cs @@ -13,12 +13,12 @@ public class FilterSource /// protected FilterSource() { } - internal FilterSource(FilePath path, FilterMode mode, GitFilterSource source) + internal unsafe FilterSource(FilePath path, FilterMode mode, git_filter_source* source) { SourceMode = mode; - ObjectId = new ObjectId(source.oid); + ObjectId = ObjectId.BuildFromPtr(&source->oid); Path = path.Native; - Root = Proxy.git_repository_workdir(source.repository).Native; + Root = Proxy.git_repository_workdir(new IntPtr(source->repository)).Native; } /// @@ -26,12 +26,21 @@ internal FilterSource(FilePath path, FilterMode mode, GitFilterSource source) /// /// /// - internal static FilterSource FromNativePtr(IntPtr ptr) + internal static unsafe FilterSource FromNativePtr(IntPtr ptr) { - var source = ptr.MarshalAs(); - FilePath path = LaxFilePathMarshaler.FromNative(source.path) ?? FilePath.Empty; + return FromNativePtr((git_filter_source*) ptr.ToPointer()); + } + + /// + /// Take an unmanaged pointer and convert it to filter source callback paramater + /// + /// + /// + internal static unsafe FilterSource FromNativePtr(git_filter_source* ptr) + { + FilePath path = LaxFilePathMarshaler.FromNative(ptr->path) ?? FilePath.Empty; FilterMode gitFilterSourceMode = Proxy.git_filter_source_mode(ptr); - return new FilterSource(path, gitFilterSourceMode, source); + return new FilterSource(path, gitFilterSourceMode, ptr); } /// diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 00ab721d3..85a01a3bf 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -109,7 +109,6 @@ - @@ -144,7 +143,6 @@ - diff --git a/LibGit2Sharp/ObjectDatabase.cs b/LibGit2Sharp/ObjectDatabase.cs index 0adb09afd..5c953eddd 100644 --- a/LibGit2Sharp/ObjectDatabase.cs +++ b/LibGit2Sharp/ObjectDatabase.cs @@ -41,11 +41,10 @@ internal ObjectDatabase(Repository repo) /// An object that can be used to iterate through the collection. public virtual IEnumerator GetEnumerator() { - ICollection oids = Proxy.git_odb_foreach(handle, - ptr => ptr.MarshalAs()); + ICollection oids = Proxy.git_odb_foreach(handle); return oids - .Select(gitOid => repo.Lookup(new ObjectId(gitOid))) + .Select(gitOid => repo.Lookup(gitOid)) .GetEnumerator(); } diff --git a/LibGit2Sharp/ObjectId.cs b/LibGit2Sharp/ObjectId.cs index 12051d066..c04100fe9 100644 --- a/LibGit2Sharp/ObjectId.cs +++ b/LibGit2Sharp/ObjectId.cs @@ -57,6 +57,11 @@ public ObjectId(byte[] rawId) Ensure.ArgumentConformsTo(rawId, b => b.Length == rawSize, "rawId"); } + internal static unsafe ObjectId BuildFromPtr(IntPtr ptr) + { + return BuildFromPtr((git_oid*) ptr.ToPointer()); + } + internal static unsafe ObjectId BuildFromPtr(git_oid* id) { return id == null ? null : new ObjectId(id->Id); diff --git a/LibGit2Sharp/PushUpdate.cs b/LibGit2Sharp/PushUpdate.cs index 8e7ac5ccd..bbabb6817 100644 --- a/LibGit2Sharp/PushUpdate.cs +++ b/LibGit2Sharp/PushUpdate.cs @@ -15,12 +15,13 @@ internal PushUpdate(string srcRefName, ObjectId srcOid, string dstRefName, Objec SourceObjectId = srcOid; SourceRefName = srcRefName; } - internal PushUpdate(GitPushUpdate update) + + internal unsafe PushUpdate(git_push_update* update) { - DestinationObjectId = update.dst; - DestinationRefName = LaxUtf8Marshaler.FromNative(update.dst_refname); - SourceObjectId = update.src; - SourceRefName = LaxUtf8Marshaler.FromNative(update.src_refname); + DestinationObjectId = ObjectId.BuildFromPtr(&update->dst); + DestinationRefName = LaxUtf8Marshaler.FromNative(update->dst_refname); + SourceObjectId = ObjectId.BuildFromPtr(&update->src); + SourceRefName = LaxUtf8Marshaler.FromNative(update->src_refname); } /// /// Empty constructor to support test suites diff --git a/LibGit2Sharp/Rebase.cs b/LibGit2Sharp/Rebase.cs index a7ea050d1..26e67335d 100644 --- a/LibGit2Sharp/Rebase.cs +++ b/LibGit2Sharp/Rebase.cs @@ -134,7 +134,7 @@ public virtual RebaseResult Start(Branch branch, Branch upstream, Branch onto, I /// /// The of who added the change to the repository. /// The that specify the rebase behavior. - public virtual RebaseResult Continue(Identity committer, RebaseOptions options) + public virtual unsafe RebaseResult Continue(Identity committer, RebaseOptions options) { Ensure.ArgumentNotNull(committer, "committer"); @@ -163,11 +163,11 @@ public virtual RebaseResult Continue(Identity committer, RebaseOptions options) // Get information on the current step long currentStepIndex = Proxy.git_rebase_operation_current(rebase); long totalStepCount = Proxy.git_rebase_operation_entrycount(rebase); - GitRebaseOperation gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebase, currentStepIndex); + git_rebase_operation* gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebase, currentStepIndex); - var stepInfo = new RebaseStepInfo(gitRebasestepInfo.type, - repository.Lookup(new ObjectId(gitRebasestepInfo.id)), - LaxUtf8NoCleanupMarshaler.FromNative(gitRebasestepInfo.exec)); + var stepInfo = new RebaseStepInfo(gitRebasestepInfo->type, + repository.Lookup(ObjectId.BuildFromPtr(&gitRebasestepInfo->id)), + LaxUtf8NoCleanupMarshaler.FromNative(gitRebasestepInfo->exec)); if (rebaseCommitResult.WasPatchAlreadyApplied) { @@ -223,7 +223,7 @@ public virtual void Abort(RebaseOptions options) /// /// The info on the current step. /// - public virtual RebaseStepInfo GetCurrentStepInfo() + public virtual unsafe RebaseStepInfo GetCurrentStepInfo() { if (repository.Info.CurrentOperation != LibGit2Sharp.CurrentOperation.RebaseMerge) { @@ -238,10 +238,10 @@ public virtual RebaseStepInfo GetCurrentStepInfo() using (RebaseSafeHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { long currentStepIndex = Proxy.git_rebase_operation_current(rebaseHandle); - GitRebaseOperation gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, currentStepIndex); - var stepInfo = new RebaseStepInfo(gitRebasestepInfo.type, - repository.Lookup(new ObjectId(gitRebasestepInfo.id)), - LaxUtf8Marshaler.FromNative(gitRebasestepInfo.exec)); + git_rebase_operation* gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, currentStepIndex); + var stepInfo = new RebaseStepInfo(gitRebasestepInfo->type, + repository.Lookup(ObjectId.BuildFromPtr(&gitRebasestepInfo->id)), + LaxUtf8Marshaler.FromNative(gitRebasestepInfo->exec)); return stepInfo; } } @@ -251,7 +251,7 @@ public virtual RebaseStepInfo GetCurrentStepInfo() /// /// /// - public virtual RebaseStepInfo GetStepInfo(long stepIndex) + public virtual unsafe RebaseStepInfo GetStepInfo(long stepIndex) { if (repository.Info.CurrentOperation != LibGit2Sharp.CurrentOperation.RebaseMerge) { @@ -265,10 +265,10 @@ public virtual RebaseStepInfo GetStepInfo(long stepIndex) using (RebaseSafeHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { - GitRebaseOperation gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, stepIndex); - var stepInfo = new RebaseStepInfo(gitRebasestepInfo.type, - repository.Lookup(new ObjectId(gitRebasestepInfo.id)), - LaxUtf8Marshaler.FromNative(gitRebasestepInfo.exec)); + git_rebase_operation* gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, stepIndex); + var stepInfo = new RebaseStepInfo(gitRebasestepInfo->type, + repository.Lookup(ObjectId.BuildFromPtr(&gitRebasestepInfo->id)), + LaxUtf8Marshaler.FromNative(gitRebasestepInfo->exec)); return stepInfo; } } diff --git a/LibGit2Sharp/RebaseOperationImpl.cs b/LibGit2Sharp/RebaseOperationImpl.cs index abb4537c3..f7d9e539f 100644 --- a/LibGit2Sharp/RebaseOperationImpl.cs +++ b/LibGit2Sharp/RebaseOperationImpl.cs @@ -74,7 +74,7 @@ private static RebaseResult CompleteRebase(RebaseSafeHandle rebaseOperationHandl /// /// /// - private static RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperationHandle, + private static unsafe RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperationHandle, Repository repository, Identity committer, RebaseOptions options, @@ -84,12 +84,12 @@ private static RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperationHandle RebaseStepResult rebaseStepResult = null; RebaseResult rebaseSequenceResult = null; - GitRebaseOperation rebaseOp = Proxy.git_rebase_operation_byindex(rebaseOperationHandle, stepToApplyIndex); - ObjectId idOfCommitBeingRebased = new ObjectId(rebaseOp.id); + git_rebase_operation* rebaseOp = Proxy.git_rebase_operation_byindex(rebaseOperationHandle, stepToApplyIndex); + ObjectId idOfCommitBeingRebased = ObjectId.BuildFromPtr(&rebaseOp->id); - RebaseStepInfo stepToApplyInfo = new RebaseStepInfo(rebaseOp.type, + RebaseStepInfo stepToApplyInfo = new RebaseStepInfo(rebaseOp->type, repository.Lookup(idOfCommitBeingRebased), - LaxUtf8NoCleanupMarshaler.FromNative(rebaseOp.exec)); + LaxUtf8NoCleanupMarshaler.FromNative(rebaseOp->exec)); // Report the rebase step we are about to perform. if (options.RebaseStepStarting != null) @@ -98,7 +98,7 @@ private static RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperationHandle } // Perform the rebase step - GitRebaseOperation rebaseOpReport = Proxy.git_rebase_next(rebaseOperationHandle); + git_rebase_operation* rebaseOpReport = Proxy.git_rebase_next(rebaseOperationHandle); // Verify that the information from the native library is consistent. VerifyRebaseOp(rebaseOpReport, stepToApplyInfo); @@ -184,13 +184,13 @@ private static RebaseStepResult ApplyPickStep(RebaseSafeHandle rebaseOperationHa /// /// /// - private static void VerifyRebaseOp(GitRebaseOperation rebaseOpReport, RebaseStepInfo stepInfo) + private static unsafe void VerifyRebaseOp(git_rebase_operation* rebaseOpReport, RebaseStepInfo stepInfo) { // The step reported via querying by index and the step returned from git_rebase_next // should be the same if (rebaseOpReport == null || - new ObjectId(rebaseOpReport.id) != stepInfo.Commit.Id || - rebaseOpReport.type != stepInfo.Type) + ObjectId.BuildFromPtr(&rebaseOpReport->id) != stepInfo.Commit.Id || + rebaseOpReport->type != stepInfo.Type) { // This is indicative of a program error - should never happen. throw new LibGit2SharpException("Unexpected step info reported by running rebase step."); diff --git a/LibGit2Sharp/RemoteCallbacks.cs b/LibGit2Sharp/RemoteCallbacks.cs index 42037a22e..b3bd512b5 100644 --- a/LibGit2Sharp/RemoteCallbacks.cs +++ b/LibGit2Sharp/RemoteCallbacks.cs @@ -97,7 +97,7 @@ internal RemoteCallbacks(FetchOptionsBase fetchOptions) /// private readonly CertificateCheckHandler CertificateCheck; - internal GitRemoteCallbacks GenerateCallbacks() + internal unsafe GitRemoteCallbacks GenerateCallbacks() { var callbacks = new GitRemoteCallbacks { version = 1 }; @@ -290,19 +290,18 @@ private int GitCredentialHandler( return cred.GitCredentialHandler(out ptr); } - private int GitCertificateCheck(IntPtr certPtr, int valid, IntPtr cHostname, IntPtr payload) + private unsafe int GitCertificateCheck(git_certificate* certPtr, int valid, IntPtr cHostname, IntPtr payload) { string hostname = LaxUtf8Marshaler.FromNative(cHostname); - GitCertificate baseCert = certPtr.MarshalAs(); Certificate cert = null; - switch (baseCert.type) + switch (certPtr->type) { case GitCertificateType.X509: - cert = new CertificateX509(certPtr.MarshalAs()); + cert = new CertificateX509((git_certificate_x509*) certPtr); break; case GitCertificateType.Hostkey: - cert = new CertificateSsh(certPtr.MarshalAs()); + cert = new CertificateSsh((git_certificate_ssh*) certPtr); break; } @@ -344,8 +343,7 @@ private int GitPushNegotiationHandler(IntPtr updates, UIntPtr len, IntPtr payloa throw new NullReferenceException("Unexpected null git_push_update pointer was encountered"); } - GitPushUpdate gitPushUpdate = ptr[i].MarshalAs(); - PushUpdate pushUpdate = new PushUpdate(gitPushUpdate); + PushUpdate pushUpdate = new PushUpdate((git_push_update*) ptr[i].ToPointer()); pushUpdates[i] = pushUpdate; } From 57a9183b6162fce97895ef255693d7cc305c74ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 15 Jan 2016 05:50:49 +0100 Subject: [PATCH 23/50] fixup! Move git_reference to the template --- LibGit2Sharp/LibGit2Sharp.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 85a01a3bf..010e7fad5 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -23,6 +23,7 @@ TRACE;DEBUG;NET40 prompt 4 + false true AllRules.ruleset bin\Debug\LibGit2Sharp.xml @@ -35,6 +36,7 @@ prompt 4 true + false bin\Release\LibGit2Sharp.xml From 1d5b5f581f739a0a9b9d2d34434636e19695cd8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 15 Jan 2016 06:04:50 +0100 Subject: [PATCH 24/50] Get rid of DiffSafeHandle and PatchSafeHandle --- LibGit2Sharp/Core/Handles/DiffSafeHandle.cs | 11 -- LibGit2Sharp/Core/Handles/Objects.cs | 138 +++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 4 + LibGit2Sharp/Core/Handles/PatchSafeHandle.cs | 11 -- LibGit2Sharp/Core/NativeMethods.cs | 38 ++--- LibGit2Sharp/Core/Opaques.cs | 2 + LibGit2Sharp/Core/Proxy.cs | 56 ++++---- LibGit2Sharp/Diff.cs | 22 +-- LibGit2Sharp/LibGit2Sharp.csproj | 2 - LibGit2Sharp/Patch.cs | 2 +- LibGit2Sharp/PatchStats.cs | 2 +- LibGit2Sharp/TreeChanges.cs | 2 +- 12 files changed, 200 insertions(+), 90 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/DiffSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/PatchSafeHandle.cs diff --git a/LibGit2Sharp/Core/Handles/DiffSafeHandle.cs b/LibGit2Sharp/Core/Handles/DiffSafeHandle.cs deleted file mode 100644 index fe117cba1..000000000 --- a/LibGit2Sharp/Core/Handles/DiffSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class DiffSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_diff_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index c1a4619e3..e35240ae6 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -418,4 +418,142 @@ public void Dispose() } } + internal unsafe class DiffHandle : IDisposable + { + git_diff* ptr; + internal git_diff* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe DiffHandle(git_diff* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe DiffHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_diff*) ptr.ToPointer(); + this.owned = owned; + } + + ~DiffHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_diff_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_diff*(DiffHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class PatchHandle : IDisposable + { + git_patch* ptr; + internal git_patch* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe PatchHandle(git_patch* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe PatchHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_patch*) ptr.ToPointer(); + this.owned = owned; + } + + ~PatchHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_patch_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_patch*(PatchHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 5e573a228..82e40790e 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -18,6 +18,8 @@ var cNames = new[] { "git_signature", "git_status_list", "git_blame", + "git_diff", + "git_patch", }; var csNames = new[] { @@ -27,6 +29,8 @@ var csNames = new[] { "SignatureHandle", "StatusListHandle", "BlameHandle", + "DiffHandle", + "PatchHandle" }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/Handles/PatchSafeHandle.cs b/LibGit2Sharp/Core/Handles/PatchSafeHandle.cs deleted file mode 100644 index 97c0dc9bb..000000000 --- a/LibGit2Sharp/Core/Handles/PatchSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class PatchSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_patch_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 54f068856..f9096c99d 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -475,11 +475,11 @@ internal static extern int git_describe_format( internal static extern void git_describe_result_free(IntPtr describe); [DllImport(libgit2)] - internal static extern void git_diff_free(IntPtr diff); + internal static extern unsafe void git_diff_free(git_diff* diff); [DllImport(libgit2)] internal static extern unsafe int git_diff_tree_to_tree( - out DiffSafeHandle diff, + out git_diff* diff, git_repository* repo, GitObjectSafeHandle oldTree, GitObjectSafeHandle newTree, @@ -487,27 +487,27 @@ internal static extern unsafe int git_diff_tree_to_tree( [DllImport(libgit2)] internal static extern unsafe int git_diff_tree_to_index( - out DiffSafeHandle diff, + out git_diff* diff, git_repository* repo, GitObjectSafeHandle oldTree, IndexSafeHandle index, GitDiffOptions options); [DllImport(libgit2)] - internal static extern int git_diff_merge( - DiffSafeHandle onto, - DiffSafeHandle from); + internal static extern unsafe int git_diff_merge( + git_diff* onto, + git_diff* from); [DllImport(libgit2)] internal static extern unsafe int git_diff_index_to_workdir( - out DiffSafeHandle diff, + out git_diff* diff, git_repository* repo, IndexSafeHandle index, GitDiffOptions options); [DllImport(libgit2)] internal static extern unsafe int git_diff_tree_to_workdir( - out DiffSafeHandle diff, + out git_diff* diff, git_repository* repo, GitObjectSafeHandle oldTree, GitDiffOptions options); @@ -547,8 +547,8 @@ internal static extern int git_diff_blobs( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_diff_foreach( - DiffSafeHandle diff, + internal static extern unsafe int git_diff_foreach( + git_diff* diff, git_diff_file_cb fileCallback, git_diff_binary_cb binaryCallback, git_diff_hunk_cb hunkCallback, @@ -556,15 +556,15 @@ internal static extern int git_diff_foreach( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_diff_find_similar( - DiffSafeHandle diff, + internal static extern unsafe int git_diff_find_similar( + git_diff* diff, GitDiffFindOptions options); [DllImport(libgit2)] - internal static extern UIntPtr git_diff_num_deltas(DiffSafeHandle diff); + internal static extern unsafe UIntPtr git_diff_num_deltas(git_diff* diff); [DllImport(libgit2)] - internal static extern unsafe git_diff_delta* git_diff_get_delta(DiffSafeHandle diff, UIntPtr idx); + internal static extern unsafe git_diff_delta* git_diff_get_delta(git_diff* diff, UIntPtr idx); [DllImport(libgit2)] internal static extern int git_filter_register( @@ -919,20 +919,20 @@ internal static extern int git_object_short_id( internal static extern GitObjectType git_object_type(GitObjectSafeHandle obj); [DllImport(libgit2)] - internal static extern int git_patch_from_diff(out PatchSafeHandle patch, DiffSafeHandle diff, UIntPtr idx); + internal static extern unsafe int git_patch_from_diff(out git_patch* patch, git_diff* diff, UIntPtr idx); [DllImport(libgit2)] - internal static extern int git_patch_print(PatchSafeHandle patch, git_diff_line_cb print_cb, IntPtr payload); + internal static extern unsafe int git_patch_print(git_patch* patch, git_diff_line_cb print_cb, IntPtr payload); [DllImport(libgit2)] - internal static extern int git_patch_line_stats( + internal static extern unsafe int git_patch_line_stats( out UIntPtr total_context, out UIntPtr total_additions, out UIntPtr total_deletions, - PatchSafeHandle patch); + git_patch* patch); [DllImport(libgit2)] - internal static extern void git_patch_free(IntPtr patch); + internal static extern unsafe void git_patch_free(git_patch* patch); /* Push network progress notification function */ internal delegate int git_push_transfer_progress(uint current, uint total, UIntPtr bytes, IntPtr payload); diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index 312d1ef92..fc67337ce 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -8,5 +8,7 @@ internal struct git_refspec {} internal struct git_repository {} internal struct git_status_list {} internal struct git_blame {} + internal struct git_diff {} + internal struct git_patch {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 42804408c..adf7ac8b5 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -722,8 +722,8 @@ public static void git_diff_blobs( } } - public static void git_diff_foreach( - DiffSafeHandle diff, + public static unsafe void git_diff_foreach( + git_diff* diff, NativeMethods.git_diff_file_cb fileCallback, NativeMethods.git_diff_hunk_cb hunkCallback, NativeMethods.git_diff_line_cb lineCallback) @@ -732,7 +732,7 @@ public static void git_diff_foreach( Ensure.ZeroResult(res); } - public static unsafe DiffSafeHandle git_diff_tree_to_index( + public static unsafe DiffHandle git_diff_tree_to_index( RepositoryHandle repo, IndexSafeHandle index, ObjectId oldTree, @@ -740,26 +740,21 @@ public static unsafe DiffSafeHandle git_diff_tree_to_index( { using (var osw = new ObjectSafeWrapper(oldTree, repo, true)) { - DiffSafeHandle diff; + git_diff* diff; int res = NativeMethods.git_diff_tree_to_index(out diff, repo, osw.ObjectPtr, index, options); Ensure.ZeroResult(res); - return diff; + return new DiffHandle(diff, true); } } - public static void git_diff_free(IntPtr diff) - { - NativeMethods.git_diff_free(diff); - } - - public static void git_diff_merge(DiffSafeHandle onto, DiffSafeHandle from) + public static unsafe void git_diff_merge(DiffHandle onto, DiffHandle from) { int res = NativeMethods.git_diff_merge(onto, from); Ensure.ZeroResult(res); } - public static unsafe DiffSafeHandle git_diff_tree_to_tree( + public static unsafe DiffHandle git_diff_tree_to_tree( RepositoryHandle repo, ObjectId oldTree, ObjectId newTree, @@ -768,53 +763,53 @@ public static unsafe DiffSafeHandle git_diff_tree_to_tree( using (var osw1 = new ObjectSafeWrapper(oldTree, repo, true)) using (var osw2 = new ObjectSafeWrapper(newTree, repo, true)) { - DiffSafeHandle diff; + git_diff* diff; int res = NativeMethods.git_diff_tree_to_tree(out diff, repo, osw1.ObjectPtr, osw2.ObjectPtr, options); Ensure.ZeroResult(res); - return diff; + return new DiffHandle(diff, true); } } - public static unsafe DiffSafeHandle git_diff_index_to_workdir( + public static unsafe DiffHandle git_diff_index_to_workdir( RepositoryHandle repo, IndexSafeHandle index, GitDiffOptions options) { - DiffSafeHandle diff; + git_diff* diff; int res = NativeMethods.git_diff_index_to_workdir(out diff, repo, index, options); Ensure.ZeroResult(res); - return diff; + return new DiffHandle(diff, true); } - public static unsafe DiffSafeHandle git_diff_tree_to_workdir( + public static unsafe DiffHandle git_diff_tree_to_workdir( RepositoryHandle repo, ObjectId oldTree, GitDiffOptions options) { using (var osw = new ObjectSafeWrapper(oldTree, repo, true)) { - DiffSafeHandle diff; + git_diff* diff; int res = NativeMethods.git_diff_tree_to_workdir(out diff, repo, osw.ObjectPtr, options); Ensure.ZeroResult(res); - return diff; + return new DiffHandle(diff, true); } } - public static void git_diff_find_similar(DiffSafeHandle diff, GitDiffFindOptions options) + public static unsafe void git_diff_find_similar(DiffHandle diff, GitDiffFindOptions options) { int res = NativeMethods.git_diff_find_similar(diff, options); Ensure.ZeroResult(res); } - public static int git_diff_num_deltas(DiffSafeHandle diff) + public static unsafe int git_diff_num_deltas(DiffHandle diff) { return (int)NativeMethods.git_diff_num_deltas(diff); } - public static unsafe git_diff_delta* git_diff_get_delta(DiffSafeHandle diff, int idx) + public static unsafe git_diff_delta* git_diff_get_delta(DiffHandle diff, int idx) { return NativeMethods.git_diff_get_delta(diff, (UIntPtr)idx); } @@ -1519,26 +1514,21 @@ public static void git_odb_stream_free(IntPtr stream) #region git_patch_ - public static void git_patch_free(IntPtr patch) + public static unsafe PatchHandle git_patch_from_diff(DiffHandle diff, int idx) { - NativeMethods.git_patch_free(patch); - } - - public static PatchSafeHandle git_patch_from_diff(DiffSafeHandle diff, int idx) - { - PatchSafeHandle handle; + git_patch* handle; int res = NativeMethods.git_patch_from_diff(out handle, diff, (UIntPtr)idx); Ensure.ZeroResult(res); - return handle; + return new PatchHandle(handle, true); } - public static void git_patch_print(PatchSafeHandle patch, NativeMethods.git_diff_line_cb printCallback) + public static unsafe void git_patch_print(PatchHandle patch, NativeMethods.git_diff_line_cb printCallback) { int res = NativeMethods.git_patch_print(patch, printCallback, IntPtr.Zero); Ensure.ZeroResult(res); } - public static Tuple git_patch_line_stats(PatchSafeHandle patch) + public static unsafe Tuple git_patch_line_stats(PatchHandle patch) { UIntPtr ctx, add, del; int res = NativeMethods.git_patch_line_stats(out ctx, out add, out del, patch); diff --git a/LibGit2Sharp/Diff.cs b/LibGit2Sharp/Diff.cs index 88c1fdcfc..8d902c15e 100644 --- a/LibGit2Sharp/Diff.cs +++ b/LibGit2Sharp/Diff.cs @@ -99,7 +99,7 @@ private static IDictionary> ChangesBuilders = new Dictionary> + private static readonly IDictionary> ChangesBuilders = new Dictionary> { { typeof(Patch), diff => new Patch(diff) }, { typeof(TreeChanges), diff => new TreeChanges(diff) }, @@ -107,9 +107,9 @@ private static IDictionary(DiffSafeHandle diff) where T : class, IDiffResult + private static T BuildDiffResult(DiffHandle diff) where T : class, IDiffResult { - Func builder; + Func builder; if (!ChangesBuilders.TryGetValue(typeof(T), out builder)) { @@ -241,7 +241,7 @@ public virtual T Compare(Tree oldTree, Tree newTree, IEnumerable path } } - using (DiffSafeHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) + using (DiffHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return BuildDiffResult(diff); } @@ -343,7 +343,7 @@ public virtual T Compare(Tree oldTree, DiffTargets diffTargets, IEnumerable(diff); } @@ -462,13 +462,13 @@ internal virtual T Compare( } } - using (DiffSafeHandle diff = BuildDiffList(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) + using (DiffHandle diff = BuildDiffList(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return BuildDiffResult(diff); } } - internal delegate DiffSafeHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options); + internal delegate DiffHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options); private static TreeComparisonHandleRetriever TreeToTree(Repository repo) { @@ -489,9 +489,9 @@ private static TreeComparisonHandleRetriever WorkdirAndIndexToTree(Repository re { TreeComparisonHandleRetriever comparisonHandleRetriever = (oh, nh, o) => { - DiffSafeHandle diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); + DiffHandle diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); - using (DiffSafeHandle diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o)) + using (DiffHandle diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o)) { Proxy.git_diff_merge(diff, diff2); } @@ -507,7 +507,7 @@ private static TreeComparisonHandleRetriever IndexToTree(Repository repo) return (oh, nh, o) => Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); } - private DiffSafeHandle BuildDiffList( + private DiffHandle BuildDiffList( ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever, @@ -542,7 +542,7 @@ private DiffSafeHandle BuildDiffList( } } - private static void DetectRenames(DiffSafeHandle diffList, CompareOptions compareOptions) + private static void DetectRenames(DiffHandle diffList, CompareOptions compareOptions) { var similarityOptions = (compareOptions == null) ? null : compareOptions.Similarity; if (similarityOptions == null || similarityOptions.RenameDetectionMode == RenameDetectionMode.Default) diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 010e7fad5..af30e0612 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -110,7 +110,6 @@ - @@ -272,7 +271,6 @@ - diff --git a/LibGit2Sharp/Patch.cs b/LibGit2Sharp/Patch.cs index 423ba78e3..dd668eda4 100644 --- a/LibGit2Sharp/Patch.cs +++ b/LibGit2Sharp/Patch.cs @@ -30,7 +30,7 @@ public class Patch : IEnumerable, IDiffResult protected Patch() { } - internal unsafe Patch(DiffSafeHandle diff) + internal unsafe Patch(DiffHandle diff) { int count = Proxy.git_diff_num_deltas(diff); for (int i = 0; i < count; i++) diff --git a/LibGit2Sharp/PatchStats.cs b/LibGit2Sharp/PatchStats.cs index cd03d9ca3..c5404fed5 100644 --- a/LibGit2Sharp/PatchStats.cs +++ b/LibGit2Sharp/PatchStats.cs @@ -25,7 +25,7 @@ public class PatchStats : IEnumerable, IDiffResult protected PatchStats() { } - internal unsafe PatchStats(DiffSafeHandle diff) + internal unsafe PatchStats(DiffHandle diff) { int count = Proxy.git_diff_num_deltas(diff); for (int i = 0; i < count; i++) diff --git a/LibGit2Sharp/TreeChanges.cs b/LibGit2Sharp/TreeChanges.cs index bd81328f6..2e317855a 100644 --- a/LibGit2Sharp/TreeChanges.cs +++ b/LibGit2Sharp/TreeChanges.cs @@ -50,7 +50,7 @@ private static IDictionary> Bu protected TreeChanges() { } - internal unsafe TreeChanges(DiffSafeHandle diff) + internal unsafe TreeChanges(DiffHandle diff) { Proxy.git_diff_foreach(diff, FileCallback, null, null); } From 4b8b026965be4a4b058fa21b3a04935e04d2b877 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 15 Jan 2016 06:24:52 +0100 Subject: [PATCH 25/50] Get rid of Configuration{,Iterator}SafeHandle --- LibGit2Sharp/Configuration.cs | 32 ++++----- .../ConfigurationIteratorSafeHandle.cs | 11 --- .../Core/Handles/ConfigurationSafeHandle.cs | 11 --- LibGit2Sharp/Core/Handles/Objects.cs | 69 +++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 4 +- LibGit2Sharp/Core/NativeMethods.cs | 56 +++++++-------- LibGit2Sharp/Core/Opaques.cs | 1 + LibGit2Sharp/Core/Proxy.cs | 62 ++++++++--------- LibGit2Sharp/LibGit2Sharp.csproj | 2 - 9 files changed, 145 insertions(+), 103 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/ConfigurationIteratorSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/ConfigurationSafeHandle.cs diff --git a/LibGit2Sharp/Configuration.cs b/LibGit2Sharp/Configuration.cs index 95467f7e9..7b1ecdf81 100644 --- a/LibGit2Sharp/Configuration.cs +++ b/LibGit2Sharp/Configuration.cs @@ -20,7 +20,7 @@ public class Configuration : IDisposable, private readonly FilePath xdgConfigPath; private readonly FilePath systemConfigPath; - private ConfigurationSafeHandle configHandle; + private ConfigurationHandle configHandle; /// /// Needed for mocking purposes. @@ -230,8 +230,8 @@ public Configuration(string globalConfigurationFileLocation, string xdgConfigura /// public virtual bool HasConfig(ConfigurationLevel level) { - using (ConfigurationSafeHandle snapshot = Snapshot()) - using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) + using (ConfigurationHandle snapshot = Snapshot()) + using (ConfigurationHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { return handle != null; } @@ -269,7 +269,7 @@ public virtual void Unset(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); - using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle)) + using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_delete(h, key); } @@ -279,7 +279,7 @@ internal void UnsetMultivar(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); - using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle)) + using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_delete_multivar(h, key); } @@ -384,7 +384,7 @@ public virtual ConfigurationEntry Get(string key) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); - using (ConfigurationSafeHandle snapshot = Snapshot()) + using (ConfigurationHandle snapshot = Snapshot()) { return Proxy.git_config_get_entry(snapshot, key); } @@ -415,8 +415,8 @@ public virtual ConfigurationEntry Get(string key, ConfigurationLevel level { Ensure.ArgumentNotNullOrEmptyString(key, "key"); - using (ConfigurationSafeHandle snapshot = Snapshot()) - using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) + using (ConfigurationHandle snapshot = Snapshot()) + using (ConfigurationHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { if (handle == null) { @@ -645,7 +645,7 @@ public virtual void Set(string key, T value, ConfigurationLevel level) Ensure.ArgumentNotNull(value, "value"); Ensure.ArgumentNotNullOrEmptyString(key, "key"); - using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle)) + using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { if (!configurationTypedUpdater.ContainsKey(typeof(T))) { @@ -676,16 +676,16 @@ public virtual IEnumerable> Find(string regexp, Confi { Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp"); - using (ConfigurationSafeHandle snapshot = Snapshot()) - using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, snapshot)) + using (ConfigurationHandle snapshot = Snapshot()) + using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, snapshot)) { return Proxy.git_config_iterator_glob(h, regexp).ToList(); } } - private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationSafeHandle fromHandle) + private ConfigurationHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationHandle fromHandle) { - ConfigurationSafeHandle handle = null; + ConfigurationHandle handle = null; if (fromHandle != null) { handle = Proxy.git_config_open_level(fromHandle, level); @@ -700,12 +700,12 @@ private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel l return handle; } - private static Action GetUpdater(Action setter) + private static Action GetUpdater(Action setter) { return (key, val, handle) => setter(handle, key, (T)val); } - private readonly static IDictionary> configurationTypedUpdater = new Dictionary> + private readonly static IDictionary> configurationTypedUpdater = new Dictionary> { { typeof(int), GetUpdater(Proxy.git_config_set_int32) }, { typeof(long), GetUpdater(Proxy.git_config_set_int64) }, @@ -778,7 +778,7 @@ internal Signature BuildSignatureOrThrow(DateTimeOffset now) return signature; } - private ConfigurationSafeHandle Snapshot() + private ConfigurationHandle Snapshot() { return Proxy.git_config_snapshot(configHandle); } diff --git a/LibGit2Sharp/Core/Handles/ConfigurationIteratorSafeHandle.cs b/LibGit2Sharp/Core/Handles/ConfigurationIteratorSafeHandle.cs deleted file mode 100644 index 0d2cb6ab6..000000000 --- a/LibGit2Sharp/Core/Handles/ConfigurationIteratorSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class ConfigurationIteratorSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_config_iterator_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/ConfigurationSafeHandle.cs b/LibGit2Sharp/Core/Handles/ConfigurationSafeHandle.cs deleted file mode 100644 index 01b2a4c9d..000000000 --- a/LibGit2Sharp/Core/Handles/ConfigurationSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class ConfigurationSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_config_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index e35240ae6..f971fb4d0 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -556,4 +556,73 @@ public void Dispose() } } + internal unsafe class ConfigurationHandle : IDisposable + { + git_config* ptr; + internal git_config* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe ConfigurationHandle(git_config* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe ConfigurationHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_config*) ptr.ToPointer(); + this.owned = owned; + } + + ~ConfigurationHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_config_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_config*(ConfigurationHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 82e40790e..68f718d2b 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -20,6 +20,7 @@ var cNames = new[] { "git_blame", "git_diff", "git_patch", + "git_config", }; var csNames = new[] { @@ -30,7 +31,8 @@ var csNames = new[] { "StatusListHandle", "BlameHandle", "DiffHandle", - "PatchHandle" + "PatchHandle", + "ConfigurationHandle", }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index f9096c99d..de82e229c 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -325,13 +325,13 @@ internal static extern unsafe int git_commit_create_from_ids( internal static extern unsafe git_oid* git_commit_tree_id(GitObjectSafeHandle commit); [DllImport(libgit2)] - internal static extern int git_config_delete_entry( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_delete_entry( + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern int git_config_delete_multivar( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_delete_multivar( + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string regexp); @@ -345,7 +345,7 @@ internal static extern int git_config_delete_multivar( internal static extern int git_config_find_xdg(GitBuf xdg_config_path); [DllImport(libgit2)] - internal static extern void git_config_free(IntPtr cfg); + internal static extern unsafe void git_config_free(git_config* cfg); [DllImport(libgit2)] internal static extern unsafe void git_config_entry_free(GitConfigEntry* entry); @@ -353,23 +353,23 @@ internal static extern int git_config_delete_multivar( [DllImport(libgit2)] internal static extern unsafe int git_config_get_entry( out GitConfigEntry* entry, - ConfigurationSafeHandle cfg, + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern int git_config_add_file_ondisk( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_add_file_ondisk( + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, uint level, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] - internal static extern int git_config_new(out ConfigurationSafeHandle cfg); + internal static extern unsafe int git_config_new(out git_config* cfg); [DllImport(libgit2)] - internal static extern int git_config_open_level( - out ConfigurationSafeHandle cfg, - ConfigurationSafeHandle parent, + internal static extern unsafe int git_config_open_level( + out git_config* cfg, + git_config* parent, uint level); [DllImport(libgit2)] @@ -388,26 +388,26 @@ internal static extern int git_config_parse_int64( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string valueToParse); [DllImport(libgit2)] - internal static extern int git_config_set_bool( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_set_bool( + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.Bool)] bool value); [DllImport(libgit2)] - internal static extern int git_config_set_int32( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_set_int32( + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, int value); [DllImport(libgit2)] - internal static extern int git_config_set_int64( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_set_int64( + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, long value); [DllImport(libgit2)] - internal static extern int git_config_set_string( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_set_string( + git_config* cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string value); @@ -416,27 +416,27 @@ internal delegate int config_foreach_callback( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_config_foreach( - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_foreach( + git_config* cfg, config_foreach_callback callback, IntPtr payload); [DllImport(libgit2)] - internal static extern int git_config_iterator_glob_new( - out ConfigurationIteratorSafeHandle iter, - ConfigurationSafeHandle cfg, + internal static extern unsafe int git_config_iterator_glob_new( + out IntPtr iter, + IntPtr cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string regexp); [DllImport(libgit2)] internal static extern int git_config_next( out IntPtr entry, - ConfigurationIteratorSafeHandle iter); + IntPtr iter); [DllImport(libgit2)] internal static extern void git_config_iterator_free(IntPtr iter); [DllImport(libgit2)] - internal static extern int git_config_snapshot(out ConfigurationSafeHandle @out, ConfigurationSafeHandle config); + internal static extern unsafe int git_config_snapshot(out git_config* @out, git_config* config); // Ordinarily we would decorate the `url` parameter with the StrictUtf8Marshaler like we do everywhere // else, but apparently doing a native->managed callback with the 64-bit version of CLR 2.0 can @@ -1376,7 +1376,7 @@ internal static extern unsafe int git_repository_open_ext( [DllImport(libgit2)] internal static extern unsafe void git_repository_set_config( git_repository* repository, - ConfigurationSafeHandle config); + git_config* config); [DllImport(libgit2)] internal static extern unsafe int git_repository_set_ident( diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index fc67337ce..045a35d9e 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -10,5 +10,6 @@ internal struct git_status_list {} internal struct git_blame {} internal struct git_diff {} internal struct git_patch {} + internal struct git_config {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index adf7ac8b5..c0e95ce67 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -430,13 +430,13 @@ public static unsafe ObjectId git_commit_tree_id(GitObjectSafeHandle obj) #region git_config_ - public static void git_config_add_file_ondisk(ConfigurationSafeHandle config, FilePath path, ConfigurationLevel level) + public static unsafe void git_config_add_file_ondisk(ConfigurationHandle config, FilePath path, ConfigurationLevel level) { int res = NativeMethods.git_config_add_file_ondisk(config, path, (uint)level, true); Ensure.ZeroResult(res); } - public static bool git_config_delete(ConfigurationSafeHandle config, string name) + public static unsafe bool git_config_delete(ConfigurationHandle config, string name) { int res = NativeMethods.git_config_delete_entry(config, name); @@ -451,7 +451,7 @@ public static bool git_config_delete(ConfigurationSafeHandle config, string name const string anyValue = ".*"; - public static bool git_config_delete_multivar(ConfigurationSafeHandle config, string name) + public static unsafe bool git_config_delete_multivar(ConfigurationHandle config, string name) { int res = NativeMethods.git_config_delete_multivar(config, name, anyValue); @@ -479,12 +479,7 @@ public static FilePath git_config_find_xdg() return ConvertPath(NativeMethods.git_config_find_xdg); } - public static void git_config_free(IntPtr config) - { - NativeMethods.git_config_free(config); - } - - public static unsafe ConfigurationEntry git_config_get_entry(ConfigurationSafeHandle config, string key) + public static unsafe ConfigurationEntry git_config_get_entry(ConfigurationHandle config, string key) { if (!configurationParser.ContainsKey(typeof(T))) { @@ -511,18 +506,18 @@ public static unsafe ConfigurationEntry git_config_get_entry(Configuration } } - public static ConfigurationSafeHandle git_config_new() + public static unsafe ConfigurationHandle git_config_new() { - ConfigurationSafeHandle handle; + git_config* handle; int res = NativeMethods.git_config_new(out handle); Ensure.ZeroResult(res); - return handle; + return new ConfigurationHandle(handle, true); } - public static ConfigurationSafeHandle git_config_open_level(ConfigurationSafeHandle parent, ConfigurationLevel level) + public static unsafe ConfigurationHandle git_config_open_level(ConfigurationHandle parent, ConfigurationLevel level) { - ConfigurationSafeHandle handle; + git_config* handle; int res = NativeMethods.git_config_open_level(out handle, parent, (uint)level); if (res == (int)GitErrorCode.NotFound) @@ -532,7 +527,7 @@ public static ConfigurationSafeHandle git_config_open_level(ConfigurationSafeHan Ensure.ZeroResult(res); - return handle; + return new ConfigurationHandle(handle, true); } public static bool git_config_parse_bool(string value) @@ -562,45 +557,45 @@ public static long git_config_parse_int64(string value) return outVal; } - public static void git_config_set_bool(ConfigurationSafeHandle config, string name, bool value) + public static unsafe void git_config_set_bool(ConfigurationHandle config, string name, bool value) { int res = NativeMethods.git_config_set_bool(config, name, value); Ensure.ZeroResult(res); } - public static void git_config_set_int32(ConfigurationSafeHandle config, string name, int value) + public static unsafe void git_config_set_int32(ConfigurationHandle config, string name, int value) { int res = NativeMethods.git_config_set_int32(config, name, value); Ensure.ZeroResult(res); } - public static void git_config_set_int64(ConfigurationSafeHandle config, string name, long value) + public static unsafe void git_config_set_int64(ConfigurationHandle config, string name, long value) { int res = NativeMethods.git_config_set_int64(config, name, value); Ensure.ZeroResult(res); } - public static void git_config_set_string(ConfigurationSafeHandle config, string name, string value) + public static unsafe void git_config_set_string(ConfigurationHandle config, string name, string value) { int res = NativeMethods.git_config_set_string(config, name, value); Ensure.ZeroResult(res); } - public static ICollection git_config_foreach( - ConfigurationSafeHandle config, + public static unsafe ICollection git_config_foreach( + ConfigurationHandle config, Func resultSelector) { return git_foreach(resultSelector, c => NativeMethods.git_config_foreach(config, (e, p) => c(e, p), IntPtr.Zero)); } public static IEnumerable> git_config_iterator_glob( - ConfigurationSafeHandle config, + ConfigurationHandle config, string regexp) { - ConfigurationIteratorSafeHandle iter; - var res = NativeMethods.git_config_iterator_glob_new(out iter, config, regexp); + IntPtr iter; + var res = NativeMethods.git_config_iterator_glob_new(out iter, config.AsIntPtr(), regexp); Ensure.ZeroResult(res); - using (iter) + try { while (true) { @@ -615,20 +610,19 @@ public static IEnumerable> git_config_iterator_glob( yield return Configuration.BuildConfigEntry(entry); } } + finally + { + NativeMethods.git_config_iterator_free(iter); + } } - public static void git_config_iterator_free(IntPtr iter) - { - NativeMethods.git_config_iterator_free(iter); - } - - public static ConfigurationSafeHandle git_config_snapshot(ConfigurationSafeHandle config) + public static unsafe ConfigurationHandle git_config_snapshot(ConfigurationHandle config) { - ConfigurationSafeHandle handle; + git_config* handle; int res = NativeMethods.git_config_snapshot(out handle, config); Ensure.ZeroResult(res); - return handle; + return new ConfigurationHandle(handle, true); } #endregion @@ -2478,7 +2472,7 @@ public static unsafe FilePath git_repository_path(RepositoryHandle repo) return NativeMethods.git_repository_path(repo); } - public static unsafe void git_repository_set_config(RepositoryHandle repo, ConfigurationSafeHandle config) + public static unsafe void git_repository_set_config(RepositoryHandle repo, ConfigurationHandle config) { NativeMethods.git_repository_set_config(repo, config); } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index af30e0612..dbe850c85 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -142,7 +142,6 @@ - @@ -286,7 +285,6 @@ - From ec88896b76568732807f713e5344b816fb761e57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 15 Jan 2016 06:40:26 +0100 Subject: [PATCH 26/50] Get rid of ConflictIteratorSafeHandle and {,Null}IndexSafeHandle --- .../Handles/ConflictIteratorSafeHandle.cs | 11 -- LibGit2Sharp/Core/Handles/IndexSafeHandle.cs | 11 -- .../Core/Handles/NullIndexSafeHandle.cs | 18 --- LibGit2Sharp/Core/Handles/Objects.cs | 138 ++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 4 + LibGit2Sharp/Core/NativeMethods.cs | 72 ++++----- LibGit2Sharp/Core/Opaques.cs | 2 + LibGit2Sharp/Core/Proxy.cs | 80 +++++----- LibGit2Sharp/Index.cs | 4 +- LibGit2Sharp/LibGit2Sharp.csproj | 3 - LibGit2Sharp/ObjectDatabase.cs | 2 +- 11 files changed, 218 insertions(+), 127 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/ConflictIteratorSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/IndexSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/NullIndexSafeHandle.cs diff --git a/LibGit2Sharp/Core/Handles/ConflictIteratorSafeHandle.cs b/LibGit2Sharp/Core/Handles/ConflictIteratorSafeHandle.cs deleted file mode 100644 index 255563af5..000000000 --- a/LibGit2Sharp/Core/Handles/ConflictIteratorSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class ConflictIteratorSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_index_conflict_iterator_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/IndexSafeHandle.cs b/LibGit2Sharp/Core/Handles/IndexSafeHandle.cs deleted file mode 100644 index d757efb68..000000000 --- a/LibGit2Sharp/Core/Handles/IndexSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class IndexSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_index_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/NullIndexSafeHandle.cs b/LibGit2Sharp/Core/Handles/NullIndexSafeHandle.cs deleted file mode 100644 index dcd4988fb..000000000 --- a/LibGit2Sharp/Core/Handles/NullIndexSafeHandle.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace LibGit2Sharp.Core.Handles -{ - internal class NullIndexSafeHandle : IndexSafeHandle - { - public NullIndexSafeHandle() - { - handle = IntPtr.Zero; - } - - protected override bool ReleaseHandleImpl() - { - // Nothing to release - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index f971fb4d0..7e0f99e1a 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -625,4 +625,142 @@ public void Dispose() } } + internal unsafe class ConflictIteratorHandle : IDisposable + { + git_index_conflict_iterator* ptr; + internal git_index_conflict_iterator* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe ConflictIteratorHandle(git_index_conflict_iterator* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe ConflictIteratorHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_index_conflict_iterator*) ptr.ToPointer(); + this.owned = owned; + } + + ~ConflictIteratorHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_index_conflict_iterator_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_index_conflict_iterator*(ConflictIteratorHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class IndexHandle : IDisposable + { + git_index* ptr; + internal git_index* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe IndexHandle(git_index* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe IndexHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_index*) ptr.ToPointer(); + this.owned = owned; + } + + ~IndexHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_index_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_index*(IndexHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 68f718d2b..2f3ed311f 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -21,6 +21,8 @@ var cNames = new[] { "git_diff", "git_patch", "git_config", + "git_index_conflict_iterator", + "git_index", }; var csNames = new[] { @@ -33,6 +35,8 @@ var csNames = new[] { "DiffHandle", "PatchHandle", "ConfigurationHandle", + "ConflictIteratorHandle", + "IndexHandle", }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index de82e229c..aa92933ad 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -490,7 +490,7 @@ internal static extern unsafe int git_diff_tree_to_index( out git_diff* diff, git_repository* repo, GitObjectSafeHandle oldTree, - IndexSafeHandle index, + git_index* index, GitDiffOptions options); [DllImport(libgit2)] @@ -502,7 +502,7 @@ internal static extern unsafe int git_diff_merge( internal static extern unsafe int git_diff_index_to_workdir( out git_diff* diff, git_repository* repo, - IndexSafeHandle index, + git_index* index, GitDiffOptions options); [DllImport(libgit2)] @@ -624,13 +624,13 @@ internal static extern unsafe int git_ignore_path_is_ignored( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] - internal static extern int git_index_add_bypath( - IndexSafeHandle index, + internal static extern unsafe int git_index_add_bypath( + git_index* index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern unsafe int git_index_add( - IndexSafeHandle index, + git_index* index, git_index_entry* entry); [DllImport(libgit2)] @@ -638,93 +638,93 @@ internal static extern unsafe int git_index_conflict_get( out git_index_entry* ancestor, out git_index_entry* ours, out git_index_entry* theirs, - IndexSafeHandle index, + git_index* index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] - internal static extern int git_index_conflict_iterator_new( - out ConflictIteratorSafeHandle iterator, - IndexSafeHandle index); + internal static extern unsafe int git_index_conflict_iterator_new( + out git_index_conflict_iterator* iterator, + git_index* index); [DllImport(libgit2)] internal static extern unsafe int git_index_conflict_next( out git_index_entry* ancestor, out git_index_entry* ours, out git_index_entry* theirs, - ConflictIteratorSafeHandle iterator); + git_index_conflict_iterator* iterator); [DllImport(libgit2)] - internal static extern void git_index_conflict_iterator_free( - IntPtr iterator); + internal static extern unsafe void git_index_conflict_iterator_free( + git_index_conflict_iterator* iterator); [DllImport(libgit2)] - internal static extern UIntPtr git_index_entrycount(IndexSafeHandle index); + internal static extern unsafe UIntPtr git_index_entrycount(git_index* index); [DllImport(libgit2)] internal static extern unsafe int git_index_entry_stage(git_index_entry* indexentry); [DllImport(libgit2)] - internal static extern void git_index_free(IntPtr index); + internal static extern unsafe void git_index_free(git_index* index); [DllImport(libgit2)] - internal static extern unsafe git_index_entry* git_index_get_byindex(IndexSafeHandle index, UIntPtr n); + internal static extern unsafe git_index_entry* git_index_get_byindex(git_index* index, UIntPtr n); [DllImport(libgit2)] internal static extern unsafe git_index_entry* git_index_get_bypath( - IndexSafeHandle index, + git_index* index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, int stage); [DllImport(libgit2)] - internal static extern int git_index_has_conflicts(IndexSafeHandle index); + internal static extern unsafe int git_index_has_conflicts(git_index* index); [DllImport(libgit2)] - internal static extern UIntPtr git_index_name_entrycount(IndexSafeHandle handle); + internal static extern unsafe UIntPtr git_index_name_entrycount(git_index* handle); [DllImport(libgit2)] - internal static extern unsafe git_index_name_entry* git_index_name_get_byindex(IndexSafeHandle handle, UIntPtr n); + internal static extern unsafe git_index_name_entry* git_index_name_get_byindex(git_index* handle, UIntPtr n); [DllImport(libgit2)] - internal static extern int git_index_open( - out IndexSafeHandle index, + internal static extern unsafe int git_index_open( + out git_index* index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath indexpath); [DllImport(libgit2)] - internal static extern int git_index_read( - IndexSafeHandle index, + internal static extern unsafe int git_index_read( + git_index* index, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] - internal static extern int git_index_remove_bypath( - IndexSafeHandle index, + internal static extern unsafe int git_index_remove_bypath( + git_index* index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] - internal static extern UIntPtr git_index_reuc_entrycount(IndexSafeHandle handle); + internal static extern unsafe UIntPtr git_index_reuc_entrycount(git_index* handle); [DllImport(libgit2)] - internal static extern unsafe git_index_reuc_entry* git_index_reuc_get_byindex(IndexSafeHandle handle, UIntPtr n); + internal static extern unsafe git_index_reuc_entry* git_index_reuc_get_byindex(git_index* handle, UIntPtr n); [DllImport(libgit2)] internal static extern unsafe git_index_reuc_entry* git_index_reuc_get_bypath( - IndexSafeHandle handle, + git_index* handle, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] - internal static extern int git_index_write(IndexSafeHandle index); + internal static extern unsafe int git_index_write(git_index* index); [DllImport(libgit2)] - internal static extern int git_index_write_tree(out GitOid treeOid, IndexSafeHandle index); + internal static extern unsafe int git_index_write_tree(out GitOid treeOid, git_index* index); [DllImport(libgit2)] - internal static extern unsafe int git_index_write_tree_to(out GitOid treeOid, IndexSafeHandle index, git_repository* repo); + internal static extern unsafe int git_index_write_tree_to(out GitOid treeOid, git_index* index, git_repository* repo); [DllImport(libgit2)] - internal static extern int git_index_read_tree(IndexSafeHandle index, GitObjectSafeHandle tree); + internal static extern unsafe int git_index_read_tree(git_index* index, GitObjectSafeHandle tree); [DllImport(libgit2)] - internal static extern int git_index_clear(IndexSafeHandle index); + internal static extern unsafe int git_index_clear(git_index* index); [DllImport(libgit2)] internal static extern unsafe int git_merge_base_many( @@ -780,7 +780,7 @@ internal static extern unsafe int git_merge( [DllImport(libgit2)] internal static extern unsafe int git_merge_commits( - out IndexSafeHandle index, + out git_index* index, git_repository* repo, GitObjectSafeHandle our_commit, GitObjectSafeHandle their_commit, @@ -1322,7 +1322,7 @@ internal static extern unsafe int git_repository_ident( git_repository* repo); [DllImport(libgit2)] - internal static extern unsafe int git_repository_index(out IndexSafeHandle index, git_repository* repo); + internal static extern unsafe int git_repository_index(out git_index* index, git_repository* repo); [DllImport(libgit2)] internal static extern unsafe int git_repository_init_ext( @@ -1388,7 +1388,7 @@ internal static extern unsafe int git_repository_set_ident( [DllImport(libgit2)] internal static extern unsafe void git_repository_set_index( git_repository* repository, - IndexSafeHandle index); + git_index* index); [DllImport(libgit2)] internal static extern unsafe int git_repository_set_workdir( diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index 045a35d9e..65abddf82 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -11,5 +11,7 @@ internal struct git_blame {} internal struct git_diff {} internal struct git_patch {} internal struct git_config {} + internal struct git_index_conflict_iterator {} + internal struct git_index {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index c0e95ce67..a028943b3 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -728,7 +728,7 @@ public static unsafe void git_diff_foreach( public static unsafe DiffHandle git_diff_tree_to_index( RepositoryHandle repo, - IndexSafeHandle index, + IndexHandle index, ObjectId oldTree, GitDiffOptions options) { @@ -767,7 +767,7 @@ public static unsafe DiffHandle git_diff_tree_to_tree( public static unsafe DiffHandle git_diff_index_to_workdir( RepositoryHandle repo, - IndexSafeHandle index, + IndexHandle index, GitDiffOptions options) { git_diff* diff; @@ -898,20 +898,20 @@ public static unsafe bool git_ignore_path_is_ignored(RepositoryHandle repo, stri #region git_index_ - public static unsafe void git_index_add(IndexSafeHandle index, git_index_entry* entry) + public static unsafe void git_index_add(IndexHandle index, git_index_entry* entry) { int res = NativeMethods.git_index_add(index, entry); Ensure.ZeroResult(res); } - public static void git_index_add_bypath(IndexSafeHandle index, FilePath path) + public static unsafe void git_index_add_bypath(IndexHandle index, FilePath path) { int res = NativeMethods.git_index_add_bypath(index, path); Ensure.ZeroResult(res); } public static unsafe Conflict git_index_conflict_get( - IndexSafeHandle index, + IndexHandle index, FilePath path) { git_index_entry* ancestor, ours, theirs; @@ -934,16 +934,16 @@ public static unsafe Conflict git_index_conflict_get( IndexEntry.BuildFromPtr(theirs)); } - public static ConflictIteratorSafeHandle git_index_conflict_iterator_new(IndexSafeHandle index) + public static unsafe ConflictIteratorHandle git_index_conflict_iterator_new(IndexHandle index) { - ConflictIteratorSafeHandle iter; + git_index_conflict_iterator* iter; int res = NativeMethods.git_index_conflict_iterator_new(out iter, index); Ensure.ZeroResult(res); - return iter; + return new ConflictIteratorHandle(iter, true); } - public static unsafe Conflict git_index_conflict_next(ConflictIteratorSafeHandle iterator) + public static unsafe Conflict git_index_conflict_next(ConflictIteratorHandle iterator) { git_index_entry* ancestor, ours, theirs; @@ -961,12 +961,7 @@ public static unsafe Conflict git_index_conflict_next(ConflictIteratorSafeHandle IndexEntry.BuildFromPtr(theirs)); } - public static void git_index_conflict_iterator_free(IntPtr iterator) - { - NativeMethods.git_index_conflict_iterator_free(iterator); - } - - public static int git_index_entrycount(IndexSafeHandle index) + public static unsafe int git_index_entrycount(IndexHandle index) { return NativeMethods.git_index_entrycount(index) .ConvertToInt(); @@ -977,22 +972,17 @@ public static unsafe StageLevel git_index_entry_stage(git_index_entry* entry) return (StageLevel)NativeMethods.git_index_entry_stage(entry); } - public static void git_index_free(IntPtr index) - { - NativeMethods.git_index_free(index); - } - - public static unsafe git_index_entry* git_index_get_byindex(IndexSafeHandle index, UIntPtr n) + public static unsafe git_index_entry* git_index_get_byindex(IndexHandle index, UIntPtr n) { return NativeMethods.git_index_get_byindex(index, n); } - public static unsafe git_index_entry* git_index_get_bypath(IndexSafeHandle index, FilePath path, int stage) + public static unsafe git_index_entry* git_index_get_bypath(IndexHandle index, FilePath path, int stage) { return NativeMethods.git_index_get_bypath(index, path, stage); } - public static bool git_index_has_conflicts(IndexSafeHandle index) + public static unsafe bool git_index_has_conflicts(IndexHandle index) { int res = NativeMethods.git_index_has_conflicts(index); Ensure.BooleanResult(res); @@ -1000,61 +990,61 @@ public static bool git_index_has_conflicts(IndexSafeHandle index) return res != 0; } - public static int git_index_name_entrycount(IndexSafeHandle index) + public static unsafe int git_index_name_entrycount(IndexHandle index) { return NativeMethods.git_index_name_entrycount(index) .ConvertToInt(); } - public static unsafe git_index_name_entry* git_index_name_get_byindex(IndexSafeHandle index, UIntPtr n) + public static unsafe git_index_name_entry* git_index_name_get_byindex(IndexHandle index, UIntPtr n) { return NativeMethods.git_index_name_get_byindex(index, n); } - public static IndexSafeHandle git_index_open(FilePath indexpath) + public static unsafe IndexHandle git_index_open(FilePath indexpath) { - IndexSafeHandle handle; + git_index* handle; int res = NativeMethods.git_index_open(out handle, indexpath); Ensure.ZeroResult(res); - return handle; + return new IndexHandle(handle, true); } - public static void git_index_read(IndexSafeHandle index) + public static unsafe void git_index_read(IndexHandle index) { int res = NativeMethods.git_index_read(index, false); Ensure.ZeroResult(res); } - public static void git_index_remove_bypath(IndexSafeHandle index, FilePath path) + public static unsafe void git_index_remove_bypath(IndexHandle index, FilePath path) { int res = NativeMethods.git_index_remove_bypath(index, path); Ensure.ZeroResult(res); } - public static int git_index_reuc_entrycount(IndexSafeHandle index) + public static unsafe int git_index_reuc_entrycount(IndexHandle index) { return NativeMethods.git_index_reuc_entrycount(index) .ConvertToInt(); } - public static unsafe git_index_reuc_entry* git_index_reuc_get_byindex(IndexSafeHandle index, UIntPtr n) + public static unsafe git_index_reuc_entry* git_index_reuc_get_byindex(IndexHandle index, UIntPtr n) { return NativeMethods.git_index_reuc_get_byindex(index, n); } - public static unsafe git_index_reuc_entry* git_index_reuc_get_bypath(IndexSafeHandle index, string path) + public static unsafe git_index_reuc_entry* git_index_reuc_get_bypath(IndexHandle index, string path) { return NativeMethods.git_index_reuc_get_bypath(index, path); } - public static void git_index_write(IndexSafeHandle index) + public static unsafe void git_index_write(IndexHandle index) { int res = NativeMethods.git_index_write(index); Ensure.ZeroResult(res); } - public static ObjectId git_index_write_tree(IndexSafeHandle index) + public static unsafe ObjectId git_index_write_tree(IndexHandle index) { GitOid treeOid; int res = NativeMethods.git_index_write_tree(out treeOid, index); @@ -1063,7 +1053,7 @@ public static ObjectId git_index_write_tree(IndexSafeHandle index) return treeOid; } - public static unsafe ObjectId git_index_write_tree_to(IndexSafeHandle index, RepositoryHandle repo) + public static unsafe ObjectId git_index_write_tree_to(IndexHandle index, RepositoryHandle repo) { GitOid treeOid; int res = NativeMethods.git_index_write_tree_to(out treeOid, index, repo); @@ -1072,13 +1062,13 @@ public static unsafe ObjectId git_index_write_tree_to(IndexSafeHandle index, Rep return treeOid; } - public static void git_index_read_fromtree(Index index, GitObjectSafeHandle tree) + public static unsafe void git_index_read_fromtree(Index index, GitObjectSafeHandle tree) { int res = NativeMethods.git_index_read_tree(index.Handle, tree); Ensure.ZeroResult(res); } - public static void git_index_clear(Index index) + public static unsafe void git_index_clear(Index index) { int res = NativeMethods.git_index_clear(index.Handle); Ensure.ZeroResult(res); @@ -1088,13 +1078,13 @@ public static void git_index_clear(Index index) #region git_merge_ - public static unsafe IndexSafeHandle git_merge_commits(RepositoryHandle repo, GitObjectSafeHandle ourCommit, GitObjectSafeHandle theirCommit, GitMergeOpts opts) + public static unsafe IndexHandle git_merge_commits(RepositoryHandle repo, GitObjectSafeHandle ourCommit, GitObjectSafeHandle theirCommit, GitMergeOpts opts) { - IndexSafeHandle index; + git_index* index; int res = NativeMethods.git_merge_commits(out index, repo, ourCommit, theirCommit, ref opts); Ensure.ZeroResult(res); - return index; + return new IndexHandle(index, true); } public static unsafe ObjectId git_merge_base_many(RepositoryHandle repo, GitOid[] commitIds) @@ -2350,13 +2340,13 @@ public static bool git_repository_head_unborn(RepositoryHandle repo) return RepositoryStateChecker(repo, NativeMethods.git_repository_head_unborn); } - public static unsafe IndexSafeHandle git_repository_index(RepositoryHandle repo) + public static unsafe IndexHandle git_repository_index(RepositoryHandle repo) { - IndexSafeHandle handle; + git_index* handle; int res = NativeMethods.git_repository_index(out handle, repo); Ensure.ZeroResult(res); - return handle; + return new IndexHandle(handle, true); } public static unsafe RepositoryHandle git_repository_init_ext( @@ -2483,7 +2473,7 @@ public static unsafe void git_repository_set_ident(RepositoryHandle repo, string Ensure.ZeroResult(res); } - public static unsafe void git_repository_set_index(RepositoryHandle repo, IndexSafeHandle index) + public static unsafe void git_repository_set_index(RepositoryHandle repo, IndexHandle index) { NativeMethods.git_repository_set_index(repo, index); } diff --git a/LibGit2Sharp/Index.cs b/LibGit2Sharp/Index.cs index 033400c67..8128741ac 100644 --- a/LibGit2Sharp/Index.cs +++ b/LibGit2Sharp/Index.cs @@ -16,7 +16,7 @@ namespace LibGit2Sharp [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Index : IEnumerable { - private readonly IndexSafeHandle handle; + private readonly IndexHandle handle; private readonly Repository repo; private readonly ConflictCollection conflicts; @@ -47,7 +47,7 @@ internal Index(Repository repo, string indexPath) repo.RegisterForCleanup(handle); } - internal IndexSafeHandle Handle + internal IndexHandle Handle { get { return handle; } } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index dbe850c85..a767f3e01 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -75,7 +75,6 @@ - @@ -228,7 +227,6 @@ - @@ -310,7 +308,6 @@ - diff --git a/LibGit2Sharp/ObjectDatabase.cs b/LibGit2Sharp/ObjectDatabase.cs index 5c953eddd..7085b3df3 100644 --- a/LibGit2Sharp/ObjectDatabase.cs +++ b/LibGit2Sharp/ObjectDatabase.cs @@ -623,7 +623,7 @@ public virtual MergeTreeResult MergeCommits(Commit ours, Commit theirs, MergeTre List conflicts = new List(); Conflict conflict; - using (ConflictIteratorSafeHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle)) + using (ConflictIteratorHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle)) { while ((conflict = Proxy.git_index_conflict_next(iterator)) != null) { From 3bc68d5246b15244e7892b123559d6bceed09148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 15 Jan 2016 06:50:05 +0100 Subject: [PATCH 27/50] Get rid of Reflog{,Entry}SafeHandle --- LibGit2Sharp/Core/Handles/Objects.cs | 69 +++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 2 + .../Core/Handles/ReflogEntrySafeHandle.cs | 6 -- LibGit2Sharp/Core/Handles/ReflogSafeHandle.cs | 11 --- LibGit2Sharp/Core/NativeMethods.cs | 21 +++--- LibGit2Sharp/Core/Opaques.cs | 2 + LibGit2Sharp/Core/Proxy.cs | 23 +++---- LibGit2Sharp/LibGit2Sharp.csproj | 2 - LibGit2Sharp/ReflogCollection.cs | 6 +- LibGit2Sharp/ReflogEntry.cs | 2 +- 10 files changed, 96 insertions(+), 48 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/ReflogEntrySafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/ReflogSafeHandle.cs diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index 7e0f99e1a..411d87540 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -763,4 +763,73 @@ public void Dispose() } } + internal unsafe class ReflogHandle : IDisposable + { + git_reflog* ptr; + internal git_reflog* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe ReflogHandle(git_reflog* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe ReflogHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_reflog*) ptr.ToPointer(); + this.owned = owned; + } + + ~ReflogHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_reflog_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_reflog*(ReflogHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 2f3ed311f..9df067d13 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -23,6 +23,7 @@ var cNames = new[] { "git_config", "git_index_conflict_iterator", "git_index", + "git_reflog", }; var csNames = new[] { @@ -37,6 +38,7 @@ var csNames = new[] { "ConfigurationHandle", "ConflictIteratorHandle", "IndexHandle", + "ReflogHandle", }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/Handles/ReflogEntrySafeHandle.cs b/LibGit2Sharp/Core/Handles/ReflogEntrySafeHandle.cs deleted file mode 100644 index 1739ccac3..000000000 --- a/LibGit2Sharp/Core/Handles/ReflogEntrySafeHandle.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class ReflogEntrySafeHandle : NotOwnedSafeHandleBase - { - } -} diff --git a/LibGit2Sharp/Core/Handles/ReflogSafeHandle.cs b/LibGit2Sharp/Core/Handles/ReflogSafeHandle.cs deleted file mode 100644 index a75deabea..000000000 --- a/LibGit2Sharp/Core/Handles/ReflogSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class ReflogSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_reflog_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index aa92933ad..e2a065821 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1075,39 +1075,38 @@ internal static extern unsafe int git_reference_ensure_log( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refname); [DllImport(libgit2)] - internal static extern void git_reflog_free( - IntPtr reflog); + internal static extern unsafe void git_reflog_free(git_reflog* reflog); [DllImport(libgit2)] internal static extern unsafe int git_reflog_read( - out ReflogSafeHandle ref_out, + out git_reflog* ref_out, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern UIntPtr git_reflog_entrycount - (ReflogSafeHandle reflog); + internal static extern unsafe UIntPtr git_reflog_entrycount + (git_reflog* reflog); [DllImport(libgit2)] - internal static extern ReflogEntrySafeHandle git_reflog_entry_byindex( - ReflogSafeHandle reflog, + internal static extern unsafe git_reflog_entry* git_reflog_entry_byindex( + git_reflog* reflog, UIntPtr idx); [DllImport(libgit2)] internal static extern unsafe git_oid* git_reflog_entry_id_old( - SafeHandle entry); + git_reflog_entry* entry); [DllImport(libgit2)] internal static extern unsafe git_oid* git_reflog_entry_id_new( - SafeHandle entry); + git_reflog_entry* entry); [DllImport(libgit2)] internal static extern unsafe git_signature* git_reflog_entry_committer( - SafeHandle entry); + git_reflog_entry* entry); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_reflog_entry_message(SafeHandle entry); + internal static extern unsafe string git_reflog_entry_message(git_reflog_entry* entry); [DllImport(libgit2)] internal static extern unsafe int git_refspec_rtransform( diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index 65abddf82..7acfe8dad 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -13,5 +13,7 @@ internal struct git_patch {} internal struct git_config {} internal struct git_index_conflict_iterator {} internal struct git_index {} + internal struct git_reflog {} + internal struct git_reflog_entry {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index a028943b3..df5fcbda9 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -1906,47 +1906,42 @@ public static unsafe void git_reference_ensure_log(RepositoryHandle repo, string #region git_reflog_ - public static void git_reflog_free(IntPtr reflog) + public static unsafe ReflogHandle git_reflog_read(RepositoryHandle repo, string canonicalName) { - NativeMethods.git_reflog_free(reflog); - } - - public static unsafe ReflogSafeHandle git_reflog_read(RepositoryHandle repo, string canonicalName) - { - ReflogSafeHandle reflog_out; + git_reflog* reflog_out; int res = NativeMethods.git_reflog_read(out reflog_out, repo, canonicalName); Ensure.ZeroResult(res); - return reflog_out; + return new ReflogHandle(reflog_out, true); } - public static int git_reflog_entrycount(ReflogSafeHandle reflog) + public static unsafe int git_reflog_entrycount(ReflogHandle reflog) { return (int)NativeMethods.git_reflog_entrycount(reflog); } - public static ReflogEntrySafeHandle git_reflog_entry_byindex(ReflogSafeHandle reflog, int idx) + public static unsafe git_reflog_entry* git_reflog_entry_byindex(ReflogHandle reflog, int idx) { return NativeMethods.git_reflog_entry_byindex(reflog, (UIntPtr)idx); } - public static unsafe ObjectId git_reflog_entry_id_old(SafeHandle entry) + public static unsafe ObjectId git_reflog_entry_id_old(git_reflog_entry* entry) { return ObjectId.BuildFromPtr(NativeMethods.git_reflog_entry_id_old(entry)); } - public static unsafe ObjectId git_reflog_entry_id_new(SafeHandle entry) + public static unsafe ObjectId git_reflog_entry_id_new(git_reflog_entry* entry) { return ObjectId.BuildFromPtr(NativeMethods.git_reflog_entry_id_new(entry)); } - public static unsafe Signature git_reflog_entry_committer(SafeHandle entry) + public static unsafe Signature git_reflog_entry_committer(git_reflog_entry* entry) { return new Signature(NativeMethods.git_reflog_entry_committer(entry)); } - public static string git_reflog_entry_message(SafeHandle entry) + public static unsafe string git_reflog_entry_message(git_reflog_entry* entry) { return NativeMethods.git_reflog_entry_message(entry); } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index a767f3e01..a0f1afe77 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -192,8 +192,6 @@ - - diff --git a/LibGit2Sharp/ReflogCollection.cs b/LibGit2Sharp/ReflogCollection.cs index a15339c57..20b1a8b73 100644 --- a/LibGit2Sharp/ReflogCollection.cs +++ b/LibGit2Sharp/ReflogCollection.cs @@ -53,17 +53,17 @@ internal ReflogCollection(Repository repo, string canonicalName) /// /// /// An object that can be used to iterate through the collection. - public virtual IEnumerator GetEnumerator() + public virtual unsafe IEnumerator GetEnumerator() { var entries = new List(); - using (ReflogSafeHandle reflog = Proxy.git_reflog_read(repo.Handle, canonicalName)) + using (ReflogHandle reflog = Proxy.git_reflog_read(repo.Handle, canonicalName)) { var entriesCount = Proxy.git_reflog_entrycount(reflog); for (int i = 0; i < entriesCount; i++) { - ReflogEntrySafeHandle handle = Proxy.git_reflog_entry_byindex(reflog, i); + git_reflog_entry* handle = Proxy.git_reflog_entry_byindex(reflog, i); entries.Add(new ReflogEntry(handle)); } } diff --git a/LibGit2Sharp/ReflogEntry.cs b/LibGit2Sharp/ReflogEntry.cs index f783b11cf..599be8151 100644 --- a/LibGit2Sharp/ReflogEntry.cs +++ b/LibGit2Sharp/ReflogEntry.cs @@ -25,7 +25,7 @@ protected ReflogEntry() /// Initializes a new instance of the class. /// /// a to the reflog entry - public ReflogEntry(SafeHandle entryHandle) + internal unsafe ReflogEntry(git_reflog_entry* entryHandle) { _from = Proxy.git_reflog_entry_id_old(entryHandle); _to = Proxy.git_reflog_entry_id_new(entryHandle); From b0a88b781e67a4719a18be41e3e8d80d6431439e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 15 Jan 2016 07:12:21 +0100 Subject: [PATCH 28/50] Get rid of some more opaque safe handles --- LibGit2Sharp/Commit.cs | 2 +- LibGit2Sharp/CommitLog.cs | 4 +- LibGit2Sharp/Core/GitObjectLazyGroup.cs | 6 +- .../Core/Handles/DescribeResultSafeHandle.cs | 11 - .../Core/Handles/GitAnnotatedCommitHandle.cs | 11 - .../Core/Handles/GitObjectSafeHandle.cs | 11 - .../Core/Handles/NotOwnedSafeHandleBase.cs | 29 - LibGit2Sharp/Core/Handles/NoteSafeHandle.cs | 11 - .../Core/Handles/NullGitObjectSafeHandle.cs | 18 - .../Core/Handles/NullRepositorySafeHandle.cs | 18 - .../Core/Handles/ObjectDatabaseSafeHandle.cs | 11 - LibGit2Sharp/Core/Handles/Objects.cs | 828 ++++++++++++++++++ LibGit2Sharp/Core/Handles/Objects.tt | 24 + .../Core/Handles/OdbStreamSafeHandle.cs | 11 - .../Core/Handles/PackBuilderSafeHandle.cs | 11 - LibGit2Sharp/Core/Handles/RebaseSafeHandle.cs | 13 - LibGit2Sharp/Core/Handles/RemoteSafeHandle.cs | 11 - .../Core/Handles/RevWalkerSafeHandle.cs | 11 - LibGit2Sharp/Core/Handles/SafeHandleBase.cs | 207 ----- .../Core/Handles/SubmoduleSafeHandle.cs | 11 - .../Core/Handles/TreeBuilderSafeHandle.cs | 11 - LibGit2Sharp/Core/NativeMethods.cs | 339 ++++--- LibGit2Sharp/Core/ObjectSafeWrapper.cs | 8 +- LibGit2Sharp/Core/Opaques.cs | 12 + LibGit2Sharp/Core/Proxy.cs | 386 ++++---- LibGit2Sharp/Core/RawContentStream.cs | 14 +- LibGit2Sharp/Core/SubmoduleLazyGroup.cs | 4 +- LibGit2Sharp/GitObject.cs | 2 +- LibGit2Sharp/LibGit2Sharp.csproj | 18 - LibGit2Sharp/Network.cs | 24 +- LibGit2Sharp/Note.cs | 2 +- LibGit2Sharp/NoteCollection.cs | 2 +- LibGit2Sharp/ObjectDatabase.cs | 2 +- LibGit2Sharp/PackBuilder.cs | 4 +- LibGit2Sharp/Rebase.cs | 35 +- LibGit2Sharp/RebaseOperationImpl.cs | 10 +- LibGit2Sharp/RefSpecCollection.cs | 4 +- LibGit2Sharp/Remote.cs | 6 +- LibGit2Sharp/RemoteCollection.cs | 6 +- LibGit2Sharp/RemoteUpdater.cs | 4 +- LibGit2Sharp/Repository.cs | 26 +- LibGit2Sharp/SubmoduleCollection.cs | 2 +- LibGit2Sharp/TreeDefinition.cs | 2 +- 43 files changed, 1277 insertions(+), 905 deletions(-) delete mode 100644 LibGit2Sharp/Core/Handles/DescribeResultSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/GitAnnotatedCommitHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/GitObjectSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/NotOwnedSafeHandleBase.cs delete mode 100644 LibGit2Sharp/Core/Handles/NoteSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/NullGitObjectSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/NullRepositorySafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/ObjectDatabaseSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/OdbStreamSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/PackBuilderSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/RebaseSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/RemoteSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/RevWalkerSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/SafeHandleBase.cs delete mode 100644 LibGit2Sharp/Core/Handles/SubmoduleSafeHandle.cs delete mode 100644 LibGit2Sharp/Core/Handles/TreeBuilderSafeHandle.cs diff --git a/LibGit2Sharp/Commit.cs b/LibGit2Sharp/Commit.cs index ea7844477..a8703f3dc 100644 --- a/LibGit2Sharp/Commit.cs +++ b/LibGit2Sharp/Commit.cs @@ -106,7 +106,7 @@ private IEnumerable RetrieveNotesOfCommit(ObjectId oid) return repo.Notes[oid]; } - private static string RetrieveEncodingOf(GitObjectSafeHandle obj) + private static string RetrieveEncodingOf(ObjectHandle obj) { string encoding = Proxy.git_commit_message_encoding(obj); diff --git a/LibGit2Sharp/CommitLog.cs b/LibGit2Sharp/CommitLog.cs index 7568181d3..abc9ab4a5 100644 --- a/LibGit2Sharp/CommitLog.cs +++ b/LibGit2Sharp/CommitLog.cs @@ -132,7 +132,7 @@ public Commit FindMergeBase(IEnumerable commits, MergeBaseFindingStrateg private class CommitEnumerator : IEnumerator { private readonly Repository repo; - private readonly RevWalkerSafeHandle handle; + private readonly RevWalkerHandle handle; private ObjectId currentOid; public CommitEnumerator(Repository repo, CommitFilter filter) @@ -191,7 +191,7 @@ private void Dispose(bool disposing) handle.SafeDispose(); } - private delegate void HidePushSignature(RevWalkerSafeHandle handle, ObjectId id); + private delegate void HidePushSignature(RevWalkerHandle handle, ObjectId id); private void InternalHidePush(IList identifier, HidePushSignature hidePush) { diff --git a/LibGit2Sharp/Core/GitObjectLazyGroup.cs b/LibGit2Sharp/Core/GitObjectLazyGroup.cs index 824cc92cc..4e0ba384e 100644 --- a/LibGit2Sharp/Core/GitObjectLazyGroup.cs +++ b/LibGit2Sharp/Core/GitObjectLazyGroup.cs @@ -3,7 +3,7 @@ namespace LibGit2Sharp.Core { - internal class GitObjectLazyGroup : LazyGroup + internal class GitObjectLazyGroup : LazyGroup { private readonly ObjectId id; @@ -13,7 +13,7 @@ public GitObjectLazyGroup(Repository repo, ObjectId id) this.id = id; } - protected override void EvaluateInternal(Action evaluator) + protected override void EvaluateInternal(Action evaluator) { using (var osw = new ObjectSafeWrapper(id, repo.Handle)) { @@ -21,7 +21,7 @@ protected override void EvaluateInternal(Action evaluator) } } - public static ILazy Singleton(Repository repo, ObjectId id, Func resultSelector) + public static ILazy Singleton(Repository repo, ObjectId id, Func resultSelector) { return Singleton(() => { diff --git a/LibGit2Sharp/Core/Handles/DescribeResultSafeHandle.cs b/LibGit2Sharp/Core/Handles/DescribeResultSafeHandle.cs deleted file mode 100644 index cbdb225e8..000000000 --- a/LibGit2Sharp/Core/Handles/DescribeResultSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class DescribeResultSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_describe_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/GitAnnotatedCommitHandle.cs b/LibGit2Sharp/Core/Handles/GitAnnotatedCommitHandle.cs deleted file mode 100644 index f125772d0..000000000 --- a/LibGit2Sharp/Core/Handles/GitAnnotatedCommitHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class GitAnnotatedCommitHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_annotated_commit_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/GitObjectSafeHandle.cs b/LibGit2Sharp/Core/Handles/GitObjectSafeHandle.cs deleted file mode 100644 index 46de2dfe7..000000000 --- a/LibGit2Sharp/Core/Handles/GitObjectSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class GitObjectSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_object_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/NotOwnedSafeHandleBase.cs b/LibGit2Sharp/Core/Handles/NotOwnedSafeHandleBase.cs deleted file mode 100644 index d9c05abf4..000000000 --- a/LibGit2Sharp/Core/Handles/NotOwnedSafeHandleBase.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace LibGit2Sharp.Core.Handles -{ - internal abstract class NotOwnedSafeHandleBase : SafeHandle - { - protected NotOwnedSafeHandleBase() - : base(IntPtr.Zero, false) - { - } - - public override bool IsInvalid - { - get { return IsZero; } - } - - public bool IsZero - { - get { return (handle == IntPtr.Zero); } - } - - protected override bool ReleaseHandle() - { - // Does nothing as the pointer is owned by libgit2 - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/NoteSafeHandle.cs b/LibGit2Sharp/Core/Handles/NoteSafeHandle.cs deleted file mode 100644 index a62c5105a..000000000 --- a/LibGit2Sharp/Core/Handles/NoteSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class NoteSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_note_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/NullGitObjectSafeHandle.cs b/LibGit2Sharp/Core/Handles/NullGitObjectSafeHandle.cs deleted file mode 100644 index 5c4521193..000000000 --- a/LibGit2Sharp/Core/Handles/NullGitObjectSafeHandle.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace LibGit2Sharp.Core.Handles -{ - internal class NullGitObjectSafeHandle : GitObjectSafeHandle - { - public NullGitObjectSafeHandle() - { - handle = IntPtr.Zero; - } - - protected override bool ReleaseHandleImpl() - { - // Nothing to release - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/NullRepositorySafeHandle.cs b/LibGit2Sharp/Core/Handles/NullRepositorySafeHandle.cs deleted file mode 100644 index cf57b96fc..000000000 --- a/LibGit2Sharp/Core/Handles/NullRepositorySafeHandle.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace LibGit2Sharp.Core.Handles -{ - internal class NullRepositorySafeHandle : SafeHandleBase - { - public NullRepositorySafeHandle() - { - handle = IntPtr.Zero; - } - - protected override bool ReleaseHandleImpl() - { - // Nothing to release - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/ObjectDatabaseSafeHandle.cs b/LibGit2Sharp/Core/Handles/ObjectDatabaseSafeHandle.cs deleted file mode 100644 index e8cfb2b0a..000000000 --- a/LibGit2Sharp/Core/Handles/ObjectDatabaseSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class ObjectDatabaseSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_odb_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index 411d87540..827b6252d 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -832,4 +832,832 @@ public void Dispose() } } + internal unsafe class TreeBuilderHandle : IDisposable + { + git_treebuilder* ptr; + internal git_treebuilder* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe TreeBuilderHandle(git_treebuilder* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe TreeBuilderHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_treebuilder*) ptr.ToPointer(); + this.owned = owned; + } + + ~TreeBuilderHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_treebuilder_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_treebuilder*(TreeBuilderHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class PackBuilderHandle : IDisposable + { + git_packbuilder* ptr; + internal git_packbuilder* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe PackBuilderHandle(git_packbuilder* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe PackBuilderHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_packbuilder*) ptr.ToPointer(); + this.owned = owned; + } + + ~PackBuilderHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_packbuilder_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_packbuilder*(PackBuilderHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class NoteHandle : IDisposable + { + git_note* ptr; + internal git_note* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe NoteHandle(git_note* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe NoteHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_note*) ptr.ToPointer(); + this.owned = owned; + } + + ~NoteHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_note_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_note*(NoteHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class DescribeResultHandle : IDisposable + { + git_describe_result* ptr; + internal git_describe_result* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe DescribeResultHandle(git_describe_result* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe DescribeResultHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_describe_result*) ptr.ToPointer(); + this.owned = owned; + } + + ~DescribeResultHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_describe_result_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_describe_result*(DescribeResultHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class SubmoduleHandle : IDisposable + { + git_submodule* ptr; + internal git_submodule* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe SubmoduleHandle(git_submodule* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe SubmoduleHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_submodule*) ptr.ToPointer(); + this.owned = owned; + } + + ~SubmoduleHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_submodule_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_submodule*(SubmoduleHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class AnnotatedCommitHandle : IDisposable + { + git_annotated_commit* ptr; + internal git_annotated_commit* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe AnnotatedCommitHandle(git_annotated_commit* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe AnnotatedCommitHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_annotated_commit*) ptr.ToPointer(); + this.owned = owned; + } + + ~AnnotatedCommitHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_annotated_commit_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_annotated_commit*(AnnotatedCommitHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class ObjectDatabaseHandle : IDisposable + { + git_odb* ptr; + internal git_odb* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe ObjectDatabaseHandle(git_odb* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe ObjectDatabaseHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_odb*) ptr.ToPointer(); + this.owned = owned; + } + + ~ObjectDatabaseHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_odb_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_odb*(ObjectDatabaseHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class RevWalkerHandle : IDisposable + { + git_revwalk* ptr; + internal git_revwalk* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe RevWalkerHandle(git_revwalk* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe RevWalkerHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_revwalk*) ptr.ToPointer(); + this.owned = owned; + } + + ~RevWalkerHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_revwalk_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_revwalk*(RevWalkerHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class RemoteHandle : IDisposable + { + git_remote* ptr; + internal git_remote* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe RemoteHandle(git_remote* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe RemoteHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_remote*) ptr.ToPointer(); + this.owned = owned; + } + + ~RemoteHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_remote_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_remote*(RemoteHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class ObjectHandle : IDisposable + { + git_object* ptr; + internal git_object* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe ObjectHandle(git_object* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe ObjectHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_object*) ptr.ToPointer(); + this.owned = owned; + } + + ~ObjectHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_object_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_object*(ObjectHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class RebaseHandle : IDisposable + { + git_rebase* ptr; + internal git_rebase* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe RebaseHandle(git_rebase* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe RebaseHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_rebase*) ptr.ToPointer(); + this.owned = owned; + } + + ~RebaseHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_rebase_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_rebase*(RebaseHandle handle) + { + return handle.Handle; + } + } + + internal unsafe class OdbStreamHandle : IDisposable + { + git_odb_stream* ptr; + internal git_odb_stream* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + public unsafe OdbStreamHandle(git_odb_stream* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + public unsafe OdbStreamHandle(IntPtr ptr, bool owned) + { + this.ptr = (git_odb_stream*) ptr.ToPointer(); + this.owned = owned; + } + + ~OdbStreamHandle() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + NativeMethods.git_odb_stream_free(ptr); + ptr = null; + } + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + public static implicit operator git_odb_stream*(OdbStreamHandle handle) + { + return handle.Handle; + } + } + } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index 9df067d13..d5f341bca 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -24,6 +24,18 @@ var cNames = new[] { "git_index_conflict_iterator", "git_index", "git_reflog", + "git_treebuilder", + "git_packbuilder", + "git_note", + "git_describe_result", + "git_submodule", + "git_annotated_commit", + "git_odb", + "git_revwalk", + "git_remote", + "git_object", + "git_rebase", + "git_odb_stream", }; var csNames = new[] { @@ -39,6 +51,18 @@ var csNames = new[] { "ConflictIteratorHandle", "IndexHandle", "ReflogHandle", + "TreeBuilderHandle", + "PackBuilderHandle", + "NoteHandle", + "DescribeResultHandle", + "SubmoduleHandle", + "AnnotatedCommitHandle", + "ObjectDatabaseHandle", + "RevWalkerHandle", + "RemoteHandle", + "ObjectHandle", + "RebaseHandle", + "OdbStreamHandle", }; for (var i = 0; i < cNames.Length; i++) diff --git a/LibGit2Sharp/Core/Handles/OdbStreamSafeHandle.cs b/LibGit2Sharp/Core/Handles/OdbStreamSafeHandle.cs deleted file mode 100644 index 10dc69db8..000000000 --- a/LibGit2Sharp/Core/Handles/OdbStreamSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class OdbStreamSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_odb_stream_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/PackBuilderSafeHandle.cs b/LibGit2Sharp/Core/Handles/PackBuilderSafeHandle.cs deleted file mode 100644 index 060fefc10..000000000 --- a/LibGit2Sharp/Core/Handles/PackBuilderSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class PackBuilderSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_packbuilder_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/RebaseSafeHandle.cs b/LibGit2Sharp/Core/Handles/RebaseSafeHandle.cs deleted file mode 100644 index e5698fcab..000000000 --- a/LibGit2Sharp/Core/Handles/RebaseSafeHandle.cs +++ /dev/null @@ -1,13 +0,0 @@ -using LibGit2Sharp.Core.Handles; - -namespace LibGit2Sharp.Core -{ - internal class RebaseSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_rebase_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/RemoteSafeHandle.cs b/LibGit2Sharp/Core/Handles/RemoteSafeHandle.cs deleted file mode 100644 index d032e34f5..000000000 --- a/LibGit2Sharp/Core/Handles/RemoteSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class RemoteSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_remote_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/RevWalkerSafeHandle.cs b/LibGit2Sharp/Core/Handles/RevWalkerSafeHandle.cs deleted file mode 100644 index 457bd027c..000000000 --- a/LibGit2Sharp/Core/Handles/RevWalkerSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class RevWalkerSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_revwalk_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/SafeHandleBase.cs b/LibGit2Sharp/Core/Handles/SafeHandleBase.cs deleted file mode 100644 index e16e30917..000000000 --- a/LibGit2Sharp/Core/Handles/SafeHandleBase.cs +++ /dev/null @@ -1,207 +0,0 @@ - -// This activates a lightweight mode which will help put under the light -// incorrectly released handles by outputing a warning message in the console. -// -// This should be activated when tests are being run of the CI server. -// -// Uncomment the line below or add a conditional symbol to activate this mode - -//#define LEAKS_IDENTIFYING - -// This activates a more throrough mode which will show the stack trace of the -// allocation code path for each handle that has been improperly released. -// -// This should be manually activated when some warnings have been raised as -// a result of LEAKS_IDENTIFYING mode activation. -// -// Uncomment the line below or add a conditional symbol to activate this mode - -//#define LEAKS_TRACKING - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using System.Runtime.ConstrainedExecution; -using System.Runtime.InteropServices; -using System.Threading; - -#if LEAKS_IDENTIFYING -namespace LibGit2Sharp.Core -{ - /// - /// Holds leaked handle type names reported by - /// - public static class LeaksContainer - { - private static readonly HashSet _typeNames = new HashSet(); - private static readonly object _lockpad = new object(); - - /// - /// Report a new leaked handle type name - /// - /// Short name of the leaked handle type. - public static void Add(string typeName) - { - lock (_lockpad) - { - _typeNames.Add(typeName); - } - } - - /// - /// Removes all previously reported leaks. - /// - public static void Clear() - { - lock (_lockpad) - { - _typeNames.Clear(); - } - } - - /// - /// Returns all reported leaked handle type names. - /// - public static IEnumerable TypeNames - { - get - { - string[] result = null; - lock (_lockpad) - { - result = _typeNames.ToArray(); - } - return result; - } - } - } -} -#endif - -namespace LibGit2Sharp.Core.Handles -{ - internal abstract class SafeHandleBase : SafeHandle - { - -#if LEAKS_TRACKING - private readonly string trace; - private readonly Guid id; -#endif - - /// - /// This is set to non-zero when has - /// been called for this handle, but - /// has not yet been called. - /// - private int registered; - - protected SafeHandleBase() - : base(IntPtr.Zero, true) - { - NativeMethods.AddHandle(); - registered = 1; - -#if LEAKS_TRACKING - id = Guid.NewGuid(); - Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Allocating {0} handle ({1})", GetType().Name, id)); - trace = new StackTrace(2, true).ToString(); -#endif - } - - protected override void Dispose(bool disposing) - { - bool leaked = !disposing && !IsInvalid; - -#if LEAKS_IDENTIFYING - if (leaked) - { - LeaksContainer.Add(GetType().Name); - } -#endif - - base.Dispose(disposing); - -#if LEAKS_TRACKING - if (!leaked) - { - Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Disposing {0} handle ({1})", GetType().Name, id)); - } - else - { - Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Unexpected finalization of {0} handle ({1})", GetType().Name, id)); - Trace.WriteLine(trace); - Trace.WriteLine(""); - } -#endif - } - - // Prevent the debugger from evaluating this property because it has side effects - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public override sealed bool IsInvalid - { - get - { - bool invalid = IsInvalidImpl(); - if (invalid && Interlocked.CompareExchange(ref registered, 0, 1) == 1) - { - /* Unregister the handle because we know ReleaseHandle won't be called - * to do it for us. - */ - NativeMethods.RemoveHandle(); - } - - return invalid; - } - } - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - protected virtual bool IsInvalidImpl() - { - return handle == IntPtr.Zero; - } - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - protected abstract bool ReleaseHandleImpl(); - - protected override sealed bool ReleaseHandle() - { - bool result; - - try - { - result = ReleaseHandleImpl(); - } - finally - { - if (Interlocked.CompareExchange(ref registered, 0, 1) == 1) - { - // if the handle is still registered at this point, we definitely - // want to unregister it - NativeMethods.RemoveHandle(); - } - else - { - /* For this to be called, the following sequence of events must occur: - * - * 1. The handle is created - * 2. The IsInvalid property is evaluated, and the result is false - * 3. The IsInvalid property is evaluated by the runtime to determine if - * finalization is necessary, and the result is now true - * - * This can only happen if the value of `handle` is manipulated in an unexpected - * way (through the Reflection API or by a specially-crafted derived type that - * does not currently exist). The only safe course of action at this point in - * the shutdown process is returning false, which will trigger the - * releaseHandleFailed MDA but have no other impact on the CLR state. - * http://msdn.microsoft.com/en-us/library/85eak4a0.aspx - */ - result = false; - } - } - - return result; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/SubmoduleSafeHandle.cs b/LibGit2Sharp/Core/Handles/SubmoduleSafeHandle.cs deleted file mode 100644 index 3e84b29b1..000000000 --- a/LibGit2Sharp/Core/Handles/SubmoduleSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class SubmoduleSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_submodule_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/Handles/TreeBuilderSafeHandle.cs b/LibGit2Sharp/Core/Handles/TreeBuilderSafeHandle.cs deleted file mode 100644 index 1fd17a292..000000000 --- a/LibGit2Sharp/Core/Handles/TreeBuilderSafeHandle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LibGit2Sharp.Core.Handles -{ - internal class TreeBuilderSafeHandle : SafeHandleBase - { - protected override bool ReleaseHandleImpl() - { - Proxy.git_treebuilder_free(handle); - return true; - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index e2a065821..c9a6e96eb 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -132,24 +132,24 @@ internal static extern unsafe int git_blob_create_fromchunks( IntPtr data); [DllImport(libgit2)] - internal static extern int git_blob_filtered_content( + internal static extern unsafe int git_blob_filtered_content( GitBuf buf, - GitObjectSafeHandle blob, + git_object* blob, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath as_path, [MarshalAs(UnmanagedType.Bool)] bool check_for_binary_data); [DllImport(libgit2)] - internal static extern IntPtr git_blob_rawcontent(GitObjectSafeHandle blob); + internal static extern unsafe IntPtr git_blob_rawcontent(git_object* blob); [DllImport(libgit2)] - internal static extern Int64 git_blob_rawsize(GitObjectSafeHandle blob); + internal static extern unsafe Int64 git_blob_rawsize(git_object* blob); [DllImport(libgit2)] internal static extern unsafe int git_branch_create_from_annotated( out git_reference* ref_out, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string branch_name, - GitAnnotatedCommitHandle target, + git_annotated_commit* target, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] @@ -192,58 +192,57 @@ internal static extern unsafe int git_branch_remote_name( [DllImport(libgit2)] internal static extern unsafe int git_rebase_init( - out RebaseSafeHandle rebase, + out git_rebase* rebase, git_repository* repo, - GitAnnotatedCommitHandle branch, - GitAnnotatedCommitHandle upstream, - GitAnnotatedCommitHandle onto, + git_annotated_commit* branch, + git_annotated_commit* upstream, + git_annotated_commit* onto, GitRebaseOptions options); [DllImport(libgit2)] internal static extern unsafe int git_rebase_open( - out RebaseSafeHandle rebase, + out git_rebase* rebase, git_repository* repo, GitRebaseOptions options); [DllImport(libgit2)] - internal static extern UIntPtr git_rebase_operation_entrycount( - RebaseSafeHandle rebase); + internal static extern unsafe UIntPtr git_rebase_operation_entrycount( + git_rebase* rebase); [DllImport(libgit2)] - internal static extern UIntPtr git_rebase_operation_current( - RebaseSafeHandle rebase); + internal static extern unsafe UIntPtr git_rebase_operation_current( + git_rebase* rebase); [DllImport(libgit2)] internal static extern unsafe git_rebase_operation* git_rebase_operation_byindex( - RebaseSafeHandle rebase, + git_rebase* rebase, UIntPtr index); [DllImport(libgit2)] internal static extern unsafe int git_rebase_next( out git_rebase_operation* operation, - RebaseSafeHandle rebase); + git_rebase* rebase); [DllImport(libgit2)] internal static extern unsafe int git_rebase_commit( ref GitOid id, - RebaseSafeHandle rebase, + git_rebase* rebase, git_signature* author, git_signature* committer, IntPtr message_encoding, IntPtr message); [DllImport(libgit2)] - internal static extern int git_rebase_abort( - RebaseSafeHandle rebase); + internal static extern unsafe int git_rebase_abort( + git_rebase* rebase); [DllImport(libgit2)] internal static extern unsafe int git_rebase_finish( - RebaseSafeHandle repo, + git_rebase* repo, git_signature* signature); [DllImport(libgit2)] - internal static extern void git_rebase_free( - IntPtr rebase); + internal static extern unsafe void git_rebase_free(git_rebase* rebase); [DllImport(libgit2)] internal static extern unsafe int git_remote_rename( @@ -268,13 +267,13 @@ internal static extern unsafe int git_branch_upstream_name( [DllImport(libgit2)] internal static extern unsafe int git_checkout_tree( git_repository* repo, - GitObjectSafeHandle treeish, + git_object* treeish, ref GitCheckoutOpts opts); [DllImport(libgit2)] internal static extern unsafe int git_checkout_index( git_repository* repo, - GitObjectSafeHandle treeish, + git_object* treeish, ref GitCheckoutOpts opts); [DllImport(libgit2)] @@ -285,10 +284,10 @@ internal static extern unsafe int git_clone( ref GitCloneOptions opts); [DllImport(libgit2)] - internal static extern unsafe git_signature* git_commit_author(GitObjectSafeHandle commit); + internal static extern unsafe git_signature* git_commit_author(git_object* commit); [DllImport(libgit2)] - internal static extern unsafe git_signature* git_commit_committer(GitObjectSafeHandle commit); + internal static extern unsafe git_signature* git_commit_committer(git_object* commit); [DllImport(libgit2)] internal static extern unsafe int git_commit_create_from_ids( @@ -305,24 +304,24 @@ internal static extern unsafe int git_commit_create_from_ids( [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_commit_message(GitObjectSafeHandle commit); + internal static extern unsafe string git_commit_message(git_object* commit); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_commit_summary(GitObjectSafeHandle commit); + internal static extern unsafe string git_commit_summary(git_object* commit); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_commit_message_encoding(GitObjectSafeHandle commit); + internal static extern unsafe string git_commit_message_encoding(git_object* commit); [DllImport(libgit2)] - internal static extern unsafe git_oid* git_commit_parent_id(GitObjectSafeHandle commit, uint n); + internal static extern unsafe git_oid* git_commit_parent_id(git_object* commit, uint n); [DllImport(libgit2)] - internal static extern uint git_commit_parentcount(GitObjectSafeHandle commit); + internal static extern unsafe uint git_commit_parentcount(git_object* commit); [DllImport(libgit2)] - internal static extern unsafe git_oid* git_commit_tree_id(GitObjectSafeHandle commit); + internal static extern unsafe git_oid* git_commit_tree_id(git_object* commit); [DllImport(libgit2)] internal static extern unsafe int git_config_delete_entry( @@ -460,19 +459,19 @@ internal static extern int git_cred_userpass_plaintext_new( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string password); [DllImport(libgit2)] - internal static extern int git_describe_commit( - out DescribeResultSafeHandle describe, - GitObjectSafeHandle committish, + internal static extern unsafe int git_describe_commit( + out git_describe_result* describe, + git_object* committish, ref GitDescribeOptions options); [DllImport(libgit2)] - internal static extern int git_describe_format( + internal static extern unsafe int git_describe_format( GitBuf buf, - DescribeResultSafeHandle describe, + git_describe_result* describe, ref GitDescribeFormatOptions options); [DllImport(libgit2)] - internal static extern void git_describe_result_free(IntPtr describe); + internal static extern unsafe void git_describe_result_free(git_describe_result* describe); [DllImport(libgit2)] internal static extern unsafe void git_diff_free(git_diff* diff); @@ -481,15 +480,15 @@ internal static extern int git_describe_format( internal static extern unsafe int git_diff_tree_to_tree( out git_diff* diff, git_repository* repo, - GitObjectSafeHandle oldTree, - GitObjectSafeHandle newTree, + git_object* oldTree, + git_object* newTree, GitDiffOptions options); [DllImport(libgit2)] internal static extern unsafe int git_diff_tree_to_index( out git_diff* diff, git_repository* repo, - GitObjectSafeHandle oldTree, + git_object* oldTree, git_index* index, GitDiffOptions options); @@ -509,7 +508,7 @@ internal static extern unsafe int git_diff_index_to_workdir( internal static extern unsafe int git_diff_tree_to_workdir( out git_diff* diff, git_repository* repo, - GitObjectSafeHandle oldTree, + git_object* oldTree, GitDiffOptions options); internal unsafe delegate int git_diff_file_cb( @@ -534,10 +533,10 @@ internal unsafe delegate int git_diff_binary_cb( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_diff_blobs( - GitObjectSafeHandle oldBlob, + internal static extern unsafe int git_diff_blobs( + git_object* oldBlob, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath old_as_path, - GitObjectSafeHandle newBlob, + git_object* newBlob, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath new_as_path, GitDiffOptions options, git_diff_file_cb fileCallback, @@ -721,7 +720,7 @@ internal static extern unsafe int git_index_remove_bypath( internal static extern unsafe int git_index_write_tree_to(out GitOid treeOid, git_index* index, git_repository* repo); [DllImport(libgit2)] - internal static extern unsafe int git_index_read_tree(git_index* index, GitObjectSafeHandle tree); + internal static extern unsafe int git_index_read_tree(git_index* index, git_object* tree); [DllImport(libgit2)] internal static extern unsafe int git_index_clear(git_index* index); @@ -742,13 +741,13 @@ internal static extern unsafe int git_merge_base_octopus( [DllImport(libgit2)] internal static extern unsafe int git_annotated_commit_from_ref( - out GitAnnotatedCommitHandle annotatedCommit, + out git_annotated_commit* annotatedCommit, git_repository* repo, git_reference* reference); [DllImport(libgit2)] internal static extern unsafe int git_annotated_commit_from_fetchhead( - out GitAnnotatedCommitHandle annotatedCommit, + out git_annotated_commit* annotatedCommit, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string branch_name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote_url, @@ -756,19 +755,19 @@ internal static extern unsafe int git_annotated_commit_from_fetchhead( [DllImport(libgit2)] internal static extern unsafe int git_annotated_commit_from_revspec( - out GitAnnotatedCommitHandle annotatedCommit, + out git_annotated_commit* annotatedCommit, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string revspec); [DllImport(libgit2)] internal static extern unsafe int git_annotated_commit_lookup( - out GitAnnotatedCommitHandle annotatedCommit, + out git_annotated_commit* annotatedCommit, git_repository* repo, ref GitOid id); [DllImport(libgit2)] internal static extern unsafe git_oid* git_annotated_commit_id( - GitAnnotatedCommitHandle annotatedCommit); + git_annotated_commit* annotatedCommit); [DllImport(libgit2)] internal static extern unsafe int git_merge( @@ -782,8 +781,8 @@ internal static extern unsafe int git_merge( internal static extern unsafe int git_merge_commits( out git_index* index, git_repository* repo, - GitObjectSafeHandle our_commit, - GitObjectSafeHandle their_commit, + git_object* our_commit, + git_object* their_commit, ref GitMergeOpts merge_opts); [DllImport(libgit2)] @@ -795,8 +794,7 @@ internal static extern unsafe int git_merge_analysis( int their_heads_len); [DllImport(libgit2)] - internal static extern void git_annotated_commit_free( - IntPtr merge_head); + internal static extern unsafe void git_annotated_commit_free(git_annotated_commit* commit); [DllImport(libgit2)] internal static extern int git_message_prettify( @@ -817,18 +815,18 @@ internal static extern unsafe int git_note_create( int force); [DllImport(libgit2)] - internal static extern void git_note_free(IntPtr note); + internal static extern unsafe void git_note_free(git_note* note); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_note_message(NoteSafeHandle note); + internal static extern unsafe string git_note_message(git_note* note); [DllImport(libgit2)] - internal static extern unsafe git_oid* git_note_id(NoteSafeHandle note); + internal static extern unsafe git_oid* git_note_id(git_note* note); [DllImport(libgit2)] internal static extern unsafe int git_note_read( - out NoteSafeHandle note, + out git_note* note, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, ref GitOid oid); @@ -859,64 +857,64 @@ internal static extern unsafe int git_note_foreach( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_odb_add_backend(ObjectDatabaseSafeHandle odb, IntPtr backend, int priority); + internal static extern unsafe int git_odb_add_backend(git_odb* odb, IntPtr backend, int priority); [DllImport(libgit2)] internal static extern IntPtr git_odb_backend_malloc(IntPtr backend, UIntPtr len); [DllImport(libgit2)] - internal static extern int git_odb_exists(ObjectDatabaseSafeHandle odb, ref GitOid id); + internal static extern unsafe int git_odb_exists(git_odb* odb, ref GitOid id); internal delegate int git_odb_foreach_cb( IntPtr id, IntPtr payload); [DllImport(libgit2)] - internal static extern int git_odb_foreach( - ObjectDatabaseSafeHandle odb, + internal static extern unsafe int git_odb_foreach( + git_odb* odb, git_odb_foreach_cb cb, IntPtr payload); [DllImport(libgit2)] - internal static extern int git_odb_open_wstream(out OdbStreamSafeHandle stream, ObjectDatabaseSafeHandle odb, Int64 size, GitObjectType type); + internal static extern unsafe int git_odb_open_wstream(out git_odb_stream* stream, git_odb* odb, Int64 size, GitObjectType type); [DllImport(libgit2)] - internal static extern void git_odb_free(IntPtr odb); + internal static extern unsafe void git_odb_free(git_odb* odb); [DllImport(libgit2)] - internal static extern int git_odb_read_header(out UIntPtr len_out, out GitObjectType type, ObjectDatabaseSafeHandle odb, ref GitOid id); + internal static extern unsafe int git_odb_read_header(out UIntPtr len_out, out GitObjectType type, git_odb* odb, ref GitOid id); [DllImport(libgit2)] - internal static extern void git_object_free(IntPtr obj); + internal static extern unsafe void git_object_free(git_object* obj); [DllImport(libgit2)] - internal static extern int git_odb_stream_write(OdbStreamSafeHandle Stream, IntPtr Buffer, UIntPtr len); + internal static extern unsafe int git_odb_stream_write(git_odb_stream* Stream, IntPtr Buffer, UIntPtr len); [DllImport(libgit2)] - internal static extern int git_odb_stream_finalize_write(out GitOid id, OdbStreamSafeHandle stream); + internal static extern unsafe int git_odb_stream_finalize_write(out GitOid id, git_odb_stream* stream); [DllImport(libgit2)] - internal static extern void git_odb_stream_free(IntPtr stream); + internal static extern unsafe void git_odb_stream_free(git_odb_stream* stream); [DllImport(libgit2)] - internal static extern unsafe git_oid* git_object_id(GitObjectSafeHandle obj); + internal static extern unsafe git_oid* git_object_id(git_object* obj); [DllImport(libgit2)] - internal static extern unsafe int git_object_lookup(out GitObjectSafeHandle obj, git_repository* repo, ref GitOid id, GitObjectType type); + internal static extern unsafe int git_object_lookup(out git_object* obj, git_repository* repo, ref GitOid id, GitObjectType type); [DllImport(libgit2)] - internal static extern int git_object_peel( - out GitObjectSafeHandle peeled, - GitObjectSafeHandle obj, + internal static extern unsafe int git_object_peel( + out git_object* peeled, + git_object* obj, GitObjectType type); [DllImport(libgit2)] - internal static extern int git_object_short_id( + internal static extern unsafe int git_object_short_id( GitBuf buf, - GitObjectSafeHandle obj); + git_object* obj); [DllImport(libgit2)] - internal static extern GitObjectType git_object_type(GitObjectSafeHandle obj); + internal static extern unsafe GitObjectType git_object_type(git_object* obj); [DllImport(libgit2)] internal static extern unsafe int git_patch_from_diff(out git_patch* patch, git_diff* diff, UIntPtr idx); @@ -939,49 +937,49 @@ internal static extern unsafe int git_patch_line_stats( internal delegate int git_packbuilder_progress(int stage, uint current, uint total, IntPtr payload); [DllImport(libgit2)] - internal static extern void git_packbuilder_free(IntPtr packbuilder); + internal static extern unsafe void git_packbuilder_free(git_packbuilder* packbuilder); [DllImport(libgit2)] - internal static extern int git_packbuilder_insert( - PackBuilderSafeHandle packbuilder, + internal static extern unsafe int git_packbuilder_insert( + git_packbuilder* packbuilder, ref GitOid id, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern int git_packbuilder_insert_commit( - PackBuilderSafeHandle packbuilder, + internal static extern unsafe int git_packbuilder_insert_commit( + git_packbuilder* packbuilder, ref GitOid id); [DllImport(libgit2)] - internal static extern int git_packbuilder_insert_recur( - PackBuilderSafeHandle packbuilder, + internal static extern unsafe int git_packbuilder_insert_recur( + git_packbuilder* packbuilder, ref GitOid id, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern int git_packbuilder_insert_tree( - PackBuilderSafeHandle packbuilder, + internal static extern unsafe int git_packbuilder_insert_tree( + git_packbuilder* packbuilder, ref GitOid id); [DllImport(libgit2)] - internal static extern unsafe int git_packbuilder_new(out PackBuilderSafeHandle packbuilder, git_repository* repo); + internal static extern unsafe int git_packbuilder_new(out git_packbuilder* packbuilder, git_repository* repo); [DllImport(libgit2)] - internal static extern UInt32 git_packbuilder_object_count(PackBuilderSafeHandle packbuilder); + internal static extern unsafe UInt32 git_packbuilder_object_count(git_packbuilder* packbuilder); [DllImport(libgit2)] - internal static extern UInt32 git_packbuilder_set_threads(PackBuilderSafeHandle packbuilder, UInt32 numThreads); + internal static extern unsafe UInt32 git_packbuilder_set_threads(git_packbuilder* packbuilder, UInt32 numThreads); [DllImport(libgit2)] - internal static extern int git_packbuilder_write( - PackBuilderSafeHandle packbuilder, + internal static extern unsafe int git_packbuilder_write( + git_packbuilder* packbuilder, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, uint mode, IntPtr progressCallback, IntPtr payload); [DllImport(libgit2)] - internal static extern UInt32 git_packbuilder_written(PackBuilderSafeHandle packbuilder); + internal static extern unsafe UInt32 git_packbuilder_written(git_packbuilder* packbuilder); [DllImport(libgit2)] internal static extern unsafe int git_reference_create( @@ -1136,32 +1134,32 @@ internal static extern unsafe string git_refspec_src( internal static extern unsafe bool git_refspec_force(git_refspec* refSpec); [DllImport(libgit2)] - internal static extern int git_remote_autotag(RemoteSafeHandle remote); + internal static extern unsafe int git_remote_autotag(git_remote* remote); [DllImport(libgit2)] - internal static extern int git_remote_connect( - RemoteSafeHandle remote, + internal static extern unsafe int git_remote_connect( + git_remote* remote, GitDirection direction, ref GitRemoteCallbacks callbacks, ref GitStrArray custom_headers); [DllImport(libgit2)] internal static extern unsafe int git_remote_create( - out RemoteSafeHandle remote, + out git_remote* remote, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] internal static extern unsafe int git_remote_create_anonymous( - out RemoteSafeHandle remote, + out git_remote* remote, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] internal static extern unsafe int git_remote_create_with_fetchspec( - out RemoteSafeHandle remote, + out git_remote* remote, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url, @@ -1173,38 +1171,32 @@ internal static extern unsafe int git_remote_delete( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern int git_remote_fetch( - RemoteSafeHandle remote, + internal static extern unsafe int git_remote_fetch( + git_remote* remote, ref GitStrArray refspecs, GitFetchOptions fetch_opts, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string log_message); [DllImport(libgit2)] - internal static extern void git_remote_free(IntPtr remote); + internal static extern unsafe void git_remote_free(git_remote* remote); [DllImport(libgit2)] - internal static extern int git_remote_get_fetch_refspecs(out GitStrArray array, RemoteSafeHandle remote); + internal static extern unsafe int git_remote_get_fetch_refspecs(out GitStrArray array, git_remote* remote); [DllImport(libgit2)] - internal static extern unsafe git_refspec* git_remote_get_refspec(RemoteSafeHandle remote, UIntPtr n); + internal static extern unsafe git_refspec* git_remote_get_refspec(git_remote* remote, UIntPtr n); [DllImport(libgit2)] - internal static extern int git_remote_get_push_refspecs(out GitStrArray array, RemoteSafeHandle remote); + internal static extern unsafe int git_remote_get_push_refspecs(out GitStrArray array, git_remote* remote); [DllImport(libgit2)] - internal static extern int git_remote_push( - RemoteSafeHandle remote, + internal static extern unsafe int git_remote_push( + git_remote* remote, ref GitStrArray refSpecs, GitPushOptions opts); [DllImport(libgit2)] - internal static extern UIntPtr git_remote_refspec_count(RemoteSafeHandle remote); - - [DllImport(libgit2)] - internal static extern int git_remote_set_fetch_refspecs(RemoteSafeHandle remote, ref GitStrArray array); - - [DllImport(libgit2)] - internal static extern int git_remote_set_push_refspecs(RemoteSafeHandle remote, ref GitStrArray array); + internal static extern unsafe UIntPtr git_remote_refspec_count(git_remote* remote); [DllImport(libgit2)] internal static extern unsafe int git_remote_set_url( @@ -1239,24 +1231,24 @@ internal static extern int git_remote_is_valid_name( [DllImport(libgit2)] internal static extern unsafe int git_remote_lookup( - out RemoteSafeHandle remote, + out git_remote* remote, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] - internal static extern unsafe int git_remote_ls(out git_remote_head** heads, out UIntPtr size, RemoteSafeHandle remote); + internal static extern unsafe int git_remote_ls(out git_remote_head** heads, out UIntPtr size, git_remote* remote); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_remote_name(RemoteSafeHandle remote); + internal static extern unsafe string git_remote_name(git_remote* remote); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_remote_url(RemoteSafeHandle remote); + internal static extern unsafe string git_remote_url(git_remote* remote); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_remote_pushurl(RemoteSafeHandle remote); + internal static extern unsafe string git_remote_pushurl(git_remote* remote); [DllImport(libgit2)] internal static extern unsafe void git_remote_set_autotag( @@ -1354,7 +1346,7 @@ internal static extern unsafe int git_repository_message( git_repository* repository); [DllImport(libgit2)] - internal static extern unsafe int git_repository_odb(out ObjectDatabaseSafeHandle odb, git_repository* repo); + internal static extern unsafe int git_repository_odb(out git_odb* odb, git_repository* repo); [DllImport(libgit2)] internal static extern unsafe int git_repository_open( @@ -1403,7 +1395,7 @@ internal static extern unsafe int git_repository_set_head_detached( [DllImport(libgit2)] internal static extern unsafe int git_repository_set_head_detached_from_annotated( git_repository* repo, - GitAnnotatedCommitHandle commit); + git_annotated_commit* commit); [DllImport(libgit2)] internal static extern unsafe int git_repository_set_head( @@ -1428,46 +1420,46 @@ internal static extern unsafe int git_repository_state( [DllImport(libgit2)] internal static extern unsafe int git_reset( git_repository* repo, - GitObjectSafeHandle target, + git_object* target, ResetMode reset_type, ref GitCheckoutOpts opts); [DllImport(libgit2)] internal static extern unsafe int git_revert( git_repository* repo, - GitObjectSafeHandle commit, + git_object* commit, GitRevertOpts opts); [DllImport(libgit2)] internal static extern unsafe int git_revparse_ext( - out GitObjectSafeHandle obj, + out git_object* obj, out git_reference* reference, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string spec); [DllImport(libgit2)] - internal static extern void git_revwalk_free(IntPtr walker); + internal static extern unsafe void git_revwalk_free(git_revwalk* walker); [DllImport(libgit2)] - internal static extern int git_revwalk_hide(RevWalkerSafeHandle walker, ref GitOid commit_id); + internal static extern unsafe int git_revwalk_hide(git_revwalk* walker, ref GitOid commit_id); [DllImport(libgit2)] - internal static extern unsafe int git_revwalk_new(out RevWalkerSafeHandle walker, git_repository* repo); + internal static extern unsafe int git_revwalk_new(out git_revwalk* walker, git_repository* repo); [DllImport(libgit2)] - internal static extern int git_revwalk_next(out GitOid id, RevWalkerSafeHandle walker); + internal static extern unsafe int git_revwalk_next(out GitOid id, git_revwalk* walker); [DllImport(libgit2)] - internal static extern int git_revwalk_push(RevWalkerSafeHandle walker, ref GitOid id); + internal static extern unsafe int git_revwalk_push(git_revwalk* walker, ref GitOid id); [DllImport(libgit2)] - internal static extern void git_revwalk_reset(RevWalkerSafeHandle walker); + internal static extern unsafe void git_revwalk_reset(git_revwalk* walker); [DllImport(libgit2)] - internal static extern void git_revwalk_sorting(RevWalkerSafeHandle walk, CommitSortStrategies sort); + internal static extern unsafe void git_revwalk_sorting(git_revwalk* walk, CommitSortStrategies sort); [DllImport(libgit2)] - internal static extern void git_revwalk_simplify_first_parent(RevWalkerSafeHandle walk); + internal static extern unsafe void git_revwalk_simplify_first_parent(git_revwalk* walk); [DllImport(libgit2)] internal static extern unsafe void git_signature_free(git_signature* signature); @@ -1556,7 +1548,7 @@ internal static extern void git_strarray_free( [DllImport(libgit2)] internal static extern unsafe int git_submodule_lookup( - out SubmoduleSafeHandle reference, + out git_submodule* reference, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath name); @@ -1567,8 +1559,8 @@ internal static extern unsafe int git_submodule_resolve_url( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] - internal static extern int git_submodule_update( - SubmoduleSafeHandle sm, + internal static extern unsafe int git_submodule_update( + git_submodule* sm, [MarshalAs(UnmanagedType.Bool)] bool init, ref GitSubmoduleOptions submoduleUpdateOptions); @@ -1584,51 +1576,50 @@ internal static extern unsafe int git_submodule_foreach( IntPtr payload); [DllImport(libgit2)] - internal static extern int git_submodule_add_to_index( - SubmoduleSafeHandle submodule, + internal static extern unsafe int git_submodule_add_to_index( + git_submodule* submodule, [MarshalAs(UnmanagedType.Bool)] bool write_index); [DllImport(libgit2)] - internal static extern void git_submodule_free( - IntPtr submodule); + internal static extern unsafe void git_submodule_free(git_submodule* submodule); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_submodule_path( - SubmoduleSafeHandle submodule); + internal static extern unsafe string git_submodule_path( + git_submodule* submodule); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_submodule_url( - SubmoduleSafeHandle submodule); + internal static extern unsafe string git_submodule_url( + git_submodule* submodule); [DllImport(libgit2)] internal static extern unsafe git_oid* git_submodule_index_id( - SubmoduleSafeHandle submodule); + git_submodule* submodule); [DllImport(libgit2)] internal static extern unsafe git_oid* git_submodule_head_id( - SubmoduleSafeHandle submodule); + git_submodule* submodule); [DllImport(libgit2)] internal static extern unsafe git_oid* git_submodule_wd_id( - SubmoduleSafeHandle submodule); + git_submodule* submodule); [DllImport(libgit2)] - internal static extern SubmoduleIgnore git_submodule_ignore( - SubmoduleSafeHandle submodule); + internal static extern unsafe SubmoduleIgnore git_submodule_ignore( + git_submodule* submodule); [DllImport(libgit2)] - internal static extern SubmoduleUpdate git_submodule_update_strategy( - SubmoduleSafeHandle submodule); + internal static extern unsafe SubmoduleUpdate git_submodule_update_strategy( + git_submodule* submodule); [DllImport(libgit2)] - internal static extern SubmoduleRecurse git_submodule_fetch_recurse_submodules( - SubmoduleSafeHandle submodule); + internal static extern unsafe SubmoduleRecurse git_submodule_fetch_recurse_submodules( + git_submodule* submodule); [DllImport(libgit2)] - internal static extern int git_submodule_reload( - SubmoduleSafeHandle submodule, + internal static extern unsafe int git_submodule_reload( + git_submodule* submodule, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] @@ -1639,8 +1630,8 @@ internal static extern unsafe int git_submodule_status( GitSubmoduleIgnore ignore); [DllImport(libgit2)] - internal static extern int git_submodule_init( - SubmoduleSafeHandle submodule, + internal static extern unsafe int git_submodule_init( + git_submodule* submodule, [MarshalAs(UnmanagedType.Bool)] bool overwrite); [DllImport(libgit2)] @@ -1648,7 +1639,7 @@ internal static extern unsafe int git_tag_annotation_create( out GitOid oid, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, - GitObjectSafeHandle target, + git_object* target, git_signature* signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message); @@ -1657,7 +1648,7 @@ internal static extern unsafe int git_tag_create( out GitOid oid, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, - GitObjectSafeHandle target, + git_object* target, git_signature* signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, [MarshalAs(UnmanagedType.Bool)] @@ -1668,7 +1659,7 @@ internal static extern unsafe int git_tag_create_lightweight( out GitOid oid, git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, - GitObjectSafeHandle target, + git_object* target, [MarshalAs(UnmanagedType.Bool)] bool force); @@ -1682,20 +1673,20 @@ internal static extern unsafe int git_tag_delete( [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_tag_message(GitObjectSafeHandle tag); + internal static extern unsafe string git_tag_message(git_object* tag); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] - internal static extern string git_tag_name(GitObjectSafeHandle tag); + internal static extern unsafe string git_tag_name(git_object* tag); [DllImport(libgit2)] - internal static extern unsafe git_signature* git_tag_tagger(GitObjectSafeHandle tag); + internal static extern unsafe git_signature* git_tag_tagger(git_object* tag); [DllImport(libgit2)] - internal static extern unsafe git_oid* git_tag_target_id(GitObjectSafeHandle tag); + internal static extern unsafe git_oid* git_tag_target_id(git_object* tag); [DllImport(libgit2)] - internal static extern GitObjectType git_tag_target_type(GitObjectSafeHandle tag); + internal static extern unsafe GitObjectType git_tag_target_type(git_object* tag); [DllImport(libgit2)] internal static extern int git_libgit2_init(); @@ -1737,12 +1728,12 @@ internal static extern int git_transport_unregister( internal static extern unsafe uint git_tree_entry_filemode(git_tree_entry* entry); [DllImport(libgit2)] - internal static extern unsafe git_tree_entry* git_tree_entry_byindex(GitObjectSafeHandle tree, UIntPtr idx); + internal static extern unsafe git_tree_entry* git_tree_entry_byindex(git_object* tree, UIntPtr idx); [DllImport(libgit2)] internal static extern unsafe int git_tree_entry_bypath( out git_tree_entry* tree, - GitObjectSafeHandle root, + git_object* root, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath treeentry_path); [DllImport(libgit2)] @@ -1759,30 +1750,30 @@ internal static extern unsafe int git_tree_entry_bypath( internal static extern unsafe GitObjectType git_tree_entry_type(git_tree_entry* entry); [DllImport(libgit2)] - internal static extern UIntPtr git_tree_entrycount(GitObjectSafeHandle tree); + internal static extern unsafe UIntPtr git_tree_entrycount(git_object* tree); [DllImport(libgit2)] - internal static extern unsafe int git_treebuilder_new(out TreeBuilderSafeHandle builder, git_repository* repo, IntPtr src); + internal static extern unsafe int git_treebuilder_new(out git_treebuilder* builder, git_repository* repo, IntPtr src); [DllImport(libgit2)] - internal static extern int git_treebuilder_insert( + internal static extern unsafe int git_treebuilder_insert( IntPtr entry_out, - TreeBuilderSafeHandle builder, + git_treebuilder* builder, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string treeentry_name, ref GitOid id, uint attributes); [DllImport(libgit2)] - internal static extern int git_treebuilder_write(out GitOid id, TreeBuilderSafeHandle bld); + internal static extern unsafe int git_treebuilder_write(out GitOid id, git_treebuilder* bld); [DllImport(libgit2)] - internal static extern void git_treebuilder_free(IntPtr bld); + internal static extern unsafe void git_treebuilder_free(git_treebuilder* bld); [DllImport(libgit2)] - internal static extern int git_blob_is_binary(GitObjectSafeHandle blob); + internal static extern unsafe int git_blob_is_binary(git_object* blob); [DllImport(libgit2)] - internal static extern unsafe int git_cherrypick(git_repository* repo, GitObjectSafeHandle commit, GitCherryPickOptions options); + internal static extern unsafe int git_cherrypick(git_repository* repo, git_object* commit, GitCherryPickOptions options); } } // ReSharper restore InconsistentNaming diff --git a/LibGit2Sharp/Core/ObjectSafeWrapper.cs b/LibGit2Sharp/Core/ObjectSafeWrapper.cs index adbee7acc..8bb7e9633 100644 --- a/LibGit2Sharp/Core/ObjectSafeWrapper.cs +++ b/LibGit2Sharp/Core/ObjectSafeWrapper.cs @@ -5,15 +5,15 @@ namespace LibGit2Sharp.Core { internal class ObjectSafeWrapper : IDisposable { - private readonly GitObjectSafeHandle objectPtr; + private readonly ObjectHandle objectPtr; - public ObjectSafeWrapper(ObjectId id, RepositoryHandle handle, bool allowNullObjectId = false) + public unsafe ObjectSafeWrapper(ObjectId id, RepositoryHandle handle, bool allowNullObjectId = false) { Ensure.ArgumentNotNull(handle, "handle"); if (allowNullObjectId && id == null) { - objectPtr = new NullGitObjectSafeHandle(); + objectPtr = new ObjectHandle(null, false); } else { @@ -22,7 +22,7 @@ public ObjectSafeWrapper(ObjectId id, RepositoryHandle handle, bool allowNullObj } } - public GitObjectSafeHandle ObjectPtr + public ObjectHandle ObjectPtr { get { return objectPtr; } } diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs index 7acfe8dad..0d0bb55f0 100644 --- a/LibGit2Sharp/Core/Opaques.cs +++ b/LibGit2Sharp/Core/Opaques.cs @@ -15,5 +15,17 @@ internal struct git_index_conflict_iterator {} internal struct git_index {} internal struct git_reflog {} internal struct git_reflog_entry {} + internal struct git_treebuilder {} + internal struct git_packbuilder {} + internal struct git_note {} + internal struct git_describe_result {} + internal struct git_submodule {} + internal struct git_annotated_commit {} + internal struct git_odb {} + internal struct git_revwalk {} + internal struct git_remote {} + internal struct git_object {} + internal struct git_rebase {} + internal struct git_odb_stream {} } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index df5fcbda9..13e5c33b0 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -148,7 +148,7 @@ public static unsafe ObjectId git_blob_create_fromfile(RepositoryHandle repo, Fi return oid; } - public static UnmanagedMemoryStream git_blob_filtered_content_stream(RepositoryHandle repo, ObjectId id, FilePath path, bool check_for_binary_data) + public static unsafe UnmanagedMemoryStream git_blob_filtered_content_stream(RepositoryHandle repo, ObjectId id, FilePath path, bool check_for_binary_data) { var buf = new GitBuf(); var handle = new ObjectSafeWrapper(id, repo).ObjectPtr; @@ -162,18 +162,18 @@ public static UnmanagedMemoryStream git_blob_filtered_content_stream(RepositoryH new[] { buf }); } - public static UnmanagedMemoryStream git_blob_rawcontent_stream(RepositoryHandle repo, ObjectId id, Int64 size) + public static unsafe UnmanagedMemoryStream git_blob_rawcontent_stream(RepositoryHandle repo, ObjectId id, Int64 size) { var handle = new ObjectSafeWrapper(id, repo).ObjectPtr; - return new RawContentStream(handle, NativeMethods.git_blob_rawcontent, h => size); + return new RawContentStream(handle, h => NativeMethods.git_blob_rawcontent(h), h => size); } - public static long git_blob_rawsize(GitObjectSafeHandle obj) + public static unsafe long git_blob_rawsize(ObjectHandle obj) { return NativeMethods.git_blob_rawsize(obj); } - public static bool git_blob_is_binary(GitObjectSafeHandle obj) + public static unsafe bool git_blob_is_binary(ObjectHandle obj) { int res = NativeMethods.git_blob_is_binary(obj); Ensure.BooleanResult(res); @@ -307,7 +307,7 @@ public static unsafe void git_checkout_tree( } } - public static unsafe void git_checkout_index(RepositoryHandle repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts) + public static unsafe void git_checkout_index(RepositoryHandle repo, ObjectHandle treeish, ref GitCheckoutOpts opts) { int res = NativeMethods.git_checkout_index(repo, treeish, ref opts); Ensure.ZeroResult(res); @@ -344,12 +344,12 @@ public static unsafe RepositoryHandle git_clone( #region git_commit_ - public static unsafe Signature git_commit_author(GitObjectSafeHandle obj) + public static unsafe Signature git_commit_author(ObjectHandle obj) { return new Signature(NativeMethods.git_commit_author(obj)); } - public static unsafe Signature git_commit_committer(GitObjectSafeHandle obj) + public static unsafe Signature git_commit_committer(ObjectHandle obj) { return new Signature(NativeMethods.git_commit_committer(obj)); } @@ -388,22 +388,22 @@ public static unsafe ObjectId git_commit_create( } } - public static string git_commit_message(GitObjectSafeHandle obj) + public static unsafe string git_commit_message(ObjectHandle obj) { return NativeMethods.git_commit_message(obj); } - public static string git_commit_summary(GitObjectSafeHandle obj) + public static unsafe string git_commit_summary(ObjectHandle obj) { return NativeMethods.git_commit_summary(obj); } - public static string git_commit_message_encoding(GitObjectSafeHandle obj) + public static unsafe string git_commit_message_encoding(ObjectHandle obj) { return NativeMethods.git_commit_message_encoding(obj); } - public static unsafe ObjectId git_commit_parent_id(GitObjectSafeHandle obj, uint i) + public static unsafe ObjectId git_commit_parent_id(ObjectHandle obj, uint i) { return ObjectId.BuildFromPtr(NativeMethods.git_commit_parent_id(obj, i)); } @@ -416,12 +416,12 @@ public static int git_commit_parentcount(RepositoryHandle repo, ObjectId id) } } - public static int git_commit_parentcount(ObjectSafeWrapper obj) + public static unsafe int git_commit_parentcount(ObjectSafeWrapper obj) { return (int)NativeMethods.git_commit_parentcount(obj.ObjectPtr); } - public static unsafe ObjectId git_commit_tree_id(GitObjectSafeHandle obj) + public static unsafe ObjectId git_commit_tree_id(ObjectHandle obj) { return ObjectId.BuildFromPtr(NativeMethods.git_commit_tree_id(obj)); } @@ -629,7 +629,7 @@ public static unsafe ConfigurationHandle git_config_snapshot(ConfigurationHandle #region git_describe_ - public static string git_describe_commit( + public static unsafe string git_describe_commit( RepositoryHandle repo, ObjectId committishId, DescribeOptions options) @@ -647,12 +647,14 @@ public static string git_describe_commit( ShowCommitOidAsFallback = options.UseCommitIdAsFallback, }; - DescribeResultSafeHandle describeHandle = null; + DescribeResultHandle describeHandle = null; try { - int res = NativeMethods.git_describe_commit(out describeHandle, osw.ObjectPtr, ref opts); + git_describe_result* result; + int res = NativeMethods.git_describe_commit(out result, osw.ObjectPtr, ref opts); Ensure.ZeroResult(res); + describeHandle = new DescribeResultHandle(result, true); using (var buf = new GitBuf()) { @@ -680,16 +682,11 @@ public static string git_describe_commit( } } - public static void git_describe_free(IntPtr iter) - { - NativeMethods.git_describe_result_free(iter); - } - #endregion #region git_diff_ - public static void git_diff_blobs( + public static unsafe void git_diff_blobs( RepositoryHandle repo, ObjectId oldBlob, ObjectId newBlob, @@ -1062,7 +1059,7 @@ public static unsafe ObjectId git_index_write_tree_to(IndexHandle index, Reposit return treeOid; } - public static unsafe void git_index_read_fromtree(Index index, GitObjectSafeHandle tree) + public static unsafe void git_index_read_fromtree(Index index, ObjectHandle tree) { int res = NativeMethods.git_index_read_tree(index.Handle, tree); Ensure.ZeroResult(res); @@ -1078,7 +1075,7 @@ public static unsafe void git_index_clear(Index index) #region git_merge_ - public static unsafe IndexHandle git_merge_commits(RepositoryHandle repo, GitObjectSafeHandle ourCommit, GitObjectSafeHandle theirCommit, GitMergeOpts opts) + public static unsafe IndexHandle git_merge_commits(RepositoryHandle repo, ObjectHandle ourCommit, ObjectHandle theirCommit, GitMergeOpts opts) { git_index* index; int res = NativeMethods.git_merge_commits(out index, repo, ourCommit, theirCommit, ref opts); @@ -1117,58 +1114,58 @@ public static unsafe ObjectId git_merge_base_octopus(RepositoryHandle repo, GitO return ret; } - public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_fetchhead(RepositoryHandle repo, string branchName, string remoteUrl, GitOid oid) + public static unsafe AnnotatedCommitHandle git_annotated_commit_from_fetchhead(RepositoryHandle repo, string branchName, string remoteUrl, GitOid oid) { - GitAnnotatedCommitHandle merge_head; + git_annotated_commit* commit; - int res = NativeMethods.git_annotated_commit_from_fetchhead(out merge_head, repo, branchName, remoteUrl, ref oid); + int res = NativeMethods.git_annotated_commit_from_fetchhead(out commit, repo, branchName, remoteUrl, ref oid); Ensure.ZeroResult(res); - return merge_head; + return new AnnotatedCommitHandle(commit, true); } - public static unsafe GitAnnotatedCommitHandle git_annotated_commit_lookup(RepositoryHandle repo, GitOid oid) + public static unsafe AnnotatedCommitHandle git_annotated_commit_lookup(RepositoryHandle repo, GitOid oid) { - GitAnnotatedCommitHandle their_head; + git_annotated_commit* commit; - int res = NativeMethods.git_annotated_commit_lookup(out their_head, repo, ref oid); + int res = NativeMethods.git_annotated_commit_lookup(out commit, repo, ref oid); Ensure.ZeroResult(res); - return their_head; + return new AnnotatedCommitHandle(commit, true); } - public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositoryHandle repo, ReferenceHandle reference) + public static unsafe AnnotatedCommitHandle git_annotated_commit_from_ref(RepositoryHandle repo, ReferenceHandle reference) { - GitAnnotatedCommitHandle their_head; + git_annotated_commit* commit; - int res = NativeMethods.git_annotated_commit_from_ref(out their_head, repo, reference.Handle); + int res = NativeMethods.git_annotated_commit_from_ref(out commit, repo, reference.Handle); Ensure.ZeroResult(res); - return their_head; + return new AnnotatedCommitHandle(commit, true); } - public static unsafe GitAnnotatedCommitHandle git_annotated_commit_from_revspec(RepositoryHandle repo, string revspec) + public static unsafe AnnotatedCommitHandle git_annotated_commit_from_revspec(RepositoryHandle repo, string revspec) { - GitAnnotatedCommitHandle their_head; + git_annotated_commit* commit; - int res = NativeMethods.git_annotated_commit_from_revspec(out their_head, repo, revspec); + int res = NativeMethods.git_annotated_commit_from_revspec(out commit, repo, revspec); Ensure.ZeroResult(res); - return their_head; + return new AnnotatedCommitHandle(commit, true); } - public static unsafe ObjectId git_annotated_commit_id(GitAnnotatedCommitHandle mergeHead) + public static unsafe ObjectId git_annotated_commit_id(AnnotatedCommitHandle mergeHead) { return ObjectId.BuildFromPtr(NativeMethods.git_annotated_commit_id(mergeHead)); } - public static unsafe void git_merge(RepositoryHandle repo, GitAnnotatedCommitHandle[] heads, GitMergeOpts mergeOptions, GitCheckoutOpts checkoutOptions) + public static unsafe void git_merge(RepositoryHandle repo, AnnotatedCommitHandle[] heads, GitMergeOpts mergeOptions, GitCheckoutOpts checkoutOptions) { - IntPtr[] their_heads = heads.Select(head => head.DangerousGetHandle()).ToArray(); + IntPtr[] their_heads = heads.Select(head => head.AsIntPtr()).ToArray(); int res = NativeMethods.git_merge(repo, their_heads, @@ -1181,11 +1178,11 @@ public static unsafe void git_merge(RepositoryHandle repo, GitAnnotatedCommitHan public static unsafe void git_merge_analysis( RepositoryHandle repo, - GitAnnotatedCommitHandle[] heads, + AnnotatedCommitHandle[] heads, out GitMergeAnalysis analysis_out, out GitMergePreference preference_out) { - IntPtr[] their_heads = heads.Select(head => head.DangerousGetHandle()).ToArray(); + IntPtr[] their_heads = heads.Select(head => head.AsIntPtr()).ToArray(); int res = NativeMethods.git_merge_analysis(out analysis_out, out preference_out, @@ -1196,11 +1193,6 @@ public static unsafe void git_merge_analysis( Ensure.ZeroResult(res); } - public static void git_annotated_commit_free(IntPtr handle) - { - NativeMethods.git_annotated_commit_free(handle); - } - #endregion #region git_message_ @@ -1272,25 +1264,20 @@ public static unsafe ICollection git_note_foreach(RepositoryHa IntPtr.Zero)); } - public static void git_note_free(IntPtr note) - { - NativeMethods.git_note_free(note); - } - - public static string git_note_message(NoteSafeHandle note) + public static unsafe string git_note_message(NoteHandle note) { return NativeMethods.git_note_message(note); } - public static unsafe ObjectId git_note_id(NoteSafeHandle note) + public static unsafe ObjectId git_note_id(NoteHandle note) { return ObjectId.BuildFromPtr(NativeMethods.git_note_id(note)); } - public static unsafe NoteSafeHandle git_note_read(RepositoryHandle repo, string notes_ref, ObjectId id) + public static unsafe NoteHandle git_note_read(RepositoryHandle repo, string notes_ref, ObjectId id) { GitOid oid = id.Oid; - NoteSafeHandle note; + git_note* note; int res = NativeMethods.git_note_read(out note, repo, notes_ref, ref oid); @@ -1301,7 +1288,7 @@ public static unsafe NoteSafeHandle git_note_read(RepositoryHandle repo, string Ensure.ZeroResult(res); - return note; + return new NoteHandle(note, true); } public static unsafe void git_note_remove(RepositoryHandle repo, string notes_ref, Signature author, Signature committer, ObjectId targetId) @@ -1326,19 +1313,14 @@ public static unsafe void git_note_remove(RepositoryHandle repo, string notes_re #region git_object_ - public static unsafe ObjectId git_object_id(GitObjectSafeHandle obj) + public static unsafe ObjectId git_object_id(ObjectHandle obj) { return ObjectId.BuildFromPtr(NativeMethods.git_object_id(obj)); } - public static void git_object_free(IntPtr obj) - { - NativeMethods.git_object_free(obj); - } - - public static unsafe GitObjectSafeHandle git_object_lookup(RepositoryHandle repo, ObjectId id, GitObjectType type) + public static unsafe ObjectHandle git_object_lookup(RepositoryHandle repo, ObjectId id, GitObjectType type) { - GitObjectSafeHandle handle; + git_object* handle; GitOid oid = id.Oid; int res = NativeMethods.git_object_lookup(out handle, repo, ref oid, type); @@ -1352,12 +1334,12 @@ public static unsafe GitObjectSafeHandle git_object_lookup(RepositoryHandle repo break; } - return handle; + return new ObjectHandle(handle, true); } - public static GitObjectSafeHandle git_object_peel(RepositoryHandle repo, ObjectId id, GitObjectType type, bool throwsIfCanNotPeel) + public static unsafe ObjectHandle git_object_peel(RepositoryHandle repo, ObjectId id, GitObjectType type, bool throwsIfCanNotPeel) { - GitObjectSafeHandle peeled; + git_object* peeled; int res; using (var obj = new ObjectSafeWrapper(id, repo)) @@ -1373,10 +1355,10 @@ public static GitObjectSafeHandle git_object_peel(RepositoryHandle repo, ObjectI } Ensure.ZeroResult(res); - return peeled; + return new ObjectHandle(peeled, true); } - public static string git_object_short_id(RepositoryHandle repo, ObjectId id) + public static unsafe string git_object_short_id(RepositoryHandle repo, ObjectId id) { using (var obj = new ObjectSafeWrapper(id, repo)) using (var buf = new GitBuf()) @@ -1388,7 +1370,7 @@ public static string git_object_short_id(RepositoryHandle repo, ObjectId id) } } - public static GitObjectType git_object_type(GitObjectSafeHandle obj) + public static unsafe GitObjectType git_object_type(ObjectHandle obj) { return NativeMethods.git_object_type(obj); } @@ -1397,7 +1379,7 @@ public static GitObjectType git_object_type(GitObjectSafeHandle obj) #region git_odb_ - public static void git_odb_add_backend(ObjectDatabaseSafeHandle odb, IntPtr backend, int priority) + public static unsafe void git_odb_add_backend(ObjectDatabaseHandle odb, IntPtr backend, int priority) { Ensure.ZeroResult(NativeMethods.git_odb_add_backend(odb, backend, priority)); } @@ -1417,7 +1399,7 @@ public static IntPtr git_odb_backend_malloc(IntPtr backend, UIntPtr len) return toReturn; } - public static bool git_odb_exists(ObjectDatabaseSafeHandle odb, ObjectId id) + public static unsafe bool git_odb_exists(ObjectDatabaseHandle odb, ObjectId id) { GitOid oid = id.Oid; @@ -1427,7 +1409,7 @@ public static bool git_odb_exists(ObjectDatabaseSafeHandle odb, ObjectId id) return (res == 1); } - public static GitObjectMetadata git_odb_read_header(ObjectDatabaseSafeHandle odb, ObjectId id) + public static unsafe GitObjectMetadata git_odb_read_header(ObjectDatabaseHandle odb, ObjectId id) { GitOid oid = id.Oid; UIntPtr length; @@ -1439,7 +1421,7 @@ public static GitObjectMetadata git_odb_read_header(ObjectDatabaseSafeHandle odb return new GitObjectMetadata((long)length, objectType); } - public static unsafe ICollection git_odb_foreach(ObjectDatabaseSafeHandle odb) + public static unsafe ICollection git_odb_foreach(ObjectDatabaseHandle odb) { var list = new List(); @@ -1452,21 +1434,16 @@ public static unsafe ICollection git_odb_foreach(ObjectDatabaseSafeHan return list; } - public static OdbStreamSafeHandle git_odb_open_wstream(ObjectDatabaseSafeHandle odb, long size, GitObjectType type) + public static unsafe OdbStreamHandle git_odb_open_wstream(ObjectDatabaseHandle odb, long size, GitObjectType type) { - OdbStreamSafeHandle stream; + git_odb_stream* stream; int res = NativeMethods.git_odb_open_wstream(out stream, odb, size, type); Ensure.ZeroResult(res); - return stream; - } - - public static void git_odb_free(IntPtr odb) - { - NativeMethods.git_odb_free(odb); + return new OdbStreamHandle(stream, true); } - public static void git_odb_stream_write(OdbStreamSafeHandle stream, byte[] data, int len) + public static void git_odb_stream_write(OdbStreamHandle stream, byte[] data, int len) { int res; unsafe @@ -1480,7 +1457,7 @@ public static void git_odb_stream_write(OdbStreamSafeHandle stream, byte[] data, Ensure.ZeroResult(res); } - public static ObjectId git_odb_stream_finalize_write(OdbStreamSafeHandle stream) + public static unsafe ObjectId git_odb_stream_finalize_write(OdbStreamHandle stream) { GitOid id; int res = NativeMethods.git_odb_stream_finalize_write(out id, stream); @@ -1489,11 +1466,6 @@ public static ObjectId git_odb_stream_finalize_write(OdbStreamSafeHandle stream) return id; } - public static void git_odb_stream_free(IntPtr stream) - { - NativeMethods.git_odb_stream_free(stream); - } - #endregion #region git_patch_ @@ -1524,22 +1496,17 @@ public static unsafe Tuple git_patch_line_stats(PatchHandle patch) #region git_packbuilder_ - public static void git_packbuilder_free(IntPtr packbuilder) - { - NativeMethods.git_packbuilder_free(packbuilder); - } - - public static unsafe PackBuilderSafeHandle git_packbuilder_new(RepositoryHandle repo) + public static unsafe PackBuilderHandle git_packbuilder_new(RepositoryHandle repo) { - PackBuilderSafeHandle handle; + git_packbuilder* handle; int res = NativeMethods.git_packbuilder_new(out handle, repo); Ensure.ZeroResult(res); - return handle; + return new PackBuilderHandle(handle, true); } - public static void git_packbuilder_insert(PackBuilderSafeHandle packbuilder, ObjectId targetId, string name) + public static unsafe void git_packbuilder_insert(PackBuilderHandle packbuilder, ObjectId targetId, string name) { GitOid oid = targetId.Oid; @@ -1547,7 +1514,7 @@ public static void git_packbuilder_insert(PackBuilderSafeHandle packbuilder, Obj Ensure.ZeroResult(res); } - internal static void git_packbuilder_insert_commit(PackBuilderSafeHandle packbuilder, ObjectId targetId) + internal static unsafe void git_packbuilder_insert_commit(PackBuilderHandle packbuilder, ObjectId targetId) { GitOid oid = targetId.Oid; @@ -1555,7 +1522,7 @@ internal static void git_packbuilder_insert_commit(PackBuilderSafeHandle packbui Ensure.ZeroResult(res); } - internal static void git_packbuilder_insert_tree(PackBuilderSafeHandle packbuilder, ObjectId targetId) + internal static unsafe void git_packbuilder_insert_tree(PackBuilderHandle packbuilder, ObjectId targetId) { GitOid oid = targetId.Oid; @@ -1563,7 +1530,7 @@ internal static void git_packbuilder_insert_tree(PackBuilderSafeHandle packbuild Ensure.ZeroResult(res); } - public static void git_packbuilder_insert_recur(PackBuilderSafeHandle packbuilder, ObjectId targetId, string name) + public static unsafe void git_packbuilder_insert_recur(PackBuilderHandle packbuilder, ObjectId targetId, string name) { GitOid oid = targetId.Oid; @@ -1571,23 +1538,23 @@ public static void git_packbuilder_insert_recur(PackBuilderSafeHandle packbuilde Ensure.ZeroResult(res); } - public static uint git_packbuilder_set_threads(PackBuilderSafeHandle packbuilder, uint numThreads) + public static unsafe uint git_packbuilder_set_threads(PackBuilderHandle packbuilder, uint numThreads) { return NativeMethods.git_packbuilder_set_threads(packbuilder, numThreads); } - public static void git_packbuilder_write(PackBuilderSafeHandle packbuilder, FilePath path) + public static unsafe void git_packbuilder_write(PackBuilderHandle packbuilder, FilePath path) { int res = NativeMethods.git_packbuilder_write(packbuilder, path, 0, IntPtr.Zero, IntPtr.Zero); Ensure.ZeroResult(res); } - public static uint git_packbuilder_object_count(PackBuilderSafeHandle packbuilder) + public static unsafe uint git_packbuilder_object_count(PackBuilderHandle packbuilder) { return NativeMethods.git_packbuilder_object_count(packbuilder); } - public static uint git_packbuilder_written(PackBuilderSafeHandle packbuilder) + public static unsafe uint git_packbuilder_written(PackBuilderHandle packbuilder) { return NativeMethods.git_packbuilder_written(packbuilder); } @@ -1595,37 +1562,37 @@ public static uint git_packbuilder_written(PackBuilderSafeHandle packbuilder) #region git_rebase - public static unsafe RebaseSafeHandle git_rebase_init( + public static unsafe RebaseHandle git_rebase_init( RepositoryHandle repo, - GitAnnotatedCommitHandle branch, - GitAnnotatedCommitHandle upstream, - GitAnnotatedCommitHandle onto, + AnnotatedCommitHandle branch, + AnnotatedCommitHandle upstream, + AnnotatedCommitHandle onto, GitRebaseOptions options) { - RebaseSafeHandle rebase = null; + git_rebase* rebase = null; int result = NativeMethods.git_rebase_init(out rebase, repo, branch, upstream, onto, options); Ensure.ZeroResult(result); - return rebase; + return new RebaseHandle(rebase, true); } - public static unsafe RebaseSafeHandle git_rebase_open(RepositoryHandle repo, GitRebaseOptions options) + public static unsafe RebaseHandle git_rebase_open(RepositoryHandle repo, GitRebaseOptions options) { - RebaseSafeHandle rebase = null; + git_rebase* rebase = null; int result = NativeMethods.git_rebase_open(out rebase, repo, options); Ensure.ZeroResult(result); - return rebase; + return new RebaseHandle(rebase, true); } - public static long git_rebase_operation_entrycount(RebaseSafeHandle rebase) + public static unsafe long git_rebase_operation_entrycount(RebaseHandle rebase) { return NativeMethods.git_rebase_operation_entrycount(rebase).ConvertToLong(); } - public static long git_rebase_operation_current(RebaseSafeHandle rebase) + public static unsafe long git_rebase_operation_current(RebaseHandle rebase) { UIntPtr result = NativeMethods.git_rebase_operation_current(rebase); @@ -1653,7 +1620,7 @@ private static UIntPtr GIT_REBASE_NO_OPERATION public const long RebaseNoOperation = -1; public static unsafe git_rebase_operation* git_rebase_operation_byindex( - RebaseSafeHandle rebase, + RebaseHandle rebase, long index) { Debug.Assert(index >= 0); @@ -1665,7 +1632,7 @@ private static UIntPtr GIT_REBASE_NO_OPERATION /// /// /// - public static unsafe git_rebase_operation* git_rebase_next(RebaseSafeHandle rebase) + public static unsafe git_rebase_operation* git_rebase_next(RebaseHandle rebase) { git_rebase_operation* ptr; int result = NativeMethods.git_rebase_next(out ptr, rebase); @@ -1679,7 +1646,7 @@ private static UIntPtr GIT_REBASE_NO_OPERATION } public static unsafe GitRebaseCommitResult git_rebase_commit( - RebaseSafeHandle rebase, + RebaseHandle rebase, Identity author, Identity committer) { @@ -1724,8 +1691,8 @@ public struct GitRebaseCommitResult public bool WasPatchAlreadyApplied; } - public static void git_rebase_abort( - RebaseSafeHandle rebase) + public static unsafe void git_rebase_abort( + RebaseHandle rebase) { Ensure.ArgumentNotNull(rebase, "rebase"); @@ -1734,7 +1701,7 @@ public static void git_rebase_abort( } public static unsafe void git_rebase_finish( - RebaseSafeHandle rebase, + RebaseHandle rebase, Identity committer) { Ensure.ArgumentNotNull(rebase, "rebase"); @@ -1747,11 +1714,6 @@ public static unsafe void git_rebase_finish( } } - public static void git_rebase_free(IntPtr rebase) - { - NativeMethods.git_rebase_free(rebase); - } - #endregion #region git_reference_ @@ -1990,39 +1952,39 @@ public static unsafe bool git_refspec_force(git_refspec* refSpec) #region git_remote_ - public static TagFetchMode git_remote_autotag(RemoteSafeHandle remote) + public static unsafe TagFetchMode git_remote_autotag(RemoteHandle remote) { return (TagFetchMode)NativeMethods.git_remote_autotag(remote); } - public static unsafe RemoteSafeHandle git_remote_create(RepositoryHandle repo, string name, string url) + public static unsafe RemoteHandle git_remote_create(RepositoryHandle repo, string name, string url) { - RemoteSafeHandle handle; + git_remote* handle; int res = NativeMethods.git_remote_create(out handle, repo, name, url); Ensure.ZeroResult(res); - return handle; + return new RemoteHandle(handle, true); } - public static unsafe RemoteSafeHandle git_remote_create_with_fetchspec(RepositoryHandle repo, string name, string url, string refspec) + public static unsafe RemoteHandle git_remote_create_with_fetchspec(RepositoryHandle repo, string name, string url, string refspec) { - RemoteSafeHandle handle; + git_remote* handle; int res = NativeMethods.git_remote_create_with_fetchspec(out handle, repo, name, url, refspec); Ensure.ZeroResult(res); - return handle; + return new RemoteHandle(handle, true); } - public static unsafe RemoteSafeHandle git_remote_create_anonymous(RepositoryHandle repo, string url) + public static unsafe RemoteHandle git_remote_create_anonymous(RepositoryHandle repo, string url) { - RemoteSafeHandle handle; + git_remote* handle; int res = NativeMethods.git_remote_create_anonymous(out handle, repo, url); Ensure.ZeroResult(res); - return handle; + return new RemoteHandle(handle, true); } - public static void git_remote_connect(RemoteSafeHandle remote, GitDirection direction, ref GitRemoteCallbacks remoteCallbacks) + public static unsafe void git_remote_connect(RemoteHandle remote, GitDirection direction, ref GitRemoteCallbacks remoteCallbacks) { GitStrArrayManaged customHeaders = new GitStrArrayManaged(); @@ -2049,17 +2011,17 @@ public static unsafe void git_remote_delete(RepositoryHandle repo, string name) Ensure.ZeroResult(res); } - public static unsafe git_refspec* git_remote_get_refspec(RemoteSafeHandle remote, int n) + public static unsafe git_refspec* git_remote_get_refspec(RemoteHandle remote, int n) { return NativeMethods.git_remote_get_refspec(remote, (UIntPtr)n); } - public static int git_remote_refspec_count(RemoteSafeHandle remote) + public static unsafe int git_remote_refspec_count(RemoteHandle remote) { return (int)NativeMethods.git_remote_refspec_count(remote); } - public static IList git_remote_get_fetch_refspecs(RemoteSafeHandle remote) + public static unsafe IList git_remote_get_fetch_refspecs(RemoteHandle remote) { var array = new GitStrArrayNative(); @@ -2076,7 +2038,7 @@ public static IList git_remote_get_fetch_refspecs(RemoteSafeHandle remot } } - public static IList git_remote_get_push_refspecs(RemoteSafeHandle remote) + public static unsafe IList git_remote_get_push_refspecs(RemoteHandle remote) { var array = new GitStrArrayNative(); @@ -2093,7 +2055,7 @@ public static IList git_remote_get_push_refspecs(RemoteSafeHandle remote } } - public static void git_remote_push(RemoteSafeHandle remote, IEnumerable refSpecs, GitPushOptions opts) + public static unsafe void git_remote_push(RemoteHandle remote, IEnumerable refSpecs, GitPushOptions opts) { var array = new GitStrArrayManaged(); @@ -2134,8 +2096,8 @@ public static unsafe void git_remote_add_push(RepositoryHandle repo, string remo Ensure.ZeroResult(res); } - public static void git_remote_fetch( - RemoteSafeHandle remote, IEnumerable refSpecs, + public static unsafe void git_remote_fetch( + RemoteHandle remote, IEnumerable refSpecs, GitFetchOptions fetchOptions, string logMessage) { var array = new GitStrArrayManaged(); @@ -2153,11 +2115,6 @@ public static void git_remote_fetch( } } - public static void git_remote_free(IntPtr remote) - { - NativeMethods.git_remote_free(remote); - } - public static bool git_remote_is_valid_name(string refname) { int res = NativeMethods.git_remote_is_valid_name(refname); @@ -2183,7 +2140,7 @@ public static unsafe IList git_remote_list(RepositoryHandle repo) } } - public static unsafe IEnumerable git_remote_ls(Repository repository, RemoteSafeHandle remote) + public static unsafe IEnumerable git_remote_ls(Repository repository, RemoteHandle remote) { git_remote_head** heads; UIntPtr count; @@ -2236,9 +2193,9 @@ public static unsafe IEnumerable git_remote_ls(Repository repository, return refs; } - public static unsafe RemoteSafeHandle git_remote_lookup(RepositoryHandle repo, string name, bool throwsIfNotFound) + public static unsafe RemoteHandle git_remote_lookup(RepositoryHandle repo, string name, bool throwsIfNotFound) { - RemoteSafeHandle handle; + git_remote* handle; int res = NativeMethods.git_remote_lookup(out handle, repo, name); if (res == (int)GitErrorCode.NotFound && !throwsIfNotFound) @@ -2247,10 +2204,10 @@ public static unsafe RemoteSafeHandle git_remote_lookup(RepositoryHandle repo, s } Ensure.ZeroResult(res); - return handle; + return new RemoteHandle(handle, true); } - public static string git_remote_name(RemoteSafeHandle remote) + public static unsafe string git_remote_name(RemoteHandle remote) { return NativeMethods.git_remote_name(remote); } @@ -2294,12 +2251,12 @@ public static unsafe void git_remote_set_autotag(RepositoryHandle repo, string r NativeMethods.git_remote_set_autotag(repo, remote, value); } - public static string git_remote_url(RemoteSafeHandle remote) + public static unsafe string git_remote_url(RemoteHandle remote) { return NativeMethods.git_remote_url(remote); } - public static string git_remote_pushurl(RemoteSafeHandle remote) + public static unsafe string git_remote_pushurl(RemoteHandle remote) { return NativeMethods.git_remote_pushurl(remote); } @@ -2400,13 +2357,13 @@ public static unsafe string git_repository_message(RepositoryHandle repo) } } - public static unsafe ObjectDatabaseSafeHandle git_repository_odb(RepositoryHandle repo) + public static unsafe ObjectDatabaseHandle git_repository_odb(RepositoryHandle repo) { - ObjectDatabaseSafeHandle handle; + git_odb* handle; int res = NativeMethods.git_repository_odb(out handle, repo); Ensure.ZeroResult(res); - return handle; + return new ObjectDatabaseHandle(handle, true); } public static unsafe RepositoryHandle git_repository_open(string path) @@ -2503,7 +2460,7 @@ public static unsafe void git_repository_set_head_detached(RepositoryHandle repo Ensure.ZeroResult(res); } - public static unsafe void git_repository_set_head_detached_from_annotated(RepositoryHandle repo, GitAnnotatedCommitHandle commit) + public static unsafe void git_repository_set_head_detached_from_annotated(RepositoryHandle repo, AnnotatedCommitHandle commit) { int res = NativeMethods.git_repository_set_head_detached_from_annotated(repo, commit); Ensure.ZeroResult(res); @@ -2552,9 +2509,9 @@ public static unsafe void git_revert( #region git_revparse_ - public static unsafe Tuple git_revparse_ext(RepositoryHandle repo, string objectish) + public static unsafe Tuple git_revparse_ext(RepositoryHandle repo, string objectish) { - GitObjectSafeHandle obj; + git_object* obj; git_reference* reference; int res = NativeMethods.git_revparse_ext(out obj, out reference, repo, objectish); @@ -2572,10 +2529,10 @@ public static unsafe Tuple git_revparse_ex break; } - return new Tuple(obj, new ReferenceHandle(reference, true)); + return new Tuple(new ObjectHandle(obj, true), new ReferenceHandle(reference, true)); } - public static GitObjectSafeHandle git_revparse_single(RepositoryHandle repo, string objectish) + public static ObjectHandle git_revparse_single(RepositoryHandle repo, string objectish) { var handles = git_revparse_ext(repo, objectish); @@ -2593,28 +2550,23 @@ public static GitObjectSafeHandle git_revparse_single(RepositoryHandle repo, str #region git_revwalk_ - public static void git_revwalk_free(IntPtr walker) - { - NativeMethods.git_revwalk_free(walker); - } - - public static void git_revwalk_hide(RevWalkerSafeHandle walker, ObjectId commit_id) + public static unsafe void git_revwalk_hide(RevWalkerHandle walker, ObjectId commit_id) { GitOid oid = commit_id.Oid; int res = NativeMethods.git_revwalk_hide(walker, ref oid); Ensure.ZeroResult(res); } - public static unsafe RevWalkerSafeHandle git_revwalk_new(RepositoryHandle repo) + public static unsafe RevWalkerHandle git_revwalk_new(RepositoryHandle repo) { - RevWalkerSafeHandle handle; + git_revwalk* handle; int res = NativeMethods.git_revwalk_new(out handle, repo); Ensure.ZeroResult(res); - return handle; + return new RevWalkerHandle(handle, true); } - public static ObjectId git_revwalk_next(RevWalkerSafeHandle walker) + public static unsafe ObjectId git_revwalk_next(RevWalkerHandle walker) { GitOid ret; int res = NativeMethods.git_revwalk_next(out ret, walker); @@ -2629,24 +2581,24 @@ public static ObjectId git_revwalk_next(RevWalkerSafeHandle walker) return ret; } - public static void git_revwalk_push(RevWalkerSafeHandle walker, ObjectId id) + public static unsafe void git_revwalk_push(RevWalkerHandle walker, ObjectId id) { GitOid oid = id.Oid; int res = NativeMethods.git_revwalk_push(walker, ref oid); Ensure.ZeroResult(res); } - public static void git_revwalk_reset(RevWalkerSafeHandle walker) + public static unsafe void git_revwalk_reset(RevWalkerHandle walker) { NativeMethods.git_revwalk_reset(walker); } - public static void git_revwalk_sorting(RevWalkerSafeHandle walker, CommitSortStrategies options) + public static unsafe void git_revwalk_sorting(RevWalkerHandle walker, CommitSortStrategies options) { NativeMethods.git_revwalk_sorting(walker, options); } - public static void git_revwalk_simplify_first_parent(RevWalkerSafeHandle walker) + public static unsafe void git_revwalk_simplify_first_parent(RevWalkerHandle walker) { NativeMethods.git_revwalk_simplify_first_parent(walker); } @@ -2821,10 +2773,10 @@ public static unsafe int git_status_list_entrycount(StatusListHandle list) /// Returns a handle to the corresponding submodule, /// or an invalid handle if a submodule is not found. /// - public static unsafe SubmoduleSafeHandle git_submodule_lookup(RepositoryHandle repo, FilePath name) + public static unsafe SubmoduleHandle git_submodule_lookup(RepositoryHandle repo, FilePath name) { - SubmoduleSafeHandle reference; - var res = NativeMethods.git_submodule_lookup(out reference, repo, name); + git_submodule* submodule; + var res = NativeMethods.git_submodule_lookup(out submodule, repo, name); switch (res) { @@ -2835,7 +2787,7 @@ public static unsafe SubmoduleSafeHandle git_submodule_lookup(RepositoryHandle r default: Ensure.ZeroResult(res); - return reference; + return new SubmoduleHandle(submodule, true); } } @@ -2855,65 +2807,60 @@ public static unsafe ICollection git_submodule_foreach(Reposit return git_foreach(resultSelector, c => NativeMethods.git_submodule_foreach(repo, (x, y, p) => c(x, y, p), IntPtr.Zero)); } - public static void git_submodule_add_to_index(SubmoduleSafeHandle submodule, bool write_index) + public static unsafe void git_submodule_add_to_index(SubmoduleHandle submodule, bool write_index) { var res = NativeMethods.git_submodule_add_to_index(submodule, write_index); Ensure.ZeroResult(res); } - public static void git_submodule_update(SubmoduleSafeHandle submodule, bool init, ref GitSubmoduleOptions options) + public static unsafe void git_submodule_update(SubmoduleHandle submodule, bool init, ref GitSubmoduleOptions options) { var res = NativeMethods.git_submodule_update(submodule, init, ref options); Ensure.ZeroResult(res); } - public static void git_submodule_free(IntPtr submodule) - { - NativeMethods.git_submodule_free(submodule); - } - - public static string git_submodule_path(SubmoduleSafeHandle submodule) + public static unsafe string git_submodule_path(SubmoduleHandle submodule) { return NativeMethods.git_submodule_path(submodule); } - public static string git_submodule_url(SubmoduleSafeHandle submodule) + public static unsafe string git_submodule_url(SubmoduleHandle submodule) { return NativeMethods.git_submodule_url(submodule); } - public static unsafe ObjectId git_submodule_index_id(SubmoduleSafeHandle submodule) + public static unsafe ObjectId git_submodule_index_id(SubmoduleHandle submodule) { return ObjectId.BuildFromPtr(NativeMethods.git_submodule_index_id(submodule)); } - public static unsafe ObjectId git_submodule_head_id(SubmoduleSafeHandle submodule) + public static unsafe ObjectId git_submodule_head_id(SubmoduleHandle submodule) { Console.WriteLine("got git_oid for head {0}", NativeMethods.git_submodule_head_id(submodule) == null); return ObjectId.BuildFromPtr(NativeMethods.git_submodule_head_id(submodule)); } - public static unsafe ObjectId git_submodule_wd_id(SubmoduleSafeHandle submodule) + public static unsafe ObjectId git_submodule_wd_id(SubmoduleHandle submodule) { return ObjectId.BuildFromPtr(NativeMethods.git_submodule_wd_id(submodule)); } - public static SubmoduleIgnore git_submodule_ignore(SubmoduleSafeHandle submodule) + public static unsafe SubmoduleIgnore git_submodule_ignore(SubmoduleHandle submodule) { return NativeMethods.git_submodule_ignore(submodule); } - public static SubmoduleUpdate git_submodule_update_strategy(SubmoduleSafeHandle submodule) + public static unsafe SubmoduleUpdate git_submodule_update_strategy(SubmoduleHandle submodule) { return NativeMethods.git_submodule_update_strategy(submodule); } - public static SubmoduleRecurse git_submodule_fetch_recurse_submodules(SubmoduleSafeHandle submodule) + public static unsafe SubmoduleRecurse git_submodule_fetch_recurse_submodules(SubmoduleHandle submodule) { return NativeMethods.git_submodule_fetch_recurse_submodules(submodule); } - public static void git_submodule_reload(SubmoduleSafeHandle submodule) + public static unsafe void git_submodule_reload(SubmoduleHandle submodule) { var res = NativeMethods.git_submodule_reload(submodule, false); Ensure.ZeroResult(res); @@ -2927,7 +2874,7 @@ public static unsafe SubmoduleStatus git_submodule_status(RepositoryHandle repo, return status; } - public static void git_submodule_init(SubmoduleSafeHandle submodule, bool overwrite) + public static unsafe void git_submodule_init(SubmoduleHandle submodule, bool overwrite) { var res = NativeMethods.git_submodule_init(submodule, overwrite); Ensure.ZeroResult(res); @@ -3009,17 +2956,17 @@ public static unsafe IList git_tag_list(RepositoryHandle repo) } } - public static string git_tag_message(GitObjectSafeHandle tag) + public static unsafe string git_tag_message(ObjectHandle tag) { return NativeMethods.git_tag_message(tag); } - public static string git_tag_name(GitObjectSafeHandle tag) + public static unsafe string git_tag_name(ObjectHandle tag) { return NativeMethods.git_tag_name(tag); } - public static unsafe Signature git_tag_tagger(GitObjectSafeHandle tag) + public static unsafe Signature git_tag_tagger(ObjectHandle tag) { git_signature* taggerHandle = NativeMethods.git_tag_tagger(tag); @@ -3034,12 +2981,12 @@ public static unsafe Signature git_tag_tagger(GitObjectSafeHandle tag) return tagger; } - public static unsafe ObjectId git_tag_target_id(GitObjectSafeHandle tag) + public static unsafe ObjectId git_tag_target_id(ObjectHandle tag) { return ObjectId.BuildFromPtr(NativeMethods.git_tag_target_id(tag)); } - public static GitObjectType git_tag_target_type(GitObjectSafeHandle tag) + public static unsafe GitObjectType git_tag_target_type(ObjectHandle tag) { return NativeMethods.git_tag_target_type(tag); } @@ -3104,7 +3051,7 @@ public static unsafe Mode git_tree_entry_attributes(git_tree_entry* entry) return (Mode)NativeMethods.git_tree_entry_filemode(entry); } - public static unsafe TreeEntryHandle git_tree_entry_byindex(GitObjectSafeHandle tree, long idx) + public static unsafe TreeEntryHandle git_tree_entry_byindex(ObjectHandle tree, long idx) { var handle = NativeMethods.git_tree_entry_byindex(tree, (UIntPtr)idx); if (handle == null) @@ -3148,7 +3095,7 @@ public static unsafe GitObjectType git_tree_entry_type(git_tree_entry* entry) return NativeMethods.git_tree_entry_type(entry); } - public static int git_tree_entrycount(GitObjectSafeHandle tree) + public static unsafe int git_tree_entrycount(ObjectHandle tree) { return (int)NativeMethods.git_tree_entrycount(tree); } @@ -3157,21 +3104,16 @@ public static int git_tree_entrycount(GitObjectSafeHandle tree) #region git_treebuilder_ - public static unsafe TreeBuilderSafeHandle git_treebuilder_new(RepositoryHandle repo) + public static unsafe TreeBuilderHandle git_treebuilder_new(RepositoryHandle repo) { - TreeBuilderSafeHandle builder; + git_treebuilder* builder; int res = NativeMethods.git_treebuilder_new(out builder, repo, IntPtr.Zero); Ensure.ZeroResult(res); - return builder; - } - - public static void git_treebuilder_free(IntPtr bld) - { - NativeMethods.git_treebuilder_free(bld); + return new TreeBuilderHandle(builder, true); } - public static void git_treebuilder_insert(TreeBuilderSafeHandle builder, string treeentry_name, TreeEntryDefinition treeEntryDefinition) + public static unsafe void git_treebuilder_insert(TreeBuilderHandle builder, string treeentry_name, TreeEntryDefinition treeEntryDefinition) { GitOid oid = treeEntryDefinition.TargetId.Oid; int res = NativeMethods.git_treebuilder_insert(IntPtr.Zero, builder, treeentry_name, ref oid, @@ -3179,7 +3121,7 @@ public static void git_treebuilder_insert(TreeBuilderSafeHandle builder, string Ensure.ZeroResult(res); } - public static ObjectId git_treebuilder_write(TreeBuilderSafeHandle bld) + public static unsafe ObjectId git_treebuilder_write(TreeBuilderHandle bld) { GitOid oid; int res = NativeMethods.git_treebuilder_write(out oid, bld); diff --git a/LibGit2Sharp/Core/RawContentStream.cs b/LibGit2Sharp/Core/RawContentStream.cs index 566eb5851..92b4b3bf0 100644 --- a/LibGit2Sharp/Core/RawContentStream.cs +++ b/LibGit2Sharp/Core/RawContentStream.cs @@ -7,13 +7,13 @@ namespace LibGit2Sharp.Core { internal class RawContentStream : UnmanagedMemoryStream { - private readonly GitObjectSafeHandle handle; + private readonly ObjectHandle handle; private readonly ICollection linkedResources; internal unsafe RawContentStream( - GitObjectSafeHandle handle, - Func bytePtrProvider, - Func sizeProvider, + ObjectHandle handle, + Func bytePtrProvider, + Func sizeProvider, ICollection linkedResources = null) : base((byte*)Wrap(handle, bytePtrProvider, linkedResources).ToPointer(), Wrap(handle, sizeProvider, linkedResources)) @@ -23,8 +23,8 @@ internal unsafe RawContentStream( } private static T Wrap( - GitObjectSafeHandle handle, - Func provider, + ObjectHandle handle, + Func provider, IEnumerable linkedResources) { T value; @@ -43,7 +43,7 @@ private static T Wrap( } private static void Dispose( - GitObjectSafeHandle handle, + ObjectHandle handle, IEnumerable linkedResources) { handle.SafeDispose(); diff --git a/LibGit2Sharp/Core/SubmoduleLazyGroup.cs b/LibGit2Sharp/Core/SubmoduleLazyGroup.cs index 10df34a41..42e40e07b 100644 --- a/LibGit2Sharp/Core/SubmoduleLazyGroup.cs +++ b/LibGit2Sharp/Core/SubmoduleLazyGroup.cs @@ -3,7 +3,7 @@ namespace LibGit2Sharp.Core { - internal class SubmoduleLazyGroup : LazyGroup + internal class SubmoduleLazyGroup : LazyGroup { private readonly string name; @@ -13,7 +13,7 @@ public SubmoduleLazyGroup(Repository repo, string name) this.name = name; } - protected override void EvaluateInternal(Action evaluator) + protected override void EvaluateInternal(Action evaluator) { repo.Submodules.Lookup(name, handle => diff --git a/LibGit2Sharp/GitObject.cs b/LibGit2Sharp/GitObject.cs index e2653ca0f..6530f212c 100644 --- a/LibGit2Sharp/GitObject.cs +++ b/LibGit2Sharp/GitObject.cs @@ -85,7 +85,7 @@ internal static GitObject BuildFrom(Repository repo, ObjectId id, GitObjectType internal Commit DereferenceToCommit(bool throwsIfCanNotBeDereferencedToACommit) { - using (GitObjectSafeHandle peeledHandle = Proxy.git_object_peel(repo.Handle, Id, GitObjectType.Commit, throwsIfCanNotBeDereferencedToACommit)) + using (ObjectHandle peeledHandle = Proxy.git_object_peel(repo.Handle, Id, GitObjectType.Commit, throwsIfCanNotBeDereferencedToACommit)) { if (peeledHandle == null) { diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index a0f1afe77..38b364581 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -73,19 +73,16 @@ - - - @@ -142,7 +139,6 @@ - @@ -185,7 +181,6 @@ - @@ -195,7 +190,6 @@ - @@ -224,7 +218,6 @@ - @@ -264,11 +257,6 @@ - - - - - @@ -291,11 +279,6 @@ - - - Code - - @@ -341,7 +324,6 @@ - diff --git a/LibGit2Sharp/Network.cs b/LibGit2Sharp/Network.cs index 611db7395..105a58af1 100644 --- a/LibGit2Sharp/Network.cs +++ b/LibGit2Sharp/Network.cs @@ -115,7 +115,7 @@ public virtual IEnumerable ListReferences(string url, CredentialsHand private IEnumerable ListReferencesInternal(string url, CredentialsHandler credentialsProvider) { - using (RemoteSafeHandle remoteHandle = BuildRemoteSafeHandle(repository.Handle, url)) + using (RemoteHandle remoteHandle = BuildRemoteHandle(repository.Handle, url)) { GitRemoteCallbacks gitCallbacks = new GitRemoteCallbacks { version = 1 }; @@ -130,24 +130,24 @@ private IEnumerable ListReferencesInternal(string url, CredentialsHan } } - static RemoteSafeHandle BuildRemoteSafeHandle(RepositoryHandle repoHandle, Remote remote) + static RemoteHandle BuildRemoteHandle(RepositoryHandle repoHandle, Remote remote) { Debug.Assert(repoHandle != null && !repoHandle.IsNull); Debug.Assert(remote != null && remote.Name != null); - RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repoHandle, remote.Name, true); - Debug.Assert(remoteHandle != null && !(remoteHandle.IsInvalid || remoteHandle.IsInvalid)); + RemoteHandle remoteHandle = Proxy.git_remote_lookup(repoHandle, remote.Name, true); + Debug.Assert(remoteHandle != null && !(remoteHandle.IsNull)); return remoteHandle; } - static RemoteSafeHandle BuildRemoteSafeHandle(RepositoryHandle repoHandle, string url) + static RemoteHandle BuildRemoteHandle(RepositoryHandle repoHandle, string url) { Debug.Assert(repoHandle != null && !repoHandle.IsNull); Debug.Assert(url != null); - RemoteSafeHandle remoteHandle = Proxy.git_remote_create_anonymous(repoHandle, url); - Debug.Assert(remoteHandle != null && !(remoteHandle.IsClosed || remoteHandle.IsInvalid)); + RemoteHandle remoteHandle = Proxy.git_remote_create_anonymous(repoHandle, url); + Debug.Assert(remoteHandle != null && !(remoteHandle.IsNull)); return remoteHandle; } @@ -159,7 +159,7 @@ static void DoFetch( string logMessage, IEnumerable refspecs) { - using (RemoteSafeHandle remoteHandle = BuildRemoteSafeHandle(repoHandle, remote)) + using (RemoteHandle remoteHandle = BuildRemoteHandle(repoHandle, remote)) { DoFetch(options, remoteHandle, logMessage, refspecs); } @@ -172,15 +172,15 @@ static void DoFetch( string logMessage, IEnumerable refspecs) { - using (RemoteSafeHandle remoteHandle = BuildRemoteSafeHandle(repoHandle, url)) + using (RemoteHandle remoteHandle = BuildRemoteHandle(repoHandle, url)) { DoFetch(options, remoteHandle, logMessage, refspecs); } } - private static void DoFetch(FetchOptions options, RemoteSafeHandle remoteHandle, string logMessage, IEnumerable refspecs) + private static void DoFetch(FetchOptions options, RemoteHandle remoteHandle, string logMessage, IEnumerable refspecs) { - Debug.Assert(remoteHandle != null && !remoteHandle.IsClosed && !remoteHandle.IsInvalid); + Debug.Assert(remoteHandle != null && !remoteHandle.IsNull); options = options ?? new FetchOptions(); @@ -517,7 +517,7 @@ public virtual void Push(Remote remote, IEnumerable pushRefSpecs, PushOp } // Load the remote. - using (RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, remote.Name, true)) + using (RemoteHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, remote.Name, true)) { var callbacks = new RemoteCallbacks(pushOptions); GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks(); diff --git a/LibGit2Sharp/Note.cs b/LibGit2Sharp/Note.cs index e40bec67e..1df0125e4 100644 --- a/LibGit2Sharp/Note.cs +++ b/LibGit2Sharp/Note.cs @@ -50,7 +50,7 @@ private Note(ObjectId blobId, string message, ObjectId targetObjectId, string @n /// public virtual ObjectId TargetObjectId { get; private set; } - internal static Note BuildFromPtr(NoteSafeHandle note, string @namespace, ObjectId targetObjectId) + internal static Note BuildFromPtr(NoteHandle note, string @namespace, ObjectId targetObjectId) { ObjectId oid = Proxy.git_note_id(note); string message = Proxy.git_note_message(note); diff --git a/LibGit2Sharp/NoteCollection.cs b/LibGit2Sharp/NoteCollection.cs index 7c8c8ecc8..6c3710f30 100644 --- a/LibGit2Sharp/NoteCollection.cs +++ b/LibGit2Sharp/NoteCollection.cs @@ -123,7 +123,7 @@ public virtual IEnumerable this[string @namespace] string canonicalNamespace = NormalizeToCanonicalName(@namespace); - using (NoteSafeHandle noteHandle = Proxy.git_note_read(repo.Handle, canonicalNamespace, id)) + using (NoteHandle noteHandle = Proxy.git_note_read(repo.Handle, canonicalNamespace, id)) { return noteHandle == null ? null diff --git a/LibGit2Sharp/ObjectDatabase.cs b/LibGit2Sharp/ObjectDatabase.cs index 7085b3df3..85efc55a3 100644 --- a/LibGit2Sharp/ObjectDatabase.cs +++ b/LibGit2Sharp/ObjectDatabase.cs @@ -17,7 +17,7 @@ namespace LibGit2Sharp public class ObjectDatabase : IEnumerable { private readonly Repository repo; - private readonly ObjectDatabaseSafeHandle handle; + private readonly ObjectDatabaseHandle handle; /// /// Needed for mocking purposes. diff --git a/LibGit2Sharp/PackBuilder.cs b/LibGit2Sharp/PackBuilder.cs index 1f797c9bf..032181a1e 100644 --- a/LibGit2Sharp/PackBuilder.cs +++ b/LibGit2Sharp/PackBuilder.cs @@ -10,7 +10,7 @@ namespace LibGit2Sharp /// public sealed class PackBuilder : IDisposable { - private readonly PackBuilderSafeHandle packBuilderHandle; + private readonly PackBuilderHandle packBuilderHandle; /// /// Constructs a PackBuilder for a . @@ -119,7 +119,7 @@ internal long WrittenObjectsCount get { return Proxy.git_packbuilder_written(packBuilderHandle); } } - internal PackBuilderSafeHandle Handle + internal PackBuilderHandle Handle { get { return packBuilderHandle; } } diff --git a/LibGit2Sharp/Rebase.cs b/LibGit2Sharp/Rebase.cs index 26e67335d..00dc3f267 100644 --- a/LibGit2Sharp/Rebase.cs +++ b/LibGit2Sharp/Rebase.cs @@ -62,6 +62,13 @@ internal Rebase(Repository repo) this.repository = repo; } + unsafe AnnotatedCommitHandle AnnotatedCommitHandleFromRefHandle(ReferenceHandle refHandle) + { + return (refHandle == null) ? + new AnnotatedCommitHandle(null, false) : + Proxy.git_annotated_commit_from_ref(this.repository.Handle, refHandle); + } + /// /// Start a rebase operation. /// @@ -92,14 +99,6 @@ public virtual RebaseResult Start(Branch branch, Branch upstream, Branch onto, I this.repository.Refs.RetrieveReferencePtr(b.CanonicalName); }; - Func AnnotatedCommitHandleFromRefHandle = - (ReferenceHandle refHandle) => - { - return (refHandle == null) ? - new GitAnnotatedCommitHandle() : - Proxy.git_annotated_commit_from_ref(this.repository.Handle, refHandle); - }; - using (GitCheckoutOptsWrapper checkoutOptionsWrapper = new GitCheckoutOptsWrapper(options)) { GitRebaseOptions gitRebaseOptions = new GitRebaseOptions() @@ -111,10 +110,10 @@ public virtual RebaseResult Start(Branch branch, Branch upstream, Branch onto, I using (ReferenceHandle branchRefPtr = RefHandleFromBranch(branch)) using (ReferenceHandle upstreamRefPtr = RefHandleFromBranch(upstream)) using (ReferenceHandle ontoRefPtr = RefHandleFromBranch(onto)) - using (GitAnnotatedCommitHandle annotatedBranchCommitHandle = AnnotatedCommitHandleFromRefHandle(branchRefPtr)) - using (GitAnnotatedCommitHandle upstreamRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(upstreamRefPtr)) - using (GitAnnotatedCommitHandle ontoRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(ontoRefPtr)) - using (RebaseSafeHandle rebaseOperationHandle = Proxy.git_rebase_init(this.repository.Handle, + using (AnnotatedCommitHandle annotatedBranchCommitHandle = AnnotatedCommitHandleFromRefHandle(branchRefPtr)) + using (AnnotatedCommitHandle upstreamRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(upstreamRefPtr)) + using (AnnotatedCommitHandle ontoRefAnnotatedCommitHandle = AnnotatedCommitHandleFromRefHandle(ontoRefPtr)) + using (RebaseHandle rebaseOperationHandle = Proxy.git_rebase_init(this.repository.Handle, annotatedBranchCommitHandle, upstreamRefAnnotatedCommitHandle, ontoRefAnnotatedCommitHandle, @@ -150,7 +149,7 @@ public virtual unsafe RebaseResult Continue(Identity committer, RebaseOptions op checkout_options = checkoutOptionsWrapper.Options, }; - using (RebaseSafeHandle rebase = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) + using (RebaseHandle rebase = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { // TODO: Should we check the pre-conditions for committing here // for instance - what if we had failed on the git_rebase_finish call, @@ -213,7 +212,7 @@ public virtual void Abort(RebaseOptions options) checkout_options = checkoutOptionsWrapper.Options, }; - using (RebaseSafeHandle rebase = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) + using (RebaseHandle rebase = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { Proxy.git_rebase_abort(rebase); } @@ -235,7 +234,7 @@ public virtual unsafe RebaseStepInfo GetCurrentStepInfo() version = 1, }; - using (RebaseSafeHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) + using (RebaseHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { long currentStepIndex = Proxy.git_rebase_operation_current(rebaseHandle); git_rebase_operation* gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, currentStepIndex); @@ -263,7 +262,7 @@ public virtual unsafe RebaseStepInfo GetStepInfo(long stepIndex) version = 1, }; - using (RebaseSafeHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) + using (RebaseHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { git_rebase_operation* gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, stepIndex); var stepInfo = new RebaseStepInfo(gitRebasestepInfo->type, @@ -284,7 +283,7 @@ public virtual long GetCurrentStepIndex() version = 1, }; - using (RebaseSafeHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) + using (RebaseHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { return Proxy.git_rebase_operation_current(rebaseHandle); } @@ -301,7 +300,7 @@ public virtual long GetTotalStepCount() version = 1, }; - using (RebaseSafeHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) + using (RebaseHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions)) { return Proxy.git_rebase_operation_entrycount(rebaseHandle); } diff --git a/LibGit2Sharp/RebaseOperationImpl.cs b/LibGit2Sharp/RebaseOperationImpl.cs index f7d9e539f..66283568a 100644 --- a/LibGit2Sharp/RebaseOperationImpl.cs +++ b/LibGit2Sharp/RebaseOperationImpl.cs @@ -14,7 +14,7 @@ internal class RebaseOperationImpl /// Committer Identity to use for the rebased commits. /// Options controlling rebase behavior. /// RebaseResult that describes the result of the rebase operation. - public static RebaseResult Run(RebaseSafeHandle rebaseOperationHandle, + public static RebaseResult Run(RebaseHandle rebaseOperationHandle, Repository repository, Identity committer, RebaseOptions options) @@ -50,7 +50,7 @@ public static RebaseResult Run(RebaseSafeHandle rebaseOperationHandle, return rebaseResult; } - private static RebaseResult CompleteRebase(RebaseSafeHandle rebaseOperationHandle, Identity committer) + private static RebaseResult CompleteRebase(RebaseHandle rebaseOperationHandle, Identity committer) { long totalStepCount = Proxy.git_rebase_operation_entrycount(rebaseOperationHandle); @@ -74,7 +74,7 @@ private static RebaseResult CompleteRebase(RebaseSafeHandle rebaseOperationHandl /// /// /// - private static unsafe RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperationHandle, + private static unsafe RebaseResult RunRebaseStep(RebaseHandle rebaseOperationHandle, Repository repository, Identity committer, RebaseOptions options, @@ -153,7 +153,7 @@ private static unsafe RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperatio return rebaseSequenceResult; } - private static RebaseStepResult ApplyPickStep(RebaseSafeHandle rebaseOperationHandle, Repository repository, Identity committer, RebaseOptions options, RebaseStepInfo stepToApplyInfo) + private static RebaseStepResult ApplyPickStep(RebaseHandle rebaseOperationHandle, Repository repository, Identity committer, RebaseOptions options, RebaseStepInfo stepToApplyInfo) { RebaseStepResult rebaseStepResult; @@ -212,7 +212,7 @@ private struct RebaseProgress /// private static RebaseProgress NextRebaseStep( Repository repository, - RebaseSafeHandle rebaseOperationHandle) + RebaseHandle rebaseOperationHandle) { // stepBeingApplied indicates the step that will be applied by by git_rebase_next. // The current step does not get incremented until git_rebase_next (except on diff --git a/LibGit2Sharp/RefSpecCollection.cs b/LibGit2Sharp/RefSpecCollection.cs index 69c098107..b656ef862 100644 --- a/LibGit2Sharp/RefSpecCollection.cs +++ b/LibGit2Sharp/RefSpecCollection.cs @@ -22,14 +22,14 @@ public class RefSpecCollection : IEnumerable protected RefSpecCollection() { } - internal RefSpecCollection(RemoteSafeHandle handle) + internal RefSpecCollection(RemoteHandle handle) { Ensure.ArgumentNotNull(handle, "handle"); refspecs = RetrieveRefSpecs(handle); } - static unsafe IList RetrieveRefSpecs(RemoteSafeHandle remoteHandle) + static unsafe IList RetrieveRefSpecs(RemoteHandle remoteHandle) { int count = Proxy.git_remote_refspec_count(remoteHandle); List refSpecs = new List(); diff --git a/LibGit2Sharp/Remote.cs b/LibGit2Sharp/Remote.cs index a28457713..091b222ec 100644 --- a/LibGit2Sharp/Remote.cs +++ b/LibGit2Sharp/Remote.cs @@ -28,7 +28,7 @@ public class Remote : IEquatable, IBelongToARepository protected Remote() { } - private Remote(RemoteSafeHandle handle, Repository repository) + private Remote(RemoteHandle handle, Repository repository) { this.repository = repository; Name = Proxy.git_remote_name(handle); @@ -38,7 +38,7 @@ private Remote(RemoteSafeHandle handle, Repository repository) refSpecs = new RefSpecCollection(handle); } - internal static Remote BuildFromPtr(RemoteSafeHandle handle, Repository repo) + internal static Remote BuildFromPtr(RemoteHandle handle, Repository repo) { var remote = new Remote(handle, repo); @@ -100,7 +100,7 @@ public virtual IEnumerable PushRefSpecs /// The transformed reference. internal unsafe string FetchSpecTransformToSource(string reference) { - using (RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, Name, true)) + using (RemoteHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, Name, true)) { git_refspec* fetchSpecPtr = Proxy.git_remote_get_refspec(remoteHandle, 0); return Proxy.git_refspec_rtransform(fetchSpecPtr, reference); diff --git a/LibGit2Sharp/RemoteCollection.cs b/LibGit2Sharp/RemoteCollection.cs index 6ab1a3faf..8733c922c 100644 --- a/LibGit2Sharp/RemoteCollection.cs +++ b/LibGit2Sharp/RemoteCollection.cs @@ -43,7 +43,7 @@ internal Remote RemoteForName(string name, bool shouldThrowIfNotFound = true) { Ensure.ArgumentNotNull(name, "name"); - using (RemoteSafeHandle handle = Proxy.git_remote_lookup(repository.Handle, name, shouldThrowIfNotFound)) + using (RemoteHandle handle = Proxy.git_remote_lookup(repository.Handle, name, shouldThrowIfNotFound)) { return handle == null ? null : Remote.BuildFromPtr(handle, this.repository); } @@ -102,7 +102,7 @@ public virtual Remote Add(string name, string url) Ensure.ArgumentNotNull(name, "name"); Ensure.ArgumentNotNull(url, "url"); - using (RemoteSafeHandle handle = Proxy.git_remote_create(repository.Handle, name, url)) + using (RemoteHandle handle = Proxy.git_remote_create(repository.Handle, name, url)) { return Remote.BuildFromPtr(handle, this.repository); } @@ -121,7 +121,7 @@ public virtual Remote Add(string name, string url, string fetchRefSpec) Ensure.ArgumentNotNull(url, "url"); Ensure.ArgumentNotNull(fetchRefSpec, "fetchRefSpec"); - using (RemoteSafeHandle handle = Proxy.git_remote_create_with_fetchspec(repository.Handle, name, url, fetchRefSpec)) + using (RemoteHandle handle = Proxy.git_remote_create_with_fetchspec(repository.Handle, name, url, fetchRefSpec)) { return Remote.BuildFromPtr(handle, this.repository); } diff --git a/LibGit2Sharp/RemoteUpdater.cs b/LibGit2Sharp/RemoteUpdater.cs index cb0e08b3c..14d5c82df 100644 --- a/LibGit2Sharp/RemoteUpdater.cs +++ b/LibGit2Sharp/RemoteUpdater.cs @@ -36,7 +36,7 @@ internal RemoteUpdater(Repository repo, Remote remote) private IEnumerable GetFetchRefSpecs() { - using (RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repo.Handle, remote.Name, true)) + using (RemoteHandle remoteHandle = Proxy.git_remote_lookup(repo.Handle, remote.Name, true)) { return Proxy.git_remote_get_fetch_refspecs(remoteHandle); } @@ -54,7 +54,7 @@ private void SetFetchRefSpecs(IEnumerable value) private IEnumerable GetPushRefSpecs() { - using (RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repo.Handle, remote.Name, true)) + using (RemoteHandle remoteHandle = Proxy.git_remote_lookup(repo.Handle, remote.Name, true)) { return Proxy.git_remote_get_push_refspecs(remoteHandle); } diff --git a/LibGit2Sharp/Repository.cs b/LibGit2Sharp/Repository.cs index 3554fcf43..951f16cff 100644 --- a/LibGit2Sharp/Repository.cs +++ b/LibGit2Sharp/Repository.cs @@ -482,9 +482,9 @@ internal GitObject LookupInternal(ObjectId id, GitObjectType type, FilePath know { Ensure.ArgumentNotNull(id, "id"); - using (GitObjectSafeHandle obj = Proxy.git_object_lookup(handle, id, type)) + using (ObjectHandle obj = Proxy.git_object_lookup(handle, id, type)) { - if (obj == null || obj.IsInvalid) + if (obj == null || obj.IsNull) { return null; } @@ -514,7 +514,7 @@ internal GitObject Lookup(string objectish, GitObjectType type, LookUpOptions lo Ensure.ArgumentNotNullOrEmptyString(objectish, "objectish"); GitObject obj; - using (GitObjectSafeHandle sh = Proxy.git_revparse_single(handle, objectish)) + using (ObjectHandle sh = Proxy.git_revparse_single(handle, objectish)) { if (sh == null) { @@ -584,7 +584,7 @@ public static IEnumerable ListRemoteReferences(string url, Credential Ensure.ArgumentNotNull(url, "url"); using (RepositoryHandle repositoryHandle = Proxy.git_repository_new()) - using (RemoteSafeHandle remoteHandle = Proxy.git_remote_create_anonymous(repositoryHandle, url)) + using (RemoteHandle remoteHandle = Proxy.git_remote_create_anonymous(repositoryHandle, url)) { var gitCallbacks = new GitRemoteCallbacks { version = 1 }; @@ -1165,7 +1165,7 @@ private IEnumerable RetrieveParentsOfTheCommitBeingCreated(bool amendPre /// /// Clean the working tree by removing files that are not under version control. /// - public void RemoveUntrackedFiles() + public unsafe void RemoveUntrackedFiles() { var options = new GitCheckoutOpts { @@ -1174,7 +1174,7 @@ public void RemoveUntrackedFiles() | CheckoutStrategy.GIT_CHECKOUT_ALLOW_CONFLICTS, }; - Proxy.git_checkout_index(Handle, new NullGitObjectSafeHandle(), ref options); + Proxy.git_checkout_index(Handle, new ObjectHandle(null, false), ref options); } private void CleanupDisposableDependencies() @@ -1205,7 +1205,7 @@ public MergeResult Merge(Commit commit, Signature merger, MergeOptions options) options = options ?? new MergeOptions(); - using (GitAnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_lookup(Handle, commit.Id.Oid)) + using (AnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_lookup(Handle, commit.Id.Oid)) { return Merge(new[] { annotatedCommitHandle }, merger, options); } @@ -1226,7 +1226,7 @@ public MergeResult Merge(Branch branch, Signature merger, MergeOptions options) options = options ?? new MergeOptions(); using (ReferenceHandle referencePtr = Refs.RetrieveReferencePtr(branch.CanonicalName)) - using (GitAnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_from_ref(Handle, referencePtr)) + using (AnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_from_ref(Handle, referencePtr)) { return Merge(new[] { annotatedCommitHandle }, merger, options); } @@ -1276,7 +1276,7 @@ public MergeResult MergeFetchedRefs(Signature merger, MergeOptions options) expectedRef); } - GitAnnotatedCommitHandle[] annotatedCommitHandles = fetchHeads.Select(fetchHead => + AnnotatedCommitHandle[] annotatedCommitHandles = fetchHeads.Select(fetchHead => Proxy.git_annotated_commit_from_fetchhead(Handle, fetchHead.RemoteCanonicalName, fetchHead.Url, fetchHead.Target.Id.Oid)).ToArray(); try @@ -1287,7 +1287,7 @@ public MergeResult MergeFetchedRefs(Signature merger, MergeOptions options) finally { // Cleanup. - foreach (GitAnnotatedCommitHandle annotatedCommitHandle in annotatedCommitHandles) + foreach (AnnotatedCommitHandle annotatedCommitHandle in annotatedCommitHandles) { annotatedCommitHandle.Dispose(); } @@ -1470,7 +1470,7 @@ private FastForwardStrategy FastForwardStrategyFromMergePreference(GitMergePrefe /// The of who is performing the merge. /// Specifies optional parameters controlling merge behavior; if null, the defaults are used. /// The of the merge. - private MergeResult Merge(GitAnnotatedCommitHandle[] annotatedCommits, Signature merger, MergeOptions options) + private MergeResult Merge(AnnotatedCommitHandle[] annotatedCommits, Signature merger, MergeOptions options) { GitMergeAnalysis mergeAnalysis; GitMergePreference mergePreference; @@ -1550,7 +1550,7 @@ private MergeResult Merge(GitAnnotatedCommitHandle[] annotatedCommits, Signature /// The of who is performing the merge. /// Specifies optional parameters controlling merge behavior; if null, the defaults are used. /// The of the merge. - private MergeResult NormalMerge(GitAnnotatedCommitHandle[] annotatedCommits, Signature merger, MergeOptions options) + private MergeResult NormalMerge(AnnotatedCommitHandle[] annotatedCommits, Signature merger, MergeOptions options) { MergeResult mergeResult; var mergeOptions = new GitMergeOpts @@ -1595,7 +1595,7 @@ private MergeResult NormalMerge(GitAnnotatedCommitHandle[] annotatedCommits, Sig /// The merge head handle to fast-forward merge. /// Options controlling merge behavior. /// The of the merge. - private MergeResult FastForwardMerge(GitAnnotatedCommitHandle annotatedCommit, MergeOptions options) + private MergeResult FastForwardMerge(AnnotatedCommitHandle annotatedCommit, MergeOptions options) { ObjectId id = Proxy.git_annotated_commit_id(annotatedCommit); Commit fastForwardCommit = (Commit)Lookup(id, ObjectType.Commit); diff --git a/LibGit2Sharp/SubmoduleCollection.cs b/LibGit2Sharp/SubmoduleCollection.cs index 2ad23f6df..f5f50fa12 100644 --- a/LibGit2Sharp/SubmoduleCollection.cs +++ b/LibGit2Sharp/SubmoduleCollection.cs @@ -146,7 +146,7 @@ internal bool TryStage(string relativePath, bool writeIndex) }); } - internal T Lookup(string name, Func selector, bool throwIfNotFound = false) + internal T Lookup(string name, Func selector, bool throwIfNotFound = false) { using (var handle = Proxy.git_submodule_lookup(repo.Handle, name)) { diff --git a/LibGit2Sharp/TreeDefinition.cs b/LibGit2Sharp/TreeDefinition.cs index 8f016c204..68f287879 100644 --- a/LibGit2Sharp/TreeDefinition.cs +++ b/LibGit2Sharp/TreeDefinition.cs @@ -397,7 +397,7 @@ private static Tuple ExtractPosixLeadingSegment(FilePath targetP private class TreeBuilder : IDisposable { - private readonly TreeBuilderSafeHandle handle; + private readonly TreeBuilderHandle handle; public TreeBuilder(Repository repo) { From c9c49b10980b92a7c3bc3df3260d643ee372de35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 15 Jan 2016 11:05:44 +0100 Subject: [PATCH 29/50] Use a common abstract class for the handles Instead of copying each and every class, we can put the common functionality into a single class, using a void pointer and use the template to generate the bits which need to know about the pointer we're dealing with. Freeing and the implicit conversion to the pointer type are thus still there, but we now don't copy the disposing code everywhere. --- LibGit2Sharp/Core/Handles/Libgit2Object.cs | 73 + LibGit2Sharp/Core/Handles/Objects.cs | 1490 +++----------------- LibGit2Sharp/Core/Handles/Objects.tt | 64 +- LibGit2Sharp/Core/Proxy.cs | 12 +- LibGit2Sharp/LibGit2Sharp.csproj | 1 + LibGit2Sharp/RebaseOperationImpl.cs | 1 + LibGit2Sharp/Reference.cs | 2 +- LibGit2Sharp/TreeEntry.cs | 4 +- 8 files changed, 286 insertions(+), 1361 deletions(-) create mode 100644 LibGit2Sharp/Core/Handles/Libgit2Object.cs diff --git a/LibGit2Sharp/Core/Handles/Libgit2Object.cs b/LibGit2Sharp/Core/Handles/Libgit2Object.cs new file mode 100644 index 000000000..134e75313 --- /dev/null +++ b/LibGit2Sharp/Core/Handles/Libgit2Object.cs @@ -0,0 +1,73 @@ +using System; + +namespace LibGit2Sharp.Core.Handles +{ + internal unsafe abstract class Libgit2Object : IDisposable + { + protected void* ptr; + + internal void* Handle + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + internal unsafe Libgit2Object(void* handle, bool owned) + { + this.ptr = handle; + this.owned = owned; + } + + internal unsafe Libgit2Object(IntPtr ptr, bool owned) + { + this.ptr = ptr.ToPointer(); + this.owned = owned; + } + + ~Libgit2Object() + { + Dispose(false); + } + + internal bool IsNull + { + get + { + return ptr == null; + } + } + + internal IntPtr AsIntPtr() + { + return new IntPtr(ptr); + } + + public abstract void Free(); + + void Dispose(bool disposing) + { + if (!disposed) + { + if (owned) + { + Free(); + } + + ptr = null; + } + + disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + } +} + diff --git a/LibGit2Sharp/Core/Handles/Objects.cs b/LibGit2Sharp/Core/Handles/Objects.cs index 827b6252d..f904b75b9 100644 --- a/LibGit2Sharp/Core/Handles/Objects.cs +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -1,1662 +1,558 @@  using System; -namespace LibGit2Sharp.Core +namespace LibGit2Sharp.Core.Handles { - internal unsafe class TreeEntryHandle : IDisposable + internal unsafe class TreeEntryHandle : Libgit2Object { - git_tree_entry* ptr; - internal git_tree_entry* Handle + internal TreeEntryHandle(git_tree_entry *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe TreeEntryHandle(git_tree_entry* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe TreeEntryHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_tree_entry*) ptr.ToPointer(); - this.owned = owned; - } - - ~TreeEntryHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal TreeEntryHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_tree_entry_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_tree_entry_free((git_tree_entry*) ptr); } public static implicit operator git_tree_entry*(TreeEntryHandle handle) { - return handle.Handle; + return (git_tree_entry*) handle.Handle; } } - internal unsafe class ReferenceHandle : IDisposable + internal unsafe class ReferenceHandle : Libgit2Object { - git_reference* ptr; - internal git_reference* Handle + internal ReferenceHandle(git_reference *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe ReferenceHandle(git_reference* handle, bool owned) + internal ReferenceHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe ReferenceHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_reference*) ptr.ToPointer(); - this.owned = owned; - } - - ~ReferenceHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_reference_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_reference_free((git_reference*) ptr); } public static implicit operator git_reference*(ReferenceHandle handle) { - return handle.Handle; + return (git_reference*) handle.Handle; } } - internal unsafe class RepositoryHandle : IDisposable + internal unsafe class RepositoryHandle : Libgit2Object { - git_repository* ptr; - internal git_repository* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe RepositoryHandle(git_repository* handle, bool owned) + internal RepositoryHandle(git_repository *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe RepositoryHandle(IntPtr ptr, bool owned) + internal RepositoryHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_repository*) ptr.ToPointer(); - this.owned = owned; - } - - ~RepositoryHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_repository_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_repository_free((git_repository*) ptr); } public static implicit operator git_repository*(RepositoryHandle handle) { - return handle.Handle; + return (git_repository*) handle.Handle; } } - internal unsafe class SignatureHandle : IDisposable + internal unsafe class SignatureHandle : Libgit2Object { - git_signature* ptr; - internal git_signature* Handle + internal SignatureHandle(git_signature *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe SignatureHandle(git_signature* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe SignatureHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_signature*) ptr.ToPointer(); - this.owned = owned; - } - - ~SignatureHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal SignatureHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_signature_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_signature_free((git_signature*) ptr); } public static implicit operator git_signature*(SignatureHandle handle) { - return handle.Handle; + return (git_signature*) handle.Handle; } } - internal unsafe class StatusListHandle : IDisposable + internal unsafe class StatusListHandle : Libgit2Object { - git_status_list* ptr; - internal git_status_list* Handle + internal StatusListHandle(git_status_list *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe StatusListHandle(git_status_list* handle, bool owned) + internal StatusListHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe StatusListHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_status_list*) ptr.ToPointer(); - this.owned = owned; - } - - ~StatusListHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_status_list_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_status_list_free((git_status_list*) ptr); } public static implicit operator git_status_list*(StatusListHandle handle) { - return handle.Handle; + return (git_status_list*) handle.Handle; } } - internal unsafe class BlameHandle : IDisposable + internal unsafe class BlameHandle : Libgit2Object { - git_blame* ptr; - internal git_blame* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe BlameHandle(git_blame* handle, bool owned) + internal BlameHandle(git_blame *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe BlameHandle(IntPtr ptr, bool owned) + internal BlameHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_blame*) ptr.ToPointer(); - this.owned = owned; - } - - ~BlameHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_blame_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_blame_free((git_blame*) ptr); } public static implicit operator git_blame*(BlameHandle handle) { - return handle.Handle; + return (git_blame*) handle.Handle; } } - internal unsafe class DiffHandle : IDisposable + internal unsafe class DiffHandle : Libgit2Object { - git_diff* ptr; - internal git_diff* Handle + internal DiffHandle(git_diff *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe DiffHandle(git_diff* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe DiffHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_diff*) ptr.ToPointer(); - this.owned = owned; - } - - ~DiffHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal DiffHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_diff_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_diff_free((git_diff*) ptr); } public static implicit operator git_diff*(DiffHandle handle) { - return handle.Handle; + return (git_diff*) handle.Handle; } } - internal unsafe class PatchHandle : IDisposable + internal unsafe class PatchHandle : Libgit2Object { - git_patch* ptr; - internal git_patch* Handle + internal PatchHandle(git_patch *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe PatchHandle(git_patch* handle, bool owned) + internal PatchHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe PatchHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_patch*) ptr.ToPointer(); - this.owned = owned; - } - - ~PatchHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_patch_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_patch_free((git_patch*) ptr); } public static implicit operator git_patch*(PatchHandle handle) { - return handle.Handle; + return (git_patch*) handle.Handle; } } - internal unsafe class ConfigurationHandle : IDisposable + internal unsafe class ConfigurationHandle : Libgit2Object { - git_config* ptr; - internal git_config* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe ConfigurationHandle(git_config* handle, bool owned) + internal ConfigurationHandle(git_config *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe ConfigurationHandle(IntPtr ptr, bool owned) + internal ConfigurationHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_config*) ptr.ToPointer(); - this.owned = owned; - } - - ~ConfigurationHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_config_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_config_free((git_config*) ptr); } public static implicit operator git_config*(ConfigurationHandle handle) { - return handle.Handle; + return (git_config*) handle.Handle; } } - internal unsafe class ConflictIteratorHandle : IDisposable + internal unsafe class ConflictIteratorHandle : Libgit2Object { - git_index_conflict_iterator* ptr; - internal git_index_conflict_iterator* Handle + internal ConflictIteratorHandle(git_index_conflict_iterator *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe ConflictIteratorHandle(git_index_conflict_iterator* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe ConflictIteratorHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_index_conflict_iterator*) ptr.ToPointer(); - this.owned = owned; - } - - ~ConflictIteratorHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal ConflictIteratorHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_index_conflict_iterator_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_index_conflict_iterator_free((git_index_conflict_iterator*) ptr); } public static implicit operator git_index_conflict_iterator*(ConflictIteratorHandle handle) { - return handle.Handle; + return (git_index_conflict_iterator*) handle.Handle; } } - internal unsafe class IndexHandle : IDisposable + internal unsafe class IndexHandle : Libgit2Object { - git_index* ptr; - internal git_index* Handle + internal IndexHandle(git_index *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe IndexHandle(git_index* handle, bool owned) + internal IndexHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe IndexHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_index*) ptr.ToPointer(); - this.owned = owned; - } - - ~IndexHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_index_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_index_free((git_index*) ptr); } public static implicit operator git_index*(IndexHandle handle) { - return handle.Handle; + return (git_index*) handle.Handle; } } - internal unsafe class ReflogHandle : IDisposable + internal unsafe class ReflogHandle : Libgit2Object { - git_reflog* ptr; - internal git_reflog* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe ReflogHandle(git_reflog* handle, bool owned) + internal ReflogHandle(git_reflog *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe ReflogHandle(IntPtr ptr, bool owned) + internal ReflogHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_reflog*) ptr.ToPointer(); - this.owned = owned; - } - - ~ReflogHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_reflog_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_reflog_free((git_reflog*) ptr); } public static implicit operator git_reflog*(ReflogHandle handle) { - return handle.Handle; + return (git_reflog*) handle.Handle; } } - internal unsafe class TreeBuilderHandle : IDisposable + internal unsafe class TreeBuilderHandle : Libgit2Object { - git_treebuilder* ptr; - internal git_treebuilder* Handle + internal TreeBuilderHandle(git_treebuilder *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe TreeBuilderHandle(git_treebuilder* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe TreeBuilderHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_treebuilder*) ptr.ToPointer(); - this.owned = owned; - } - - ~TreeBuilderHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal TreeBuilderHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_treebuilder_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_treebuilder_free((git_treebuilder*) ptr); } public static implicit operator git_treebuilder*(TreeBuilderHandle handle) { - return handle.Handle; + return (git_treebuilder*) handle.Handle; } } - internal unsafe class PackBuilderHandle : IDisposable + internal unsafe class PackBuilderHandle : Libgit2Object { - git_packbuilder* ptr; - internal git_packbuilder* Handle + internal PackBuilderHandle(git_packbuilder *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe PackBuilderHandle(git_packbuilder* handle, bool owned) + internal PackBuilderHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe PackBuilderHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_packbuilder*) ptr.ToPointer(); - this.owned = owned; - } - - ~PackBuilderHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_packbuilder_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_packbuilder_free((git_packbuilder*) ptr); } public static implicit operator git_packbuilder*(PackBuilderHandle handle) { - return handle.Handle; + return (git_packbuilder*) handle.Handle; } } - internal unsafe class NoteHandle : IDisposable + internal unsafe class NoteHandle : Libgit2Object { - git_note* ptr; - internal git_note* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe NoteHandle(git_note* handle, bool owned) + internal NoteHandle(git_note *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe NoteHandle(IntPtr ptr, bool owned) + internal NoteHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_note*) ptr.ToPointer(); - this.owned = owned; - } - - ~NoteHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_note_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_note_free((git_note*) ptr); } public static implicit operator git_note*(NoteHandle handle) { - return handle.Handle; + return (git_note*) handle.Handle; } } - internal unsafe class DescribeResultHandle : IDisposable + internal unsafe class DescribeResultHandle : Libgit2Object { - git_describe_result* ptr; - internal git_describe_result* Handle + internal DescribeResultHandle(git_describe_result *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe DescribeResultHandle(git_describe_result* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe DescribeResultHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_describe_result*) ptr.ToPointer(); - this.owned = owned; - } - - ~DescribeResultHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal DescribeResultHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_describe_result_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_describe_result_free((git_describe_result*) ptr); } public static implicit operator git_describe_result*(DescribeResultHandle handle) { - return handle.Handle; + return (git_describe_result*) handle.Handle; } } - internal unsafe class SubmoduleHandle : IDisposable + internal unsafe class SubmoduleHandle : Libgit2Object { - git_submodule* ptr; - internal git_submodule* Handle + internal SubmoduleHandle(git_submodule *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe SubmoduleHandle(git_submodule* handle, bool owned) + internal SubmoduleHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe SubmoduleHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_submodule*) ptr.ToPointer(); - this.owned = owned; - } - - ~SubmoduleHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_submodule_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_submodule_free((git_submodule*) ptr); } public static implicit operator git_submodule*(SubmoduleHandle handle) { - return handle.Handle; + return (git_submodule*) handle.Handle; } } - internal unsafe class AnnotatedCommitHandle : IDisposable + internal unsafe class AnnotatedCommitHandle : Libgit2Object { - git_annotated_commit* ptr; - internal git_annotated_commit* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe AnnotatedCommitHandle(git_annotated_commit* handle, bool owned) + internal AnnotatedCommitHandle(git_annotated_commit *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe AnnotatedCommitHandle(IntPtr ptr, bool owned) + internal AnnotatedCommitHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_annotated_commit*) ptr.ToPointer(); - this.owned = owned; - } - - ~AnnotatedCommitHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_annotated_commit_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_annotated_commit_free((git_annotated_commit*) ptr); } public static implicit operator git_annotated_commit*(AnnotatedCommitHandle handle) { - return handle.Handle; + return (git_annotated_commit*) handle.Handle; } } - internal unsafe class ObjectDatabaseHandle : IDisposable + internal unsafe class ObjectDatabaseHandle : Libgit2Object { - git_odb* ptr; - internal git_odb* Handle + internal ObjectDatabaseHandle(git_odb *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe ObjectDatabaseHandle(git_odb* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe ObjectDatabaseHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_odb*) ptr.ToPointer(); - this.owned = owned; - } - - ~ObjectDatabaseHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal ObjectDatabaseHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_odb_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_odb_free((git_odb*) ptr); } public static implicit operator git_odb*(ObjectDatabaseHandle handle) { - return handle.Handle; + return (git_odb*) handle.Handle; } } - internal unsafe class RevWalkerHandle : IDisposable + internal unsafe class RevWalkerHandle : Libgit2Object { - git_revwalk* ptr; - internal git_revwalk* Handle + internal RevWalkerHandle(git_revwalk *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe RevWalkerHandle(git_revwalk* handle, bool owned) + internal RevWalkerHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe RevWalkerHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_revwalk*) ptr.ToPointer(); - this.owned = owned; - } - - ~RevWalkerHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_revwalk_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_revwalk_free((git_revwalk*) ptr); } public static implicit operator git_revwalk*(RevWalkerHandle handle) { - return handle.Handle; + return (git_revwalk*) handle.Handle; } } - internal unsafe class RemoteHandle : IDisposable + internal unsafe class RemoteHandle : Libgit2Object { - git_remote* ptr; - internal git_remote* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe RemoteHandle(git_remote* handle, bool owned) + internal RemoteHandle(git_remote *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe RemoteHandle(IntPtr ptr, bool owned) + internal RemoteHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_remote*) ptr.ToPointer(); - this.owned = owned; - } - - ~RemoteHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_remote_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_remote_free((git_remote*) ptr); } public static implicit operator git_remote*(RemoteHandle handle) { - return handle.Handle; + return (git_remote*) handle.Handle; } } - internal unsafe class ObjectHandle : IDisposable + internal unsafe class ObjectHandle : Libgit2Object { - git_object* ptr; - internal git_object* Handle + internal ObjectHandle(git_object *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe ObjectHandle(git_object* handle, bool owned) - { - this.ptr = handle; - this.owned = owned; - } - - public unsafe ObjectHandle(IntPtr ptr, bool owned) - { - this.ptr = (git_object*) ptr.ToPointer(); - this.owned = owned; - } - - ~ObjectHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() + internal ObjectHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - return new IntPtr(ptr); } - void Dispose(bool disposing) + public override void Free() { - if (!disposed) - { - if (owned) - { - NativeMethods.git_object_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_object_free((git_object*) ptr); } public static implicit operator git_object*(ObjectHandle handle) { - return handle.Handle; + return (git_object*) handle.Handle; } } - internal unsafe class RebaseHandle : IDisposable + internal unsafe class RebaseHandle : Libgit2Object { - git_rebase* ptr; - internal git_rebase* Handle + internal RebaseHandle(git_rebase *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe RebaseHandle(git_rebase* handle, bool owned) + internal RebaseHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe RebaseHandle(IntPtr ptr, bool owned) + public override void Free() { - this.ptr = (git_rebase*) ptr.ToPointer(); - this.owned = owned; - } - - ~RebaseHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_rebase_free(ptr); - ptr = null; - } - } - - disposed = true; - } - - public void Dispose() - { - Dispose(true); + NativeMethods.git_rebase_free((git_rebase*) ptr); } public static implicit operator git_rebase*(RebaseHandle handle) { - return handle.Handle; + return (git_rebase*) handle.Handle; } } - internal unsafe class OdbStreamHandle : IDisposable + internal unsafe class OdbStreamHandle : Libgit2Object { - git_odb_stream* ptr; - internal git_odb_stream* Handle - { - get - { - return ptr; - } - } - - bool owned; - bool disposed; - - public unsafe OdbStreamHandle(git_odb_stream* handle, bool owned) + internal OdbStreamHandle(git_odb_stream *ptr, bool owned) + : base((void *) ptr, owned) { - this.ptr = handle; - this.owned = owned; } - public unsafe OdbStreamHandle(IntPtr ptr, bool owned) + internal OdbStreamHandle(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = (git_odb_stream*) ptr.ToPointer(); - this.owned = owned; - } - - ~OdbStreamHandle() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.git_odb_stream_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.git_odb_stream_free((git_odb_stream*) ptr); } public static implicit operator git_odb_stream*(OdbStreamHandle handle) { - return handle.Handle; + return (git_odb_stream*) handle.Handle; } } diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt index d5f341bca..3ecfe811e 100644 --- a/LibGit2Sharp/Core/Handles/Objects.tt +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -7,7 +7,7 @@ using System; -namespace LibGit2Sharp.Core +namespace LibGit2Sharp.Core.Handles { <# @@ -68,72 +68,26 @@ var csNames = new[] { for (var i = 0; i < cNames.Length; i++) { #> - internal unsafe class <#= csNames[i] #> : IDisposable + internal unsafe class <#= csNames[i] #> : Libgit2Object { - <#= cNames[i] #>* ptr; - internal <#= cNames[i] #>* Handle + internal <#= csNames[i] #>(<#= cNames[i] #> *ptr, bool owned) + : base((void *) ptr, owned) { - get - { - return ptr; - } } - bool owned; - bool disposed; - - public unsafe <#= csNames[i] #>(<#= cNames[i] #>* handle, bool owned) + internal <#= csNames[i] #>(IntPtr ptr, bool owned) + : base(ptr, owned) { - this.ptr = handle; - this.owned = owned; - } - - public unsafe <#= csNames[i] #>(IntPtr ptr, bool owned) - { - this.ptr = (<#= cNames[i] #>*) ptr.ToPointer(); - this.owned = owned; - } - - ~<#= csNames[i] #>() - { - Dispose(false); - } - - internal bool IsNull - { - get - { - return ptr == null; - } - } - - internal IntPtr AsIntPtr() - { - return new IntPtr(ptr); - } - - void Dispose(bool disposing) - { - if (!disposed) - { - if (owned) - { - NativeMethods.<#= cNames[i] #>_free(ptr); - ptr = null; - } - } - - disposed = true; } - public void Dispose() + public override void Free() { - Dispose(true); + NativeMethods.<#= cNames[i] #>_free((<#= cNames[i] #>*) ptr); } public static implicit operator <#= cNames[i] #>*(<#= csNames[i] #> handle) { - return handle.Handle; + return (<#= cNames[i] #>*) handle.Handle; } } diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 13e5c33b0..b043e70b7 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -200,7 +200,7 @@ public static unsafe ReferenceHandle git_branch_create_from_annotated(Repository public static unsafe void git_branch_delete(ReferenceHandle reference) { - int res = NativeMethods.git_branch_delete(reference.Handle); + int res = NativeMethods.git_branch_delete(reference); Ensure.ZeroResult(res); } @@ -245,7 +245,7 @@ public static void git_branch_iterator_free(IntPtr iter) public static unsafe ReferenceHandle git_branch_move(ReferenceHandle reference, string new_branch_name, bool force) { git_reference* ref_out; - int res = NativeMethods.git_branch_move(out ref_out, reference.Handle, new_branch_name, force); + int res = NativeMethods.git_branch_move(out ref_out, reference, new_branch_name, force); Ensure.ZeroResult(res); return new ReferenceHandle(ref_out, true); } @@ -1140,7 +1140,7 @@ public static unsafe AnnotatedCommitHandle git_annotated_commit_from_ref(Reposit { git_annotated_commit* commit; - int res = NativeMethods.git_annotated_commit_from_ref(out commit, repo, reference.Handle); + int res = NativeMethods.git_annotated_commit_from_ref(out commit, repo, reference); Ensure.ZeroResult(res); @@ -1821,7 +1821,7 @@ public static unsafe ReferenceHandle git_reference_rename( { git_reference* ref_out; - int res = NativeMethods.git_reference_rename(out ref_out, reference.Handle, newName, allowOverwrite, logMessage); + int res = NativeMethods.git_reference_rename(out ref_out, reference, newName, allowOverwrite, logMessage); Ensure.ZeroResult(res); return new ReferenceHandle(ref_out, true); @@ -1832,7 +1832,7 @@ public static unsafe ReferenceHandle git_reference_set_target(ReferenceHandle re GitOid oid = id.Oid; git_reference* ref_out; - int res = NativeMethods.git_reference_set_target(out ref_out, reference.Handle, ref oid, logMessage); + int res = NativeMethods.git_reference_set_target(out ref_out, reference, ref oid, logMessage); Ensure.ZeroResult(res); return new ReferenceHandle(ref_out, true); @@ -1842,7 +1842,7 @@ public static unsafe ReferenceHandle git_reference_symbolic_set_target(Reference { git_reference* ref_out; - int res = NativeMethods.git_reference_symbolic_set_target(out ref_out, reference.Handle, target, logMessage); + int res = NativeMethods.git_reference_symbolic_set_target(out ref_out, reference, target, logMessage); Ensure.ZeroResult(res); return new ReferenceHandle(ref_out, true); diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 38b364581..0cf7598e8 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -342,6 +342,7 @@ Objects.tt + diff --git a/LibGit2Sharp/RebaseOperationImpl.cs b/LibGit2Sharp/RebaseOperationImpl.cs index 66283568a..c35564573 100644 --- a/LibGit2Sharp/RebaseOperationImpl.cs +++ b/LibGit2Sharp/RebaseOperationImpl.cs @@ -1,5 +1,6 @@ using System; using LibGit2Sharp.Core; +using LibGit2Sharp.Core.Handles; using System.Globalization; namespace LibGit2Sharp diff --git a/LibGit2Sharp/Reference.cs b/LibGit2Sharp/Reference.cs index 340ba5df3..40a85f79f 100644 --- a/LibGit2Sharp/Reference.cs +++ b/LibGit2Sharp/Reference.cs @@ -39,7 +39,7 @@ internal Reference(IRepository repo, string canonicalName, string targetIdentifi // This overload lets public-facing methods avoid having to use the pointers directly internal static unsafe T BuildFromPtr(ReferenceHandle handle, Repository repo) where T : Reference { - return BuildFromPtr(handle.Handle, repo); + return BuildFromPtr((git_reference*) handle.Handle, repo); } internal static unsafe T BuildFromPtr(git_reference* handle, Repository repo) where T : Reference diff --git a/LibGit2Sharp/TreeEntry.cs b/LibGit2Sharp/TreeEntry.cs index 3c80f606d..f3713a776 100644 --- a/LibGit2Sharp/TreeEntry.cs +++ b/LibGit2Sharp/TreeEntry.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.Runtime.InteropServices; using LibGit2Sharp.Core; +using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { @@ -27,9 +28,8 @@ public class TreeEntry : IEquatable protected TreeEntry() { } - internal unsafe TreeEntry(TreeEntryHandle handle, ObjectId parentTreeId, Repository repo, FilePath parentPath) + internal unsafe TreeEntry(TreeEntryHandle entry, ObjectId parentTreeId, Repository repo, FilePath parentPath) { - var entry = handle.Handle; this.parentTreeId = parentTreeId; this.repo = repo; targetOid = Proxy.git_tree_entry_id(entry); From 5516201eadbb00ac81ad0340ae425e2b05c4b223 Mon Sep 17 00:00:00 2001 From: Edward Thomson Date: Fri, 4 Mar 2016 17:00:08 -0500 Subject: [PATCH 30/50] Bump version number to 0.23 (prerelease) --- LibGit2Sharp/Properties/AssemblyInfo.cs | 6 +++--- appveyor.yml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/LibGit2Sharp/Properties/AssemblyInfo.cs b/LibGit2Sharp/Properties/AssemblyInfo.cs index b848dc65a..34c8f06bd 100644 --- a/LibGit2Sharp/Properties/AssemblyInfo.cs +++ b/LibGit2Sharp/Properties/AssemblyInfo.cs @@ -42,6 +42,6 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.22.0")] -[assembly: AssemblyFileVersion("0.22.0")] -[assembly: AssemblyInformationalVersion("0.22.0-dev00000000000000")] +[assembly: AssemblyVersion("0.23.0")] +[assembly: AssemblyFileVersion("0.23.0")] +[assembly: AssemblyInformationalVersion("0.23.0-dev00000000000000")] diff --git a/appveyor.yml b/appveyor.yml index c7a8f9fd2..dd4c82f1e 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -16,7 +16,7 @@ environment: secure: nuzUT+HecXGIi3KaPd/1hgFEZJan/j6+oNbPV75JKjk= coverity_email: secure: eGVilNg1Yuq+Xj+SW8r3WCtjnzhoDV0sNJkma4NRq7A= - version : 0.22.0 + version : 0.23.0 matrix: - xunit_runner: xunit.console.x86.exe Arch: 32 From 3bbf91c43e8db8996d10a3fb4514d12161a7812d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 4 Mar 2016 14:11:08 +0100 Subject: [PATCH 31/50] Remove deprecated methods and types --- LibGit2Sharp.Tests/CheckoutFixture.cs | 17 ---- LibGit2Sharp/CheckoutConflictException.cs | 38 ++++++- LibGit2Sharp/CommitFilter.cs | 31 ------ LibGit2Sharp/CommitLog.cs | 24 ----- LibGit2Sharp/CompareOptions.cs | 6 -- LibGit2Sharp/Configuration.cs | 30 ------ LibGit2Sharp/FileStatus.cs | 48 --------- LibGit2Sharp/IQueryableCommitLog.cs | 18 ---- LibGit2Sharp/IRepository.cs | 12 --- LibGit2Sharp/LibGit2Sharp.csproj | 3 - LibGit2Sharp/MergeConflictException.cs | 61 ------------ LibGit2Sharp/MergeOptions.cs | 6 -- LibGit2Sharp/NoteCollection.cs | 30 ------ LibGit2Sharp/ReferenceWrapper.cs | 9 -- LibGit2Sharp/ReflogEntry.cs | 9 -- LibGit2Sharp/Repository.cs | 15 --- LibGit2Sharp/RepositoryExtensions.cs | 116 ---------------------- 17 files changed, 37 insertions(+), 436 deletions(-) delete mode 100644 LibGit2Sharp/MergeConflictException.cs diff --git a/LibGit2Sharp.Tests/CheckoutFixture.cs b/LibGit2Sharp.Tests/CheckoutFixture.cs index 132cb68ec..80cb9727d 100644 --- a/LibGit2Sharp.Tests/CheckoutFixture.cs +++ b/LibGit2Sharp.Tests/CheckoutFixture.cs @@ -1029,23 +1029,6 @@ public void CanCheckoutPathFromCurrentBranch(string fileName) } } - [Fact] - public void CanCatchDeprecatedException() - { - bool caught = false; - - try - { - throw new CheckoutConflictException(); - } - catch (MergeConflictException) - { - caught = true; - } - - Assert.True(caught); - } - /// /// Helper method to populate a simple repository with /// a single file and two branches. diff --git a/LibGit2Sharp/CheckoutConflictException.cs b/LibGit2Sharp/CheckoutConflictException.cs index 811e2183a..a06360afb 100644 --- a/LibGit2Sharp/CheckoutConflictException.cs +++ b/LibGit2Sharp/CheckoutConflictException.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.Serialization; using LibGit2Sharp.Core; namespace LibGit2Sharp @@ -9,7 +10,7 @@ namespace LibGit2Sharp /// in the working directory. /// [Serializable] - public class CheckoutConflictException : MergeConflictException + public class CheckoutConflictException : LibGit2SharpException { /// /// Initializes a new instance of the class. @@ -17,6 +18,41 @@ public class CheckoutConflictException : MergeConflictException public CheckoutConflictException() { } + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// A message that describes the error. + public CheckoutConflictException(string message) + : base(message) + { } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// A composite format string for use in . + /// An object array that contains zero or more objects to format. + public CheckoutConflictException(string format, params object[] args) + : base(format, args) + { } + + /// + /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception. If the parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception. + public CheckoutConflictException(string message, Exception innerException) + : base(message, innerException) + { } + + /// + /// Initializes a new instance of the class with a serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected CheckoutConflictException(SerializationInfo info, StreamingContext context) + : base(info, context) + { } + internal CheckoutConflictException(string message, GitErrorCode code, GitErrorCategory category) : base(message, code, category) { } diff --git a/LibGit2Sharp/CommitFilter.cs b/LibGit2Sharp/CommitFilter.cs index fe0bfd127..56b23389c 100644 --- a/LibGit2Sharp/CommitFilter.cs +++ b/LibGit2Sharp/CommitFilter.cs @@ -28,22 +28,6 @@ public CommitFilter() /// public CommitSortStrategies SortBy { get; set; } - /// - /// A pointer to a commit object or a list of pointers to consider as starting points. - /// - /// Can be either a containing the sha or reference canonical name to use, - /// a , a , a , a , - /// a , an or even a mixed collection of all of the above. - /// By default, the will be used as boundary. - /// - /// - [Obsolete("This property will be removed in the next release. Please use IncludeReachableFrom instead.")] - public object Since - { - get { return IncludeReachableFrom; } - set { IncludeReachableFrom = value; } - } - /// /// A pointer to a commit object or a list of pointers to consider as starting points. /// @@ -60,21 +44,6 @@ internal IList SinceList get { return ToList(IncludeReachableFrom); } } - /// - /// A pointer to a commit object or a list of pointers which will be excluded (along with ancestors) from the enumeration. - /// - /// Can be either a containing the sha or reference canonical name to use, - /// a , a , a , a , - /// a , an or even a mixed collection of all of the above. - /// - /// - [Obsolete("This property will be removed in the next release. Please use ExcludeReachableFrom instead.")] - public object Until - { - get { return ExcludeReachableFrom; } - set { ExcludeReachableFrom = value; } - } - /// /// A pointer to a commit object or a list of pointers which will be excluded (along with ancestors) from the enumeration. /// diff --git a/LibGit2Sharp/CommitLog.cs b/LibGit2Sharp/CommitLog.cs index 7568181d3..f21af0da7 100644 --- a/LibGit2Sharp/CommitLog.cs +++ b/LibGit2Sharp/CommitLog.cs @@ -105,30 +105,6 @@ public IEnumerable QueryBy(string path, FollowFilter filter) return new FileHistory(repo, path, new CommitFilter { SortBy = filter.SortBy }); } - /// - /// Find the best possible merge base given two s. - /// - /// The first . - /// The second . - /// The merge base or null if none found. - [Obsolete("This method will be removed in the next release. Please use ObjectDatabase.FindMergeBase() instead.")] - public Commit FindMergeBase(Commit first, Commit second) - { - return repo.ObjectDatabase.FindMergeBase(first, second); - } - - /// - /// Find the best possible merge base given two or more according to the . - /// - /// The s for which to find the merge base. - /// The strategy to leverage in order to find the merge base. - /// The merge base or null if none found. - [Obsolete("This method will be removed in the next release. Please use ObjectDatabase.FindMergeBase() instead.")] - public Commit FindMergeBase(IEnumerable commits, MergeBaseFindingStrategy strategy) - { - return repo.ObjectDatabase.FindMergeBase(commits, strategy); - } - private class CommitEnumerator : IEnumerator { private readonly Repository repo; diff --git a/LibGit2Sharp/CompareOptions.cs b/LibGit2Sharp/CompareOptions.cs index 6b3acdfe6..fbd147c79 100644 --- a/LibGit2Sharp/CompareOptions.cs +++ b/LibGit2Sharp/CompareOptions.cs @@ -39,12 +39,6 @@ public CompareOptions() /// public bool IncludeUnmodified { get; set; } - /// - /// Use the "patience diff" algorithm. - /// - [Obsolete("This property will be removed in the next release. Please use Algorithm instead.")] - public bool UsePatienceAlgorithm { get; set; } - /// /// Algorithm to be used when performing a Diff. /// By default, will be used. diff --git a/LibGit2Sharp/Configuration.cs b/LibGit2Sharp/Configuration.cs index 4dbab2412..5a2f2be18 100644 --- a/LibGit2Sharp/Configuration.cs +++ b/LibGit2Sharp/Configuration.cs @@ -195,36 +195,6 @@ public static Configuration BuildFrom( return new Configuration(null, repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation); } - /// - /// Access configuration values without a repository. Generally you want to access configuration via an instance of instead. - /// - /// Path to a Global configuration file. If null, the default path for a global configuration file will be probed. - [Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string) instead.")] - public Configuration(string globalConfigurationFileLocation) - : this(null, null, globalConfigurationFileLocation, null, null) - { } - - /// - /// Access configuration values without a repository. Generally you want to access configuration via an instance of instead. - /// - /// Path to a Global configuration file. If null, the default path for a global configuration file will be probed. - /// Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed. - [Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string, string) instead.")] - public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation) - : this(null, null, globalConfigurationFileLocation, xdgConfigurationFileLocation, null) - { } - - /// - /// Access configuration values without a repository. Generally you want to access configuration via an instance of instead. - /// - /// Path to a Global configuration file. If null, the default path for a global configuration file will be probed. - /// Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed. - /// Path to a System configuration file. If null, the default path for a system configuration file will be probed. - [Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string, string, string) instead.")] - public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation) - : this(null, null, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation) - { } - /// /// Determines which configuration file has been found. /// diff --git a/LibGit2Sharp/FileStatus.cs b/LibGit2Sharp/FileStatus.cs index b07323449..fbd32affd 100644 --- a/LibGit2Sharp/FileStatus.cs +++ b/LibGit2Sharp/FileStatus.cs @@ -18,34 +18,16 @@ public enum FileStatus /// Unaltered = 0, /* GIT_STATUS_CURRENT */ - /// - /// New file has been added to the Index. It's unknown from the Head. - /// - [Obsolete("This enum member will be removed in the next release. Please use NewInIndex instead.")] - Added = (1 << 0), /* GIT_STATUS_INDEX_NEW */ - /// /// New file has been added to the Index. It's unknown from the Head. /// NewInIndex = (1 << 0), /* GIT_STATUS_INDEX_NEW */ - /// - /// New version of a file has been added to the Index. A previous version exists in the Head. - /// - [Obsolete("This enum member will be removed in the next release. Please use ModifiedInIndex instead.")] - Staged = (1 << 1), /* GIT_STATUS_INDEX_MODIFIED */ - /// /// New version of a file has been added to the Index. A previous version exists in the Head. /// ModifiedInIndex = (1 << 1), /* GIT_STATUS_INDEX_MODIFIED */ - /// - /// The deletion of a file has been promoted from the working directory to the Index. A previous version exists in the Head. - /// - [Obsolete("This enum member will be removed in the next release. Please use DeletedFromIndex instead.")] - Removed = (1 << 2), /* GIT_STATUS_INDEX_DELETED */ - /// /// The deletion of a file has been promoted from the working directory to the Index. A previous version exists in the Head. /// @@ -56,56 +38,26 @@ public enum FileStatus /// RenamedInIndex = (1 << 3), /* GIT_STATUS_INDEX_RENAMED */ - /// - /// A change in type for a file has been promoted from the working directory to the Index. A previous version exists in the Head. - /// - [Obsolete("This enum member will be removed in the next release. Please use TypeChangeInIndex instead.")] - StagedTypeChange = (1 << 4), /* GIT_STATUS_INDEX_TYPECHANGE */ - /// /// A change in type for a file has been promoted from the working directory to the Index. A previous version exists in the Head. /// TypeChangeInIndex = (1 << 4), /* GIT_STATUS_INDEX_TYPECHANGE */ - /// - /// New file in the working directory, unknown from the Index and the Head. - /// - [Obsolete("This enum member will be removed in the next release. Please use NewInWorkdir instead.")] - Untracked = (1 << 7), /* GIT_STATUS_WT_NEW */ - /// /// New file in the working directory, unknown from the Index and the Head. /// NewInWorkdir = (1 << 7), /* GIT_STATUS_WT_NEW */ - /// - /// The file has been updated in the working directory. A previous version exists in the Index. - /// - [Obsolete("This enum member will be removed in the next release. Please use ModifiedInWorkdir instead.")] - Modified = (1 << 8), /* GIT_STATUS_WT_MODIFIED */ - /// /// The file has been updated in the working directory. A previous version exists in the Index. /// ModifiedInWorkdir = (1 << 8), /* GIT_STATUS_WT_MODIFIED */ - /// - /// The file has been deleted from the working directory. A previous version exists in the Index. - /// - [Obsolete("This enum member will be removed in the next release. Please use DeletedFromWorkdir instead.")] - Missing = (1 << 9), /* GIT_STATUS_WT_DELETED */ - /// /// The file has been deleted from the working directory. A previous version exists in the Index. /// DeletedFromWorkdir = (1 << 9), /* GIT_STATUS_WT_DELETED */ - /// - /// The file type has been changed in the working directory. A previous version exists in the Index. - /// - [Obsolete("This enum member will be removed in the next release. Please use TypeChangeInWorkdir instead.")] - TypeChanged = (1 << 10), /* GIT_STATUS_WT_TYPECHANGE */ - /// /// The file type has been changed in the working directory. A previous version exists in the Index. /// diff --git a/LibGit2Sharp/IQueryableCommitLog.cs b/LibGit2Sharp/IQueryableCommitLog.cs index 457ad2fa6..4a57dd3b3 100644 --- a/LibGit2Sharp/IQueryableCommitLog.cs +++ b/LibGit2Sharp/IQueryableCommitLog.cs @@ -29,23 +29,5 @@ public interface IQueryableCommitLog : ICommitLog /// The options used to control which commits will be returned. /// A list of file history entries, ready to be enumerated. IEnumerable QueryBy(string path, FollowFilter filter); - - /// - /// Find the best possible merge base given two s. - /// - /// The first . - /// The second . - /// The merge base or null if none found. - [Obsolete("This method will be removed in the next release. Please use ObjectDatabase.FindMergeBase() instead.")] - Commit FindMergeBase(Commit first, Commit second); - - /// - /// Find the best possible merge base given two or more according to the . - /// - /// The s for which to find the merge base. - /// The strategy to leverage in order to find the merge base. - /// The merge base or null if none found. - [Obsolete("This method will be removed in the next release. Please use ObjectDatabase.FindMergeBase() instead.")] - Commit FindMergeBase(IEnumerable commits, MergeBaseFindingStrategy strategy); } } diff --git a/LibGit2Sharp/IRepository.cs b/LibGit2Sharp/IRepository.cs index 317a0e76b..1bd921a51 100644 --- a/LibGit2Sharp/IRepository.cs +++ b/LibGit2Sharp/IRepository.cs @@ -174,18 +174,6 @@ public interface IRepository : IDisposable /// Collection of parameters controlling checkout behavior. void Reset(ResetMode resetMode, Commit commit, CheckoutOptions options); - /// - /// Replaces entries in the with entries from the specified commit. - /// - /// The target commit object. - /// The list of paths (either files or directories) that should be considered. - /// - /// If set, the passed will be treated as explicit paths. - /// Use these options to determine how unmatched explicit paths should be handled. - /// - [Obsolete("This method will be removed in the next release. Please use Index.Replace() instead.")] - void Reset(Commit commit, IEnumerable paths, ExplicitPathsOptions explicitPathsOptions); - /// /// Clean the working tree by removing files that are not under version control. /// diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index 72afcc658..c9d8b2aac 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -23,7 +23,6 @@ TRACE;DEBUG;NET40 prompt 4 - false true AllRules.ruleset bin\Debug\LibGit2Sharp.xml @@ -36,7 +35,6 @@ prompt 4 true - false bin\Release\LibGit2Sharp.xml @@ -255,7 +253,6 @@ - diff --git a/LibGit2Sharp/MergeConflictException.cs b/LibGit2Sharp/MergeConflictException.cs deleted file mode 100644 index d95124dc0..000000000 --- a/LibGit2Sharp/MergeConflictException.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Runtime.Serialization; -using LibGit2Sharp.Core; - -namespace LibGit2Sharp -{ - /// - /// The exception that is thrown when a checkout cannot be performed - /// because of a conflicting change staged in the index, or unstaged - /// in the working directory. - /// - [Serializable] - [Obsolete("This type will be removed in the next release. Please use CheckoutConflictException instead.")] - public class MergeConflictException : LibGit2SharpException - { - /// - /// Initializes a new instance of the class. - /// - public MergeConflictException() - { } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// A message that describes the error. - public MergeConflictException(string message) - : base(message) - { } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// A composite format string for use in . - /// An object array that contains zero or more objects to format. - public MergeConflictException(string format, params object[] args) - : base(format, args) - { } - - /// - /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - /// - /// The error message that explains the reason for the exception. - /// The exception that is the cause of the current exception. If the parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception. - public MergeConflictException(string message, Exception innerException) - : base(message, innerException) - { } - - /// - /// Initializes a new instance of the class with a serialized data. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - protected MergeConflictException(SerializationInfo info, StreamingContext context) - : base(info, context) - { } - - internal MergeConflictException(string message, GitErrorCode code, GitErrorCategory category) - : base(message, code, category) - { } - } -} diff --git a/LibGit2Sharp/MergeOptions.cs b/LibGit2Sharp/MergeOptions.cs index c36e6ddca..b57d955e4 100644 --- a/LibGit2Sharp/MergeOptions.cs +++ b/LibGit2Sharp/MergeOptions.cs @@ -37,12 +37,6 @@ public enum FastForwardStrategy /// Default = 0, - /// - /// Do not fast-forward. Always creates a merge commit. - /// - [Obsolete("This enum member will be removed in the next release. Please use NoFastForward instead.")] - NoFastFoward = 1, /* GIT_MERGE_NO_FASTFORWARD */ - /// /// Do not fast-forward. Always creates a merge commit. /// diff --git a/LibGit2Sharp/NoteCollection.cs b/LibGit2Sharp/NoteCollection.cs index 7c8c8ecc8..c9f083835 100644 --- a/LibGit2Sharp/NoteCollection.cs +++ b/LibGit2Sharp/NoteCollection.cs @@ -163,22 +163,6 @@ internal static string UnCanonicalizeName(string name) return name.Substring(Reference.NotePrefix.Length); } - /// - /// Creates or updates a on the specified object, and for the given namespace. - /// Both the Author and Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable. - /// - /// The target , for which the note will be created. - /// The note message. - /// The namespace on which the note will be created. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace'). - /// The note which was just saved. - [Obsolete("This method will be removed in the next release. Please use Add(ObjectId, string, Signature, Signature, string) instead.")] - public virtual Note Add(ObjectId targetId, string message, string @namespace) - { - Signature author = repo.Config.BuildSignatureOrThrow(DateTimeOffset.Now); - - return Add(targetId, message, author, author, @namespace); - } - /// /// Creates or updates a on the specified object, and for the given namespace. /// @@ -205,20 +189,6 @@ public virtual Note Add(ObjectId targetId, string message, Signature author, Sig return this[canonicalNamespace, targetId]; } - /// - /// Deletes the note on the specified object, and for the given namespace. - /// Both the Author and Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable. - /// - /// The target , for which the note will be created. - /// The namespace on which the note will be removed. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace'). - [Obsolete("This method will be removed in the next release. Please use Remove(ObjectId, Signature, Signature, string) instead.")] - public virtual void Remove(ObjectId targetId, string @namespace) - { - Signature author = repo.Config.BuildSignatureOrThrow(DateTimeOffset.Now); - - Remove(targetId, author, author, @namespace); - } - /// /// Deletes the note on the specified object, and for the given namespace. /// diff --git a/LibGit2Sharp/ReferenceWrapper.cs b/LibGit2Sharp/ReferenceWrapper.cs index 471dc1ede..9b5f151d3 100644 --- a/LibGit2Sharp/ReferenceWrapper.cs +++ b/LibGit2Sharp/ReferenceWrapper.cs @@ -59,15 +59,6 @@ public virtual string FriendlyName get { return Shorten(); } } - /// - /// Gets the name of this reference. - /// - [Obsolete("This property will be removed in the next release. Please use FriendlyName instead.")] - public virtual string Name - { - get { return FriendlyName; } - } - /// /// Returns the , a representation of the current reference. /// diff --git a/LibGit2Sharp/ReflogEntry.cs b/LibGit2Sharp/ReflogEntry.cs index f783b11cf..38387e1d7 100644 --- a/LibGit2Sharp/ReflogEntry.cs +++ b/LibGit2Sharp/ReflogEntry.cs @@ -57,15 +57,6 @@ public virtual Signature Committer get { return _committer; } } - /// - /// of the committer of this reference update - /// - [Obsolete("This property will be removed in the next release. Please use Committer instead.")] - public virtual Signature Commiter - { - get { return Committer; } - } - /// /// the message assiocated to this reference update /// diff --git a/LibGit2Sharp/Repository.cs b/LibGit2Sharp/Repository.cs index bf96c206d..bfb551f9f 100644 --- a/LibGit2Sharp/Repository.cs +++ b/LibGit2Sharp/Repository.cs @@ -1030,21 +1030,6 @@ public void CheckoutPaths(string committishOrBranchSpec, IEnumerable pat CheckoutTree(commit.Tree, listOfPaths, checkoutOptions ?? new CheckoutOptions()); } - /// - /// Replaces entries in the with entries from the specified commit. - /// - /// The target commit object. - /// The list of paths (either files or directories) that should be considered. - /// - /// If set, the passed will be treated as explicit paths. - /// Use these options to determine how unmatched explicit paths should be handled. - /// - [Obsolete("This method will be removed in the next release. Please use Index.Replace() instead.")] - public void Reset(Commit commit, IEnumerable paths, ExplicitPathsOptions explicitPathsOptions) - { - Index.Replace(commit, paths, explicitPathsOptions); - } - /// /// Stores the content of the as a new into the repository. /// The tip of the will be used as the parent of this new Commit. diff --git a/LibGit2Sharp/RepositoryExtensions.cs b/LibGit2Sharp/RepositoryExtensions.cs index d3754caa3..447470bac 100644 --- a/LibGit2Sharp/RepositoryExtensions.cs +++ b/LibGit2Sharp/RepositoryExtensions.cs @@ -178,31 +178,6 @@ public static void Reset(this IRepository repository, ResetMode resetMode, strin repository.Reset(resetMode, commit); } - /// - /// Replaces entries in the with entries from the specified commit. - /// - /// The being worked with. - /// A revparse spec for the target commit object. - /// The list of paths (either files or directories) that should be considered. - /// - /// If set, the passed will be treated as explicit paths. - /// Use these options to determine how unmatched explicit paths should be handled. - /// - [Obsolete("This method will be removed in the next release. Please use Index.Replace() instead.")] - public static void Reset(this IRepository repository, string committish = "HEAD", IEnumerable paths = null, ExplicitPathsOptions explicitPathsOptions = null) - { - if (repository.Info.IsBare) - { - throw new BareRepositoryException("Reset is not allowed in a bare repository"); - } - - Ensure.ArgumentNotNullOrEmptyString(committish, "committish"); - - Commit commit = LookUpCommit(repository, committish); - - repository.Index.Replace(commit, paths, explicitPathsOptions); - } - private static Commit LookUpCommit(IRepository repository, string committish) { GitObject obj = repository.Lookup(committish); @@ -210,74 +185,6 @@ private static Commit LookUpCommit(IRepository repository, string committish) return obj.DereferenceToCommit(true); } - /// - /// Stores the content of the as a new into the repository. - /// The tip of the will be used as the parent of this new Commit. - /// Once the commit is created, the will move forward to point at it. - /// Both the Author and Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable. - /// - /// The being worked with. - /// The description of why a change was made to the repository. - /// The generated . - [Obsolete("This method will be removed in the next release. Please use Commit(string, Signature, Signature) instead.")] - public static Commit Commit(this IRepository repository, string message) - { - return repository.Commit(message, (CommitOptions)null); - } - - /// - /// Stores the content of the as a new into the repository. - /// The tip of the will be used as the parent of this new Commit. - /// Once the commit is created, the will move forward to point at it. - /// Both the Author and Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable. - /// - /// The being worked with. - /// The description of why a change was made to the repository. - /// The that specify the commit behavior. - /// The generated . - [Obsolete("This method will be removed in the next release. Please use Commit(string, Signature, Signature, CommitOptions) instead.")] - public static Commit Commit(this IRepository repository, string message, CommitOptions options) - { - Signature author = repository.Config.BuildSignatureOrThrow(DateTimeOffset.Now); - - return repository.Commit(message, author, options); - } - - /// - /// Stores the content of the as a new into the repository. - /// The tip of the will be used as the parent of this new Commit. - /// Once the commit is created, the will move forward to point at it. - /// The Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable. - /// - /// The being worked with. - /// The of who made the change. - /// The description of why a change was made to the repository. - /// The generated . - [Obsolete("This method will be removed in the next release. Please use Commit(string, Signature, Signature) instead.")] - public static Commit Commit(this IRepository repository, string message, Signature author) - { - return repository.Commit(message, author, (CommitOptions)null); - } - - /// - /// Stores the content of the as a new into the repository. - /// The tip of the will be used as the parent of this new Commit. - /// Once the commit is created, the will move forward to point at it. - /// The Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable. - /// - /// The being worked with. - /// The of who made the change. - /// The description of why a change was made to the repository. - /// The that specify the commit behavior. - /// The generated . - [Obsolete("This method will be removed in the next release. Please use Commit(string, Signature, Signature, CommitOptions) instead.")] - public static Commit Commit(this IRepository repository, string message, Signature author, CommitOptions options) - { - Signature committer = repository.Config.BuildSignatureOrThrow(DateTimeOffset.Now); - - return repository.Commit(message, author, committer, options); - } - /// /// Stores the content of the as a new into the repository. /// The tip of the will be used as the parent of this new Commit. @@ -597,29 +504,6 @@ public static void Reset(this IRepository repository, ResetMode resetMode, Commi repository.Reset(resetMode, commit); } - /// - /// Replaces entries in the with entries from the specified commit. - /// - /// The being worked with. - /// The target commit object. - /// The list of paths (either files or directories) that should be considered. - [Obsolete("This method will be removed in the next release. Please use Index.Replace() instead.")] - public static void Reset(this IRepository repository, Commit commit, IEnumerable paths) - { - repository.Index.Replace(commit, paths, null); - } - - /// - /// Replaces entries in the with entries from the specified commit. - /// - /// The being worked with. - /// The target commit object. - [Obsolete("This method will be removed in the next release. Please use Index.Replace() instead.")] - public static void Reset(this IRepository repository, Commit commit) - { - repository.Index.Replace(commit, null, null); - } - /// /// Find where each line of a file originated. /// From 4bb5f5f55623c8c9b175a1dcc342e7bcc29f0c98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 14 Dec 2015 19:04:15 +0100 Subject: [PATCH 32/50] Keep the remote and refspec handle around Refspecs aren't just read-only, we need the objects around for some operations (added in a later commit). The memory is owned by the remote object so we need to keep that around as well. --- LibGit2Sharp/RefSpec.cs | 67 ++++++++++++++++++++----------- LibGit2Sharp/RefSpecCollection.cs | 12 ++---- LibGit2Sharp/Remote.cs | 16 +++++--- LibGit2Sharp/RemoteCollection.cs | 18 +++------ 4 files changed, 63 insertions(+), 50 deletions(-) diff --git a/LibGit2Sharp/RefSpec.cs b/LibGit2Sharp/RefSpec.cs index 9c811c5f9..c51146968 100644 --- a/LibGit2Sharp/RefSpec.cs +++ b/LibGit2Sharp/RefSpec.cs @@ -1,4 +1,5 @@ -using System.Diagnostics; +using System; +using System.Diagnostics; using System.Globalization; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; @@ -11,17 +12,13 @@ namespace LibGit2Sharp [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RefSpec { - private RefSpec(string refSpec, RefSpecDirection direction, string source, string destination, bool forceUpdate) - { - Ensure.ArgumentNotNullOrEmptyString(refSpec, "refSpec"); - Ensure.ArgumentNotNull(source, "source"); - Ensure.ArgumentNotNull(destination, "destination"); + readonly Remote remote; + readonly GitRefSpecHandle handle; - Specification = refSpec; - Direction = direction; - Source = source; - Destination = destination; - ForceUpdate = forceUpdate; + internal RefSpec(Remote remote, GitRefSpecHandle handle) + { + this.remote = remote; + this.handle = handle; } /// @@ -30,38 +27,60 @@ private RefSpec(string refSpec, RefSpecDirection direction, string source, strin protected RefSpec() { } - internal static RefSpec BuildFromPtr(GitRefSpecHandle handle) - { - Ensure.ArgumentNotNull(handle, "handle"); - - return new RefSpec(Proxy.git_refspec_string(handle), Proxy.git_refspec_direction(handle), - Proxy.git_refspec_src(handle), Proxy.git_refspec_dst(handle), Proxy.git_refspec_force(handle)); - } - /// /// Gets the pattern describing the mapping between remote and local references /// - public virtual string Specification { get; private set; } + public virtual string Specification + { + get + { + return Proxy.git_refspec_string(this.handle); + } + } /// /// Indicates whether this is intended to be used during a Push or Fetch operation /// - public virtual RefSpecDirection Direction { get; private set; } + public virtual RefSpecDirection Direction + { + get + { + return Proxy.git_refspec_direction(this.handle); + } + } /// /// The source reference specifier /// - public virtual string Source { get; private set; } + public virtual string Source + { + get + { + return Proxy.git_refspec_src(this.handle); + } + } /// /// The target reference specifier /// - public virtual string Destination { get; private set; } + public virtual string Destination + { + get + { + return Proxy.git_refspec_dst(this.handle); + } + } /// /// Indicates whether the destination will be force-updated if fast-forwarding is not possible /// - public virtual bool ForceUpdate { get; private set; } + public virtual bool ForceUpdate + { + get + { + return Proxy.git_refspec_force(this.handle); + } + } private string DebuggerDisplay { diff --git a/LibGit2Sharp/RefSpecCollection.cs b/LibGit2Sharp/RefSpecCollection.cs index 163281a12..34eb3cb6e 100644 --- a/LibGit2Sharp/RefSpecCollection.cs +++ b/LibGit2Sharp/RefSpecCollection.cs @@ -22,28 +22,24 @@ public class RefSpecCollection : IEnumerable protected RefSpecCollection() { } - internal RefSpecCollection(RemoteSafeHandle handle) + internal RefSpecCollection(Remote remote, RemoteSafeHandle handle) { Ensure.ArgumentNotNull(handle, "handle"); - refspecs = RetrieveRefSpecs(handle); + refspecs = RetrieveRefSpecs(remote, handle); } - static IList RetrieveRefSpecs(RemoteSafeHandle remoteHandle) + static IList RetrieveRefSpecs(Remote remote, RemoteSafeHandle remoteHandle) { int count = Proxy.git_remote_refspec_count(remoteHandle); List refSpecs = new List(); for (int i = 0; i < count; i++) { - using (GitRefSpecHandle handle = Proxy.git_remote_get_refspec(remoteHandle, i)) - { - refSpecs.Add(RefSpec.BuildFromPtr(handle)); - } + refSpecs.Add(new RefSpec(remote, Proxy.git_remote_get_refspec(remoteHandle, i))); } return refSpecs; - } /// diff --git a/LibGit2Sharp/Remote.cs b/LibGit2Sharp/Remote.cs index 137208198..82a2c8409 100644 --- a/LibGit2Sharp/Remote.cs +++ b/LibGit2Sharp/Remote.cs @@ -22,27 +22,31 @@ public class Remote : IEquatable, IBelongToARepository private readonly RefSpecCollection refSpecs; private string pushUrl; + readonly RemoteSafeHandle handle; + /// /// Needed for mocking purposes. /// protected Remote() { } - private Remote(RemoteSafeHandle handle, Repository repository) + internal Remote(RemoteSafeHandle handle, Repository repository) { this.repository = repository; + this.handle = handle; Name = Proxy.git_remote_name(handle); Url = Proxy.git_remote_url(handle); PushUrl = Proxy.git_remote_pushurl(handle); TagFetchMode = Proxy.git_remote_autotag(handle); - refSpecs = new RefSpecCollection(handle); + refSpecs = new RefSpecCollection(this, handle); } - internal static Remote BuildFromPtr(RemoteSafeHandle handle, Repository repo) + ~Remote() { - var remote = new Remote(handle, repo); - - return remote; + if (handle != null) + { + handle.Dispose(); + } } /// diff --git a/LibGit2Sharp/RemoteCollection.cs b/LibGit2Sharp/RemoteCollection.cs index 6ab1a3faf..86bb41331 100644 --- a/LibGit2Sharp/RemoteCollection.cs +++ b/LibGit2Sharp/RemoteCollection.cs @@ -43,10 +43,8 @@ internal Remote RemoteForName(string name, bool shouldThrowIfNotFound = true) { Ensure.ArgumentNotNull(name, "name"); - using (RemoteSafeHandle handle = Proxy.git_remote_lookup(repository.Handle, name, shouldThrowIfNotFound)) - { - return handle == null ? null : Remote.BuildFromPtr(handle, this.repository); - } + RemoteSafeHandle handle = Proxy.git_remote_lookup(repository.Handle, name, shouldThrowIfNotFound); + return handle == null ? null : new Remote(handle, this.repository); } /// @@ -102,10 +100,8 @@ public virtual Remote Add(string name, string url) Ensure.ArgumentNotNull(name, "name"); Ensure.ArgumentNotNull(url, "url"); - using (RemoteSafeHandle handle = Proxy.git_remote_create(repository.Handle, name, url)) - { - return Remote.BuildFromPtr(handle, this.repository); - } + RemoteSafeHandle handle = Proxy.git_remote_create(repository.Handle, name, url); + return new Remote(handle, this.repository); } /// @@ -121,10 +117,8 @@ public virtual Remote Add(string name, string url, string fetchRefSpec) Ensure.ArgumentNotNull(url, "url"); Ensure.ArgumentNotNull(fetchRefSpec, "fetchRefSpec"); - using (RemoteSafeHandle handle = Proxy.git_remote_create_with_fetchspec(repository.Handle, name, url, fetchRefSpec)) - { - return Remote.BuildFromPtr(handle, this.repository); - } + RemoteSafeHandle handle = Proxy.git_remote_create_with_fetchspec(repository.Handle, name, url, fetchRefSpec); + return new Remote(handle, this.repository); } /// From 53b66beadfb6f59283fb90133e52ab783d7026fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 14 Dec 2015 21:38:10 +0100 Subject: [PATCH 33/50] Bind the missing refspec methods These are actions, so they need the handle which we previously made the code keep around. --- LibGit2Sharp.Tests/RefSpecFixture.cs | 38 ++++++++++++++++++++++++++ LibGit2Sharp/Core/NativeMethods.cs | 16 +++++++++++ LibGit2Sharp/Core/Proxy.cs | 21 +++++++++++++++ LibGit2Sharp/RefSpec.cs | 40 ++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+) diff --git a/LibGit2Sharp.Tests/RefSpecFixture.cs b/LibGit2Sharp.Tests/RefSpecFixture.cs index dc82a5fc3..094547160 100644 --- a/LibGit2Sharp.Tests/RefSpecFixture.cs +++ b/LibGit2Sharp.Tests/RefSpecFixture.cs @@ -190,5 +190,43 @@ public void SettingInvalidRefSpecsThrows(string refSpec) Assert.Equal(oldRefSpecs, newRemote.RefSpecs.Select(r => r.Specification).ToList()); } } + + [Theory] + [InlineData("refs/heads/master", true, false)] + [InlineData("refs/heads/some/master", true, false)] + [InlineData("refs/remotes/foo/master", false, true)] + [InlineData("refs/tags/foo", false, false)] + public void CanCheckForMatches(string reference, bool shouldMatchSource, bool shouldMatchDest) + { + var path = SandboxStandardTestRepo(); + using (var repo = InitIsolatedRepository(path)) + { + var remote = repo.Network.Remotes.Add("foo", "blahblah", "refs/heads/*:refs/remotes/foo/*"); + var refspec = remote.RefSpecs.Single(); + + Assert.Equal(shouldMatchSource, refspec.SourceMatches(reference)); + Assert.Equal(shouldMatchDest, refspec.DestinationMatches(reference)); + } + } + + [Theory] + [InlineData("refs/heads/master", "refs/remotes/foo/master")] + [InlineData("refs/heads/bar/master", "refs/remotes/foo/bar/master")] + [InlineData("refs/heads/master", "refs/remotes/foo/master")] + public void CanTransformRefspecs(string lhs, string rhs) + { + var path = SandboxStandardTestRepo(); + using (var repo = InitIsolatedRepository(path)) + { + var remote = repo.Network.Remotes.Add("foo", "blahblah", "refs/heads/*:refs/remotes/foo/*"); + var refspec = remote.RefSpecs.Single(); + + var actualTransformed = refspec.Transform(lhs); + var actualReverseTransformed = refspec.ReverseTransform(rhs); + + Assert.Equal(rhs, actualTransformed); + Assert.Equal(lhs, actualReverseTransformed); + } + } } } diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 8978abda4..94cbe7c27 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1112,6 +1112,12 @@ internal static extern IntPtr git_reflog_entry_committer( [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_reflog_entry_message(SafeHandle entry); + [DllImport(libgit2)] + internal static extern int git_refspec_transform( + GitBuf buf, + GitRefSpecHandle refspec, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); + [DllImport(libgit2)] internal static extern int git_refspec_rtransform( GitBuf buf, @@ -1139,6 +1145,16 @@ internal static extern string git_refspec_src( [DllImport(libgit2)] internal static extern bool git_refspec_force(GitRefSpecHandle refSpec); + [DllImport(libgit2)] + internal static extern bool git_refspec_src_matches( + GitRefSpecHandle resfpec, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string reference); + + [DllImport(libgit2)] + internal static extern bool git_refspec_dst_matches( + GitRefSpecHandle resfpec, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string reference); + [DllImport(libgit2)] internal static extern int git_remote_autotag(RemoteSafeHandle remote); diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index 35371d886..b19fa6499 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -2017,6 +2017,17 @@ public static string git_reflog_entry_message(SafeHandle entry) #region git_refspec + public static string git_refspec_transform(GitRefSpecHandle refSpecPtr, string name) + { + using (var buf = new GitBuf()) + { + int res = NativeMethods.git_refspec_transform(buf, refSpecPtr, name); + Ensure.ZeroResult(res); + + return LaxUtf8Marshaler.FromNative(buf.ptr) ?? string.Empty; + } + } + public static string git_refspec_rtransform(GitRefSpecHandle refSpecPtr, string name) { using (var buf = new GitBuf()) @@ -2053,6 +2064,16 @@ public static bool git_refspec_force(GitRefSpecHandle refSpec) return NativeMethods.git_refspec_force(refSpec); } + public static bool git_refspec_src_matches(GitRefSpecHandle refspec, string reference) + { + return NativeMethods.git_refspec_src_matches(refspec, reference); + } + + public static bool git_refspec_dst_matches(GitRefSpecHandle refspec, string reference) + { + return NativeMethods.git_refspec_dst_matches(refspec, reference); + } + #endregion #region git_remote_ diff --git a/LibGit2Sharp/RefSpec.cs b/LibGit2Sharp/RefSpec.cs index c51146968..aeeabb75e 100644 --- a/LibGit2Sharp/RefSpec.cs +++ b/LibGit2Sharp/RefSpec.cs @@ -82,6 +82,46 @@ public virtual bool ForceUpdate } } + /// + /// Check whether the given reference matches the source (lhs) part of + /// this refspec. + /// + /// The reference name to check + public virtual bool SourceMatches(string reference) + { + return Proxy.git_refspec_src_matches(handle, reference); + } + + /// + /// Check whether the given reference matches the target (rhs) part of + /// this refspec. + /// + /// The reference name to check + public virtual bool DestinationMatches(string reference) + { + return Proxy.git_refspec_dst_matches(handle, reference); + } + + /// + /// Perform the transformation described by this refspec on the given + /// reference name (from source to destination). + /// + /// The reference name to transform + public virtual string Transform(string reference) + { + return Proxy.git_refspec_transform(handle, reference); + } + + /// + /// Perform the reverse of the transformation described by this refspec + /// on the given reference name (from destination to source). + /// + /// The reference name to transform + public virtual string ReverseTransform(string reference) + { + return Proxy.git_refspec_rtransform(handle, reference); + } + private string DebuggerDisplay { get From d6282d3b56e09c96df823e4fbadb07c3deb9777b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 15 Dec 2015 14:02:48 +0100 Subject: [PATCH 34/50] Properly implement disposable for Remote --- LibGit2Sharp/Remote.cs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/LibGit2Sharp/Remote.cs b/LibGit2Sharp/Remote.cs index 82a2c8409..f92b4aa10 100644 --- a/LibGit2Sharp/Remote.cs +++ b/LibGit2Sharp/Remote.cs @@ -12,7 +12,7 @@ namespace LibGit2Sharp /// A remote repository whose branches are tracked. /// [DebuggerDisplay("{DebuggerDisplay,nq}")] - public class Remote : IEquatable, IBelongToARepository + public class Remote : IEquatable, IBelongToARepository, IDisposable { private static readonly LambdaEqualityHelper equalityHelper = new LambdaEqualityHelper(x => x.Name, x => x.Url, x => x.PushUrl); @@ -43,12 +43,37 @@ internal Remote(RemoteSafeHandle handle, Repository repository) ~Remote() { - if (handle != null) + Dispose(false); + } + + #region IDisposable + + bool disposedValue = false; // To detect redundant calls + + /// + /// Release the unmanaged remote object + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + void Dispose(bool disposing) + { + if (!disposedValue) { - handle.Dispose(); + if (handle != null) + { + handle.Dispose(); + } + + disposedValue = true; } } + #endregion + /// /// Gets the alias of this remote repository. /// From 24c4a8e090c806a4b197ddff3e81cf6384ed1e84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 15 Dec 2015 14:26:26 +0100 Subject: [PATCH 35/50] Don't load refspecs eagerly If the user never asks for the refspecs, we should not spend the time and memory to load them into managed memory. --- LibGit2Sharp/RefSpecCollection.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/LibGit2Sharp/RefSpecCollection.cs b/LibGit2Sharp/RefSpecCollection.cs index 34eb3cb6e..46b1c4360 100644 --- a/LibGit2Sharp/RefSpecCollection.cs +++ b/LibGit2Sharp/RefSpecCollection.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -14,7 +15,9 @@ namespace LibGit2Sharp [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RefSpecCollection : IEnumerable { - readonly IList refspecs; + readonly Remote remote; + readonly RemoteSafeHandle handle; + readonly Lazy> refspecs; /// /// Needed for mocking purposes. @@ -26,7 +29,10 @@ internal RefSpecCollection(Remote remote, RemoteSafeHandle handle) { Ensure.ArgumentNotNull(handle, "handle"); - refspecs = RetrieveRefSpecs(remote, handle); + this.remote = remote; + this.handle = handle; + + refspecs = new Lazy>(() => RetrieveRefSpecs(remote, handle)); } static IList RetrieveRefSpecs(Remote remote, RemoteSafeHandle remoteHandle) @@ -48,7 +54,7 @@ static IList RetrieveRefSpecs(Remote remote, RemoteSafeHandle remoteHan /// An object that can be used to iterate through the collection. public virtual IEnumerator GetEnumerator() { - return refspecs.GetEnumerator(); + return refspecs.Value.GetEnumerator(); } /// From 49384143784b1ed00fa6fa10475d066b9ba3a2ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 8 Mar 2016 09:25:35 +0100 Subject: [PATCH 36/50] Add the template for changes after v0.22 --- CHANGES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 22a41d5b2..e2933860f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,14 @@ - Windows (x86/amd64): - Linux/Mac OS X: +## v0.22 + 1 + +### Additions + +### Changes + +### Fixes + ## v0.22 - ([diff](https://github.com/libgit2/libgit2sharp/compare/v0.21.1...v0.22)) ### Additions From 3c3674a7e6b3f1f4b8660db39f41d500b84933d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 8 Mar 2016 00:38:46 +0100 Subject: [PATCH 37/50] Mark per-repo config locations obsolete --- LibGit2Sharp/RepositoryOptions.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/LibGit2Sharp/RepositoryOptions.cs b/LibGit2Sharp/RepositoryOptions.cs index a4e9541f8..3b6d39da5 100644 --- a/LibGit2Sharp/RepositoryOptions.cs +++ b/LibGit2Sharp/RepositoryOptions.cs @@ -1,4 +1,6 @@ -namespace LibGit2Sharp +using System; + +namespace LibGit2Sharp { /// /// Provides optional additional information to the Repository to be opened. @@ -34,6 +36,7 @@ public sealed class RepositoryOptions /// /// . /// + [Obsolete("This option is deprecated. Use GlobalConfiguration.SetConfigSearchPaths()")] public string GlobalConfigurationLocation { get; set; } /// @@ -44,6 +47,7 @@ public sealed class RepositoryOptions /// /// . /// + [Obsolete("This option is deprecated. Use GlobalConfiguration.SetConfigSearchPaths()")] public string XdgConfigurationLocation { get; set; } /// @@ -54,6 +58,7 @@ public sealed class RepositoryOptions /// /// . /// + [Obsolete("This option is deprecated. Use GlobalConfiguration.SetConfigSearchPaths()")] public string SystemConfigurationLocation { get; set; } /// From 1bd1cd5b29adc4848f39c7b2339d6192816d16a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 8 Mar 2016 01:22:38 +0100 Subject: [PATCH 38/50] Remove the explicit repository isolation in tests We now isolate all tests by setting the config search paths globally at the start of the fixture. --- LibGit2Sharp.Tests/AttributesFixture.cs | 2 +- LibGit2Sharp.Tests/BranchFixture.cs | 10 +-- LibGit2Sharp.Tests/ConfigurationFixture.cs | 18 +--- LibGit2Sharp.Tests/FetchFixture.cs | 4 +- LibGit2Sharp.Tests/MergeFixture.cs | 2 +- LibGit2Sharp.Tests/ObjectDatabaseFixture.cs | 2 +- LibGit2Sharp.Tests/RefSpecFixture.cs | 30 ++++--- LibGit2Sharp.Tests/RemoteFixture.cs | 3 +- LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs | 82 +++++++++---------- 9 files changed, 66 insertions(+), 87 deletions(-) diff --git a/LibGit2Sharp.Tests/AttributesFixture.cs b/LibGit2Sharp.Tests/AttributesFixture.cs index c607ce651..8a0a15dce 100644 --- a/LibGit2Sharp.Tests/AttributesFixture.cs +++ b/LibGit2Sharp.Tests/AttributesFixture.cs @@ -9,7 +9,7 @@ public class AttributesFixture : BaseFixture [Fact] public void StagingHonorsTheAttributesFiles() { - using (var repo = InitIsolatedRepository()) + using (var repo = new Repository(InitNewRepository())) { CreateAttributesFile(repo); diff --git a/LibGit2Sharp.Tests/BranchFixture.cs b/LibGit2Sharp.Tests/BranchFixture.cs index 715defd87..be82049ea 100644 --- a/LibGit2Sharp.Tests/BranchFixture.cs +++ b/LibGit2Sharp.Tests/BranchFixture.cs @@ -447,11 +447,10 @@ public void QueryRemoteForRemoteBranch() [Fact] public void QueryUnresolvableRemoteForRemoteBranch() { - var path = SandboxStandardTestRepo(); - var fetchRefSpecs = new string[] { "+refs/heads/notfound/*:refs/remotes/origin/notfound/*" }; - using (var repo = InitIsolatedRepository(path)) + var path = SandboxStandardTestRepo(); + using (var repo = new Repository(path)) { // Update the remote config such that the remote for a // remote branch cannot be resolved @@ -472,12 +471,11 @@ public void QueryUnresolvableRemoteForRemoteBranch() [Fact] public void QueryAmbigousRemoteForRemoteBranch() { - var path = SandboxStandardTestRepo(); - const string fetchRefSpec = "+refs/heads/*:refs/remotes/origin/*"; const string url = "http://github.com/libgit2/TestGitRepository"; - using (var repo = InitIsolatedRepository(path)) + var path = SandboxStandardTestRepo(); + using (var repo = new Repository(path)) { // Add a second remote so that it is ambiguous which remote // the remote-tracking branch tracks. diff --git a/LibGit2Sharp.Tests/ConfigurationFixture.cs b/LibGit2Sharp.Tests/ConfigurationFixture.cs index 30c8b207f..b50fa7e98 100644 --- a/LibGit2Sharp.Tests/ConfigurationFixture.cs +++ b/LibGit2Sharp.Tests/ConfigurationFixture.cs @@ -36,12 +36,8 @@ public void CanUnsetAnEntryFromTheLocalConfiguration() [Fact] public void CanUnsetAnEntryFromTheGlobalConfiguration() { - SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); - - var options = BuildFakeConfigs(scd); - string path = SandboxBareTestRepo(); - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { Assert.True(repo.Config.HasConfig(ConfigurationLevel.Global)); Assert.Equal(42, repo.Config.Get("Wow.Man-I-am-totally-global").Value); @@ -331,12 +327,8 @@ public void SettingUnsupportedTypeThrows() [Fact] public void CanGetAnEntryFromASpecificStore() { - SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); - - var options = BuildFakeConfigs(scd); - string path = SandboxStandardTestRepo(); - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { Assert.True(repo.Config.HasConfig(ConfigurationLevel.Local)); Assert.True(repo.Config.HasConfig(ConfigurationLevel.Global)); @@ -356,12 +348,8 @@ public void CanGetAnEntryFromASpecificStore() [Fact] public void CanTellIfASpecificStoreContainsAKey() { - SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); - - var options = BuildFakeConfigs(scd); - string path = SandboxBareTestRepo(); - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { Assert.True(repo.Config.HasConfig(ConfigurationLevel.System)); diff --git a/LibGit2Sharp.Tests/FetchFixture.cs b/LibGit2Sharp.Tests/FetchFixture.cs index 89a7e8a62..f6465f801 100644 --- a/LibGit2Sharp.Tests/FetchFixture.cs +++ b/LibGit2Sharp.Tests/FetchFixture.cs @@ -213,9 +213,7 @@ public void FetchHonorsTheFetchPruneConfigurationEntry() string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath); - var options = BuildFakeConfigs(BuildSelfCleaningDirectory()); - - using (var clonedRepo = new Repository(clonedRepoPath, options)) + using (var clonedRepo = new Repository(clonedRepoPath)) { Assert.Equal(5, clonedRepo.Branches.Count(b => b.IsRemote)); diff --git a/LibGit2Sharp.Tests/MergeFixture.cs b/LibGit2Sharp.Tests/MergeFixture.cs index eadbffec5..f38f456de 100644 --- a/LibGit2Sharp.Tests/MergeFixture.cs +++ b/LibGit2Sharp.Tests/MergeFixture.cs @@ -678,7 +678,7 @@ public void MergeCanSpecifyMergeFileFavorOption(MergeFileFavor fileFavorFlag) const string conflictBranchName = "conflicts"; string path = SandboxMergeTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { Branch branch = repo.Branches[conflictBranchName]; Assert.NotNull(branch); diff --git a/LibGit2Sharp.Tests/ObjectDatabaseFixture.cs b/LibGit2Sharp.Tests/ObjectDatabaseFixture.cs index 8e2a1d843..bfbb6ae5a 100644 --- a/LibGit2Sharp.Tests/ObjectDatabaseFixture.cs +++ b/LibGit2Sharp.Tests/ObjectDatabaseFixture.cs @@ -109,7 +109,7 @@ public void CanCreateABlobFromAStream(string expectedSha, string hintPath) sb.Append("libgit2\n\r\n"); } - using (var repo = InitIsolatedRepository()) + using (var repo = new Repository(InitNewRepository())) { CreateAttributesFiles(Path.Combine(repo.Info.Path, "info"), "attributes"); diff --git a/LibGit2Sharp.Tests/RefSpecFixture.cs b/LibGit2Sharp.Tests/RefSpecFixture.cs index 094547160..fa272746a 100644 --- a/LibGit2Sharp.Tests/RefSpecFixture.cs +++ b/LibGit2Sharp.Tests/RefSpecFixture.cs @@ -11,7 +11,7 @@ public class RefSpecFixture : BaseFixture public void CanCountRefSpecs() { var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; Assert.Equal(1, remote.RefSpecs.Count()); @@ -22,7 +22,7 @@ public void CanCountRefSpecs() public void CanIterateOverRefSpecs() { var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; int count = 0; @@ -39,7 +39,7 @@ public void CanIterateOverRefSpecs() public void FetchAndPushRefSpecsComposeRefSpecs() { var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; @@ -53,7 +53,7 @@ public void FetchAndPushRefSpecsComposeRefSpecs() public void CanReadRefSpecDetails() { var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; @@ -73,7 +73,7 @@ public void CanReadRefSpecDetails() public void CanReplaceRefSpecs(string[] newFetchRefSpecs, string[] newPushRefSpecs) { var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; var oldRefSpecs = remote.RefSpecs.ToList(); @@ -101,15 +101,15 @@ public void CanReplaceRefSpecs(string[] newFetchRefSpecs, string[] newPushRefSpe public void RemoteUpdaterSavesRefSpecsPermanently() { var fetchRefSpecs = new string[] { "refs/their/heads/*:refs/my/heads/*", "+refs/their/tag:refs/my/tag" }; - var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; repo.Network.Remotes.Update(remote, r => r.FetchRefSpecs = fetchRefSpecs); } - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; var actualRefSpecs = remote.RefSpecs @@ -124,9 +124,9 @@ public void RemoteUpdaterSavesRefSpecsPermanently() public void CanAddAndRemoveRefSpecs() { string newRefSpec = "+refs/heads/test:refs/heads/other-test"; - var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; @@ -150,7 +150,7 @@ public void CanAddAndRemoveRefSpecs() public void CanClearRefSpecs() { var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; @@ -178,7 +178,7 @@ public void CanClearRefSpecs() public void SettingInvalidRefSpecsThrows(string refSpec) { var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(path)) { var remote = repo.Network.Remotes["origin"]; var oldRefSpecs = remote.RefSpecs.Select(r => r.Specification).ToList(); @@ -198,8 +198,7 @@ public void SettingInvalidRefSpecsThrows(string refSpec) [InlineData("refs/tags/foo", false, false)] public void CanCheckForMatches(string reference, bool shouldMatchSource, bool shouldMatchDest) { - var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(InitNewRepository())) { var remote = repo.Network.Remotes.Add("foo", "blahblah", "refs/heads/*:refs/remotes/foo/*"); var refspec = remote.RefSpecs.Single(); @@ -215,8 +214,7 @@ public void CanCheckForMatches(string reference, bool shouldMatchSource, bool sh [InlineData("refs/heads/master", "refs/remotes/foo/master")] public void CanTransformRefspecs(string lhs, string rhs) { - var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) + using (var repo = new Repository(InitNewRepository())) { var remote = repo.Network.Remotes.Add("foo", "blahblah", "refs/heads/*:refs/remotes/foo/*"); var refspec = remote.RefSpecs.Single(); diff --git a/LibGit2Sharp.Tests/RemoteFixture.cs b/LibGit2Sharp.Tests/RemoteFixture.cs index 8b8c81133..9a8768cb8 100644 --- a/LibGit2Sharp.Tests/RemoteFixture.cs +++ b/LibGit2Sharp.Tests/RemoteFixture.cs @@ -377,9 +377,8 @@ public void CanNotRenameWhenRemoteWithSameNameExists() public void ShoudlPruneOnFetchReflectsTheConfiguredSetting(bool? fetchPrune, bool? remotePrune, bool expectedFetchPrune) { var path = SandboxStandardTestRepo(); - var scd = BuildSelfCleaningDirectory(); - using (var repo = new Repository(path, BuildFakeConfigs(scd))) + using (var repo = new Repository(path)) { Assert.Null(repo.Config.Get("fetch.prune")); Assert.Null(repo.Config.Get("remote.origin.prune")); diff --git a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs index c1fbefb7f..317dab164 100644 --- a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs +++ b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs @@ -16,12 +16,14 @@ public class BaseFixture : IPostTestDirectoryRemover, IDisposable { private readonly List directories = new List(); -#if LEAKS_IDENTIFYING public BaseFixture() { + BuildFakeConfigs(this); + +#if LEAKS_IDENTIFYING LeaksContainer.Clear(); - } #endif + } static BaseFixture() { @@ -80,6 +82,35 @@ private static void SetUpTestEnvironment() CleanupTestReposOlderThan(TimeSpan.FromMinutes(15)); } + public static void BuildFakeConfigs(IPostTestDirectoryRemover dirRemover) + { + var scd = new SelfCleaningDirectory(dirRemover); + + string global = null, xdg = null, system = null; + BuildFakeRepositoryOptions(scd, out global, out xdg, out system); + + StringBuilder sb = new StringBuilder() + .AppendFormat("[Woot]{0}", Environment.NewLine) + .AppendFormat("this-rocks = global{0}", Environment.NewLine) + .AppendFormat("[Wow]{0}", Environment.NewLine) + .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); + File.WriteAllText(Path.Combine(global, ".gitconfig"), sb.ToString()); + + sb = new StringBuilder() + .AppendFormat("[Woot]{0}", Environment.NewLine) + .AppendFormat("this-rocks = system{0}", Environment.NewLine); + File.WriteAllText(Path.Combine(system, "gitconfig"), sb.ToString()); + + sb = new StringBuilder() + .AppendFormat("[Woot]{0}", Environment.NewLine) + .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); + File.WriteAllText(Path.Combine(xdg, "config"), sb.ToString()); + + GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Global, global); + GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Xdg, xdg); + GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.System, system); + } + private static void CleanupTestReposOlderThan(TimeSpan olderThan) { var oldTestRepos = new DirectoryInfo(Constants.TemporaryReposPath) @@ -207,14 +238,6 @@ protected string InitNewRepository(bool isBare = false) return Repository.Init(scd.DirectoryPath, isBare); } - protected Repository InitIsolatedRepository(string path = null, bool isBare = false, RepositoryOptions options = null) - { - path = path ?? InitNewRepository(isBare); - options = BuildFakeConfigs(BuildSelfCleaningDirectory(), options); - - return new Repository(path, options); - } - public void Register(string directoryPath) { directories.Add(directoryPath); @@ -293,42 +316,17 @@ protected static void AssertValueInConfigFile(string configFilePath, string rege Assert.True(r.Success, text); } - public RepositoryOptions BuildFakeConfigs(SelfCleaningDirectory scd, RepositoryOptions options = null) - { - options = BuildFakeRepositoryOptions(scd, options); - - StringBuilder sb = new StringBuilder() - .AppendFormat("[Woot]{0}", Environment.NewLine) - .AppendFormat("this-rocks = global{0}", Environment.NewLine) - .AppendFormat("[Wow]{0}", Environment.NewLine) - .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); - File.WriteAllText(options.GlobalConfigurationLocation, sb.ToString()); - - sb = new StringBuilder() - .AppendFormat("[Woot]{0}", Environment.NewLine) - .AppendFormat("this-rocks = system{0}", Environment.NewLine); - File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); - - sb = new StringBuilder() - .AppendFormat("[Woot]{0}", Environment.NewLine) - .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); - File.WriteAllText(options.XdgConfigurationLocation, sb.ToString()); - - return options; - } - - private static RepositoryOptions BuildFakeRepositoryOptions(SelfCleaningDirectory scd, RepositoryOptions options = null) + private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out string global, out string xdg, out string system) { - options = options ?? new RepositoryOptions(); - string confs = Path.Combine(scd.DirectoryPath, "confs"); Directory.CreateDirectory(confs); - options.GlobalConfigurationLocation = Path.Combine(confs, "my-global-config"); - options.XdgConfigurationLocation = Path.Combine(confs, "my-xdg-config"); - options.SystemConfigurationLocation = Path.Combine(confs, "my-system-config"); - - return options; + global = Path.Combine(confs, "my-global-config"); + Directory.CreateDirectory(global); + xdg = Path.Combine(confs, "my-xdg-config"); + Directory.CreateDirectory(xdg); + system = Path.Combine(confs, "my-system-config"); + Directory.CreateDirectory(system); } /// From f67f385b01b68b2eb6d1f502832821f0fda93c01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 8 Mar 2016 01:46:54 +0100 Subject: [PATCH 39/50] Set the dummy user in the local configuration We set a dummy user name and email in the global configuration through the options. Move away from this obsoleted method and set the configuration at the repo level, which is where a test-specific configuration should live. --- LibGit2Sharp.Tests/CommitFixture.cs | 5 ++-- LibGit2Sharp.Tests/ConfigurationFixture.cs | 27 +++++++------------ LibGit2Sharp.Tests/FilterFixture.cs | 11 +++----- .../FilterSubstitutionCipherFixture.cs | 25 +++++++---------- LibGit2Sharp.Tests/NoteFixture.cs | 10 +++---- LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs | 14 +++------- 6 files changed, 34 insertions(+), 58 deletions(-) diff --git a/LibGit2Sharp.Tests/CommitFixture.cs b/LibGit2Sharp.Tests/CommitFixture.cs index 82148246d..30a996fd7 100644 --- a/LibGit2Sharp.Tests/CommitFixture.cs +++ b/LibGit2Sharp.Tests/CommitFixture.cs @@ -542,11 +542,10 @@ public void DirectlyAccessingAnUnknownTreeEntryOfTheCommitReturnsNull() public void CanCommitWithSignatureFromConfig() { string repoPath = InitNewRepository(); - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - using (var repo = new Repository(repoPath, options)) + using (var repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); diff --git a/LibGit2Sharp.Tests/ConfigurationFixture.cs b/LibGit2Sharp.Tests/ConfigurationFixture.cs index b50fa7e98..ee49fd249 100644 --- a/LibGit2Sharp.Tests/ConfigurationFixture.cs +++ b/LibGit2Sharp.Tests/ConfigurationFixture.cs @@ -139,12 +139,10 @@ public void CanReadStringValue() [Fact] public void CanEnumerateGlobalConfig() { - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - var path = SandboxStandardTestRepoGitDir(); - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); var entry = repo.Config.FirstOrDefault>(e => e.Key == "user.name"); Assert.NotNull(entry); Assert.Equal(Constants.Signature.Name, entry.Value); @@ -196,16 +194,14 @@ public void CanFindInLocalConfig() [Fact] public void CanFindInGlobalConfig() { - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; var path = SandboxStandardTestRepoGitDir(); - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { - var matches = repo.Config.Find(@"\.name", ConfigurationLevel.Global); + var matches = repo.Config.Find("-rocks", ConfigurationLevel.Global); Assert.NotNull(matches); - Assert.Equal(new[] { "user.name" }, + Assert.Equal(new[] { "woot.this-rocks" }, matches.Select(m => m.Key).ToArray()); } } @@ -375,16 +371,14 @@ public void CanAccessConfigurationWithoutARepository(Func localC { var path = SandboxStandardTestRepoGitDir(); - string globalConfigPath = CreateConfigurationWithDummyUser(Constants.Identity); - var options = new RepositoryOptions { GlobalConfigurationLocation = globalConfigPath }; - - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { repo.Config.Set("my.key", "local"); repo.Config.Set("my.key", "mouse", ConfigurationLevel.Global); } - using (var config = Configuration.BuildFrom(localConfigurationPathProvider(path), globalConfigPath)) + var globalPath = Path.Combine(GlobalSettings.GetConfigSearchPaths(ConfigurationLevel.Global).Single(), ".gitconfig"); + using (var config = Configuration.BuildFrom(localConfigurationPathProvider(path), globalPath)) { Assert.Equal("local", config.Get("my.key").Value); Assert.Equal("mouse", config.Get("my.key", ConfigurationLevel.Global).Value); @@ -406,11 +400,10 @@ public void PassingANonExistingLocalConfigurationFileToBuildFromthrowss() public void CannotBuildAProperSignatureFromConfigWhenFullIdentityCannotBeFoundInTheConfig(string name, string email) { string repoPath = InitNewRepository(); - string configPath = CreateConfigurationWithDummyUser(name, email); - var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - using (var repo = new Repository(repoPath, options)) + using (var repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, name, email); Assert.Equal(name, repo.Config.GetValueOrDefault("user.name")); Assert.Equal(email, repo.Config.GetValueOrDefault("user.email")); diff --git a/LibGit2Sharp.Tests/FilterFixture.cs b/LibGit2Sharp.Tests/FilterFixture.cs index 0afc9f702..e0a5282d9 100644 --- a/LibGit2Sharp.Tests/FilterFixture.cs +++ b/LibGit2Sharp.Tests/FilterFixture.cs @@ -276,11 +276,9 @@ public void CanFilterLargeFiles() string attributesPath = Path.Combine(Directory.GetParent(repoPath).Parent.FullName, ".gitattributes"); FileInfo attributesFile = new FileInfo(attributesPath); - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - - using (Repository repo = new Repository(repoPath, repositoryOptions)) + using (Repository repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); File.WriteAllText(attributesPath, "*.blob filter=test"); repo.Stage(attributesFile.Name); repo.Stage(contentFile.Name); @@ -421,9 +419,8 @@ private static FileInfo StageNewFile(IRepository repo, string contents = "null") private Repository CreateTestRepository(string path) { - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - var repository = new Repository(path, repositoryOptions); + var repository = new Repository(path); + CreateConfigurationWithDummyUser(repository, Constants.Identity); CreateAttributesFile(repository, "* filter=test"); return repository; } diff --git a/LibGit2Sharp.Tests/FilterSubstitutionCipherFixture.cs b/LibGit2Sharp.Tests/FilterSubstitutionCipherFixture.cs index a57197626..f022c9571 100644 --- a/LibGit2Sharp.Tests/FilterSubstitutionCipherFixture.cs +++ b/LibGit2Sharp.Tests/FilterSubstitutionCipherFixture.cs @@ -21,10 +21,9 @@ public void SmugdeIsNotCalledForFileWhichDoesNotMatchAnAttributeEntry() string repoPath = InitNewRepository(); string fileName = Guid.NewGuid() + ".rot13"; - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - using (var repo = new Repository(repoPath, repositoryOptions)) + using (var repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); CreateAttributesFile(repo, "*.rot13 filter=rot13"); var blob = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput); @@ -61,10 +60,9 @@ public void CorrectlyEncodesAndDecodesInput() string repoPath = InitNewRepository(); string fileName = Guid.NewGuid() + ".rot13"; - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - using (var repo = new Repository(repoPath, repositoryOptions)) + using (var repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); CreateAttributesFile(repo, "*.rot13 filter=rot13"); var blob = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput); @@ -106,10 +104,9 @@ public void WhenStagedFileDoesNotMatchPathSpecFileIsNotFiltered(string pathSpec, string repoPath = InitNewRepository(); string fileName = Guid.NewGuid() + fileExtension; - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - using (var repo = new Repository(repoPath, repositoryOptions)) + using (var repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); CreateAttributesFile(repo, attributeFileEntry); CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput); @@ -141,10 +138,9 @@ public void CleanIsCalledIfAttributeEntryMatches(string filterAttribute, string string repoPath = InitNewRepository(); string fileName = Guid.NewGuid() + ".txt"; - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - using (var repo = new Repository(repoPath, repositoryOptions)) + using (var repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); CreateAttributesFile(repo, attributeEntry); CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput); @@ -172,10 +168,9 @@ public void SmudgeIsCalledIfAttributeEntryMatches(string filterAttribute, string string repoPath = InitNewRepository(); string fileName = Guid.NewGuid() + ".txt"; - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; - using (var repo = new Repository(repoPath, repositoryOptions)) + using (var repo = new Repository(repoPath)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); CreateAttributesFile(repo, attributeEntry); CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput); diff --git a/LibGit2Sharp.Tests/NoteFixture.cs b/LibGit2Sharp.Tests/NoteFixture.cs index 0c879e3e1..c1ea2b71e 100644 --- a/LibGit2Sharp.Tests/NoteFixture.cs +++ b/LibGit2Sharp.Tests/NoteFixture.cs @@ -168,12 +168,11 @@ public void CreatingANoteWhichAlreadyExistsOverwritesThePreviousNote() [Fact] public void CanAddANoteWithSignatureFromConfig() { - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; string path = SandboxBareTestRepo(); - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); var commit = repo.Lookup("9fd738e8f7967c078dceed8190330fc8648ee56a"); Signature signature = repo.Config.BuildSignature(DateTimeOffset.Now); @@ -268,12 +267,11 @@ public void RemovingANonExistingNoteDoesntThrow() [Fact] public void CanRemoveANoteWithSignatureFromConfig() { - string configPath = CreateConfigurationWithDummyUser(Constants.Identity); - RepositoryOptions options = new RepositoryOptions() { GlobalConfigurationLocation = configPath }; string path = SandboxBareTestRepo(); - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { + CreateConfigurationWithDummyUser(repo, Constants.Identity); var commit = repo.Lookup("8496071c1b46c854b31185ea97743be6a8774479"); var notes = repo.Notes[commit.Id]; diff --git a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs index 317dab164..4c76aefe1 100644 --- a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs +++ b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs @@ -335,18 +335,14 @@ private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out st /// The configuration file will be removed automatically when the tests are finished /// The identity to use for user.name and user.email /// The path to the configuration file - protected string CreateConfigurationWithDummyUser(Identity identity) + protected void CreateConfigurationWithDummyUser(Repository repo, Identity identity) { - return CreateConfigurationWithDummyUser(identity.Name, identity.Email); + CreateConfigurationWithDummyUser(repo, identity.Name, identity.Email); } - protected string CreateConfigurationWithDummyUser(string name, string email) + protected void CreateConfigurationWithDummyUser(Repository repo, string name, string email) { - SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); - - string configFilePath = Touch(scd.DirectoryPath, "fake-config"); - - using (Configuration config = Configuration.BuildFrom(configFilePath)) + Configuration config = repo.Config; { if (name != null) { @@ -358,8 +354,6 @@ protected string CreateConfigurationWithDummyUser(string name, string email) config.Set("user.email", email); } } - - return configFilePath; } /// From 917f6537d647918e99799fa1cdc8e8438852d042 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 8 Mar 2016 09:21:52 +0100 Subject: [PATCH 40/50] Remove the last uses of explicit config paths for Repository These tests use the option to set a global configuration file with the filemode we want. But the filemode setting should be set per-repository as it comes down to the workdir for each repository. Switch to setting the configuration in the local configuration, which is also more in line with how it would exist in the wild. --- LibGit2Sharp.Tests/DiffTreeToTreeFixture.cs | 31 ++++--------------- .../DiffWorkdirToIndexFixture.cs | 31 ++++--------------- 2 files changed, 12 insertions(+), 50 deletions(-) diff --git a/LibGit2Sharp.Tests/DiffTreeToTreeFixture.cs b/LibGit2Sharp.Tests/DiffTreeToTreeFixture.cs index bebbdded0..ebd426787 100644 --- a/LibGit2Sharp.Tests/DiffTreeToTreeFixture.cs +++ b/LibGit2Sharp.Tests/DiffTreeToTreeFixture.cs @@ -1044,12 +1044,9 @@ public void ComparingReliesOnProvidedConfigEntriesIfAny() repo.Config.Unset("core.filemode"); } - SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); - - var options = BuildFakeSystemConfigFilemodeOption(scd, true); - - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { + SetFilemode(repo, true); var changes = repo.Diff.Compare(new[] { file }); Assert.Equal(1, changes.Count()); @@ -1059,34 +1056,18 @@ public void ComparingReliesOnProvidedConfigEntriesIfAny() Assert.Equal(Mode.NonExecutableFile, change.Mode); } - options = BuildFakeSystemConfigFilemodeOption(scd, false); - - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { + SetFilemode(repo, false); var changes = repo.Diff.Compare(new[] { file }); Assert.Equal(0, changes.Count()); } } - private RepositoryOptions BuildFakeSystemConfigFilemodeOption( - SelfCleaningDirectory scd, - bool value) + void SetFilemode(Repository repo, bool value) { - Directory.CreateDirectory(scd.DirectoryPath); - - var options = new RepositoryOptions - { - SystemConfigurationLocation = Path.Combine( - scd.RootedDirectoryPath, "fake-system.config") - }; - - StringBuilder sb = new StringBuilder() - .AppendFormat("[core]{0}", Environment.NewLine) - .AppendFormat("filemode = {1}{0}", Environment.NewLine, value); - Touch("", options.SystemConfigurationLocation, sb.ToString()); - - return options; + repo.Config.Set("core.filemode", value); } [Fact] diff --git a/LibGit2Sharp.Tests/DiffWorkdirToIndexFixture.cs b/LibGit2Sharp.Tests/DiffWorkdirToIndexFixture.cs index 65f075826..f08ee877a 100644 --- a/LibGit2Sharp.Tests/DiffWorkdirToIndexFixture.cs +++ b/LibGit2Sharp.Tests/DiffWorkdirToIndexFixture.cs @@ -127,12 +127,9 @@ public void ComparingReliesOnProvidedConfigEntriesIfAny() repo.Config.Unset("core.filemode", ConfigurationLevel.Local); } - SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); - - var options = BuildFakeSystemConfigFilemodeOption(scd, true); - - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { + SetFilemode(repo, true); var changes = repo.Diff.Compare(new[] { file }); Assert.Equal(1, changes.Count()); @@ -142,34 +139,18 @@ public void ComparingReliesOnProvidedConfigEntriesIfAny() Assert.Equal(Mode.NonExecutableFile, change.Mode); } - options = BuildFakeSystemConfigFilemodeOption(scd, false); - - using (var repo = new Repository(path, options)) + using (var repo = new Repository(path)) { + SetFilemode(repo, false); var changes = repo.Diff.Compare(new[] { file }); Assert.Equal(0, changes.Count()); } } - private RepositoryOptions BuildFakeSystemConfigFilemodeOption( - SelfCleaningDirectory scd, - bool value) + void SetFilemode(Repository repo, bool value) { - Directory.CreateDirectory(scd.DirectoryPath); - - var options = new RepositoryOptions - { - SystemConfigurationLocation = Path.Combine( - scd.RootedDirectoryPath, "fake-system.config") - }; - - StringBuilder sb = new StringBuilder() - .AppendFormat("[core]{0}", Environment.NewLine) - .AppendFormat("filemode = {1}{0}", Environment.NewLine, value); - File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); - - return options; + repo.Config.Set("core.filemode", value); } [Fact] From 4924146c52b971ec356b5c88bfb9b92202356443 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 8 Mar 2016 09:37:55 +0100 Subject: [PATCH 41/50] Add CHANGES entry for config paths in RepositoryOptions --- CHANGES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index e2933860f..4c71613e1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -16,6 +16,8 @@ ### Changes + - Obsolete the config paths in RepositoryOptions + ### Fixes ## v0.22 - ([diff](https://github.com/libgit2/libgit2sharp/compare/v0.21.1...v0.22)) From 840422d3b11887f8249445e9b7b859c1e5283996 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 9 Mar 2016 11:47:43 +0100 Subject: [PATCH 42/50] Don't load an object just to check its ID In order to check for equality we just need to compare the ID of the object. We do not need to look up the object but can compare their identifiers directly. This also requires us to modify Branch's check for the current branch, but the new code more accurately reflects the check we do want to perform. Namely whether HEAD points to our reference name. --- LibGit2Sharp/Branch.cs | 10 +++++++++- LibGit2Sharp/ReferenceWrapper.cs | 4 +++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/LibGit2Sharp/Branch.cs b/LibGit2Sharp/Branch.cs index 31fe33d89..dbb1dd9ec 100644 --- a/LibGit2Sharp/Branch.cs +++ b/LibGit2Sharp/Branch.cs @@ -106,7 +106,15 @@ public virtual BranchTrackingDetails TrackingDetails /// public virtual bool IsCurrentRepositoryHead { - get { return repo.Head == this; } + get + { + if (this is DetachedHead) + { + return repo.Head.reference.TargetIdentifier == this.reference.TargetIdentifier; + } + + return repo.Head.reference.TargetIdentifier == this.CanonicalName; + } } /// diff --git a/LibGit2Sharp/ReferenceWrapper.cs b/LibGit2Sharp/ReferenceWrapper.cs index 9b5f151d3..349be3008 100644 --- a/LibGit2Sharp/ReferenceWrapper.cs +++ b/LibGit2Sharp/ReferenceWrapper.cs @@ -16,10 +16,11 @@ public abstract class ReferenceWrapper : IEquatable protected readonly Repository repo; + protected readonly Reference reference; private readonly Lazy objectBuilder; private static readonly LambdaEqualityHelper> equalityHelper = - new LambdaEqualityHelper>(x => x.CanonicalName, x => x.TargetObject); + new LambdaEqualityHelper>(x => x.CanonicalName, x => x.reference.TargetIdentifier); private readonly string canonicalName; @@ -40,6 +41,7 @@ protected internal ReferenceWrapper(Repository repo, Reference reference, Func(() => RetrieveTargetObject(reference)); } From 06d28664826a029dbd53fea48c61a4bf2e0c004f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 9 Mar 2016 20:34:32 +0100 Subject: [PATCH 43/50] Make tests aware of the ProgramData config level --- LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs | 14 +++++++++++--- LibGit2Sharp/ConfigurationLevel.cs | 5 +++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs index 4c76aefe1..349921766 100644 --- a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs +++ b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs @@ -86,8 +86,8 @@ public static void BuildFakeConfigs(IPostTestDirectoryRemover dirRemover) { var scd = new SelfCleaningDirectory(dirRemover); - string global = null, xdg = null, system = null; - BuildFakeRepositoryOptions(scd, out global, out xdg, out system); + string global = null, xdg = null, system = null, programData = null; + BuildFakeRepositoryOptions(scd, out global, out xdg, out system, out programData); StringBuilder sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) @@ -106,9 +106,15 @@ public static void BuildFakeConfigs(IPostTestDirectoryRemover dirRemover) .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); File.WriteAllText(Path.Combine(xdg, "config"), sb.ToString()); + sb = new StringBuilder() + .AppendFormat("[Woot]{0}", Environment.NewLine) + .AppendFormat("this-rocks = programdata{0}", Environment.NewLine); + File.WriteAllText(Path.Combine(programData, "config"), sb.ToString()); + GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Global, global); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Xdg, xdg); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.System, system); + GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.ProgramData, programData); } private static void CleanupTestReposOlderThan(TimeSpan olderThan) @@ -316,7 +322,7 @@ protected static void AssertValueInConfigFile(string configFilePath, string rege Assert.True(r.Success, text); } - private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out string global, out string xdg, out string system) + private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out string global, out string xdg, out string system, out string programData) { string confs = Path.Combine(scd.DirectoryPath, "confs"); Directory.CreateDirectory(confs); @@ -327,6 +333,8 @@ private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out st Directory.CreateDirectory(xdg); system = Path.Combine(confs, "my-system-config"); Directory.CreateDirectory(system); + programData = Path.Combine(confs, "my-programdata-config"); + Directory.CreateDirectory(programData); } /// diff --git a/LibGit2Sharp/ConfigurationLevel.cs b/LibGit2Sharp/ConfigurationLevel.cs index 92122727a..9fd57df28 100644 --- a/LibGit2Sharp/ConfigurationLevel.cs +++ b/LibGit2Sharp/ConfigurationLevel.cs @@ -24,5 +24,10 @@ public enum ConfigurationLevel /// The system wide .gitconfig. /// System = 2, + + /// + /// Another system-wide configuration on Windows. + /// + ProgramData = 1, } } From ebc43b4547b2367adfd26d9f8edfb043c854ac7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Wed, 9 Mar 2016 22:21:36 +0100 Subject: [PATCH 44/50] Teach the custom config builder about ProgramData --- LibGit2Sharp/Configuration.cs | 7 +++++++ LibGit2Sharp/Core/NativeMethods.cs | 3 +++ LibGit2Sharp/Core/Proxy.cs | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/LibGit2Sharp/Configuration.cs b/LibGit2Sharp/Configuration.cs index 5a2f2be18..a59b93b60 100644 --- a/LibGit2Sharp/Configuration.cs +++ b/LibGit2Sharp/Configuration.cs @@ -19,6 +19,7 @@ public class Configuration : IDisposable, private readonly FilePath globalConfigPath; private readonly FilePath xdgConfigPath; private readonly FilePath systemConfigPath; + private readonly FilePath programDataConfigPath; private ConfigurationSafeHandle configHandle; @@ -43,6 +44,7 @@ internal Configuration( globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global(); xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg(); systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system(); + programDataConfigPath = Proxy.git_config_find_programdata(); Init(repository); } @@ -81,6 +83,11 @@ private void Init(Repository repository) { Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System); } + + if (programDataConfigPath != null) + { + Proxy.git_config_add_file_ondisk(configHandle, programDataConfigPath, ConfigurationLevel.ProgramData); + } } private FilePath NormalizeConfigPath(FilePath path) diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 94cbe7c27..2a80146c8 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -344,6 +344,9 @@ internal static extern int git_config_delete_multivar( [DllImport(libgit2)] internal static extern int git_config_find_xdg(GitBuf xdg_config_path); + [DllImport(libgit2)] + internal static extern int git_config_find_programdata(GitBuf programdata_config_path); + [DllImport(libgit2)] internal static extern void git_config_free(IntPtr cfg); diff --git a/LibGit2Sharp/Core/Proxy.cs b/LibGit2Sharp/Core/Proxy.cs index b19fa6499..47c7d0352 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -468,6 +468,11 @@ public static FilePath git_config_find_xdg() return ConvertPath(NativeMethods.git_config_find_xdg); } + public static FilePath git_config_find_programdata() + { + return ConvertPath(NativeMethods.git_config_find_programdata); + } + public static void git_config_free(IntPtr config) { NativeMethods.git_config_free(config); From 3615df921ded6e58b08bc438645d9291804f5db1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Tue, 15 Mar 2016 09:52:42 +0100 Subject: [PATCH 45/50] Suppress or fix some unused varible warnings These (except for the one) are there to keep the pointers alive, so we do want them there even if we never read from them. --- LibGit2Sharp.Tests/SmartSubtransportFixture.cs | 2 +- LibGit2Sharp/Core/NativeMethods.cs | 3 +++ LibGit2Sharp/RefSpec.cs | 3 +++ LibGit2Sharp/RefSpecCollection.cs | 3 +++ 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/LibGit2Sharp.Tests/SmartSubtransportFixture.cs b/LibGit2Sharp.Tests/SmartSubtransportFixture.cs index 6d4e0fe40..f8bf3d90c 100644 --- a/LibGit2Sharp.Tests/SmartSubtransportFixture.cs +++ b/LibGit2Sharp.Tests/SmartSubtransportFixture.cs @@ -84,7 +84,7 @@ public void CanUseCredentials(string scheme, string url, string user, string pas string remoteName = "testRemote"; var scd = BuildSelfCleaningDirectory(); - var repoPath = Repository.Init(scd.RootedDirectoryPath); + Repository.Init(scd.RootedDirectoryPath); SmartSubtransportRegistration registration = null; diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 94cbe7c27..184d549ac 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -14,7 +14,10 @@ internal static class NativeMethods { public const uint GIT_PATH_MAX = 4096; private const string libgit2 = NativeDllName.Name; + // This is here to keep the pointer alive + #pragma warning disable 0414 private static readonly LibraryLifetimeObject lifetimeObject; + #pragma warning restore 0414 private static int handlesCount; /// diff --git a/LibGit2Sharp/RefSpec.cs b/LibGit2Sharp/RefSpec.cs index aeeabb75e..bf6af7cec 100644 --- a/LibGit2Sharp/RefSpec.cs +++ b/LibGit2Sharp/RefSpec.cs @@ -12,7 +12,10 @@ namespace LibGit2Sharp [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RefSpec { + // This is here to keep the pointer alive + #pragma warning disable 0414 readonly Remote remote; + #pragma warning restore 0414 readonly GitRefSpecHandle handle; internal RefSpec(Remote remote, GitRefSpecHandle handle) diff --git a/LibGit2Sharp/RefSpecCollection.cs b/LibGit2Sharp/RefSpecCollection.cs index 46b1c4360..cd483955a 100644 --- a/LibGit2Sharp/RefSpecCollection.cs +++ b/LibGit2Sharp/RefSpecCollection.cs @@ -15,8 +15,11 @@ namespace LibGit2Sharp [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RefSpecCollection : IEnumerable { + // These are here to keep the pointer alive + #pragma warning disable 0414 readonly Remote remote; readonly RemoteSafeHandle handle; + #pragma warning restore 0414 readonly Lazy> refspecs; /// From d45523c2110e7e8691a6fafe5f11da45cc4ce53d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 15 Feb 2016 11:22:22 +0100 Subject: [PATCH 46/50] Bring back LeaksContainer It went away when removing the base safe handle, but we need it for the debug/CI builds. --- LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs | 2 +- LibGit2Sharp/Core/Handles/Libgit2Object.cs | 114 +++++++++++++++++- LibGit2Sharp/Tree.cs | 5 +- 3 files changed, 116 insertions(+), 5 deletions(-) diff --git a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs index c1fbefb7f..38a9306e1 100644 --- a/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs +++ b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs @@ -234,7 +234,7 @@ public virtual void Dispose() if (LeaksContainer.TypeNames.Any()) { Assert.False(true, string.Format("Some handles of the following types haven't been properly released: {0}.{1}" - + "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in SafeHandleBase.cs{1}" + + "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in Libgit2Object.cs{1}" + "and run the tests locally.", string.Join(", ", LeaksContainer.TypeNames), Environment.NewLine)); } #endif diff --git a/LibGit2Sharp/Core/Handles/Libgit2Object.cs b/LibGit2Sharp/Core/Handles/Libgit2Object.cs index 134e75313..cbb431a98 100644 --- a/LibGit2Sharp/Core/Handles/Libgit2Object.cs +++ b/LibGit2Sharp/Core/Handles/Libgit2Object.cs @@ -1,9 +1,90 @@ -using System; +// This activates a lightweight mode which will help put under the light +// incorrectly released handles by outputing a warning message in the console. +// +// This should be activated when tests are being run of the CI server. +// +// Uncomment the line below or add a conditional symbol to activate this mode + +// #define LEAKS_IDENTIFYING + +// This activates a more throrough mode which will show the stack trace of the +// allocation code path for each handle that has been improperly released. +// +// This should be manually activated when some warnings have been raised as +// a result of LEAKS_IDENTIFYING mode activation. +// +// Uncomment the line below or add a conditional symbol to activate this mode + +// #define LEAKS_TRACKING + +using System; +using System.Linq; +using System.Diagnostics; +using System.Globalization; +using System.Collections.Generic; + +#if LEAKS_IDENTIFYING +namespace LibGit2Sharp.Core +{ + /// + /// Holds leaked handle type names reported by + /// + public static class LeaksContainer + { + private static readonly HashSet _typeNames = new HashSet(); + private static readonly object _lockpad = new object(); + + /// + /// Report a new leaked handle type name + /// + /// Short name of the leaked handle type. + public static void Add(string typeName) + { + lock (_lockpad) + { + _typeNames.Add(typeName); + } + } + + /// + /// Removes all previously reported leaks. + /// + public static void Clear() + { + lock (_lockpad) + { + _typeNames.Clear(); + } + } + + /// + /// Returns all reported leaked handle type names. + /// + public static IEnumerable TypeNames + { + get + { + string[] result = null; + lock (_lockpad) + { + result = _typeNames.ToArray(); + } + return result; + } + } + } +} +#endif namespace LibGit2Sharp.Core.Handles { internal unsafe abstract class Libgit2Object : IDisposable { +#if LEAKS_TRACKING + private readonly string trace; + private readonly Guid id; +#endif + protected void* ptr; internal void* Handle @@ -21,12 +102,17 @@ internal unsafe Libgit2Object(void* handle, bool owned) { this.ptr = handle; this.owned = owned; + +#if LEAKS_TRACKING + id = Guid.NewGuid(); + Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Allocating {0} handle ({1})", GetType().Name, id)); + trace = new StackTrace(2, true).ToString(); +#endif } internal unsafe Libgit2Object(IntPtr ptr, bool owned) + : this(ptr.ToPointer(), owned) { - this.ptr = ptr.ToPointer(); - this.owned = owned; } ~Libgit2Object() @@ -51,6 +137,15 @@ internal IntPtr AsIntPtr() void Dispose(bool disposing) { + #if LEAKS_IDENTIFYING + bool leaked = !disposing && ptr != null; + + if (leaked) + { + LeaksContainer.Add(GetType().Name); + } +#endif + if (!disposed) { if (owned) @@ -62,6 +157,19 @@ void Dispose(bool disposing) } disposed = true; + +#if LEAKS_TRACKING + if (!leaked) + { + Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Disposing {0} handle ({1})", GetType().Name, id)); + } + else + { + Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Unexpected finalization of {0} handle ({1})", GetType().Name, id)); + Trace.WriteLine(trace); + Trace.WriteLine(""); + } +#endif } public void Dispose() diff --git a/LibGit2Sharp/Tree.cs b/LibGit2Sharp/Tree.cs index af7946186..0a19f4e04 100644 --- a/LibGit2Sharp/Tree.cs +++ b/LibGit2Sharp/Tree.cs @@ -77,7 +77,10 @@ internal string Path unsafe TreeEntry byIndex(ObjectSafeWrapper obj, uint i, ObjectId parentTreeId, Repository repo, FilePath parentPath) { - return new TreeEntry(Proxy.git_tree_entry_byindex(obj.ObjectPtr, i), parentTreeId, repo, parentPath); + using (var entryHandle = Proxy.git_tree_entry_byindex(obj.ObjectPtr, i)) + { + return new TreeEntry(entryHandle, parentTreeId, repo, parentPath); + } } /// From 9225134e7074f4dba33ab7caa1c940e12e900c4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 21 Mar 2016 10:02:16 +0100 Subject: [PATCH 47/50] Dispose of a few Remotes in the tests --- LibGit2Sharp.Tests/RefSpecFixture.cs | 35 +++++++++++++++------------- LibGit2Sharp/RepositoryExtensions.cs | 6 +++-- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/LibGit2Sharp.Tests/RefSpecFixture.cs b/LibGit2Sharp.Tests/RefSpecFixture.cs index fa272746a..b9ac369e9 100644 --- a/LibGit2Sharp.Tests/RefSpecFixture.cs +++ b/LibGit2Sharp.Tests/RefSpecFixture.cs @@ -105,8 +105,10 @@ public void RemoteUpdaterSavesRefSpecsPermanently() using (var repo = new Repository(path)) { - var remote = repo.Network.Remotes["origin"]; - repo.Network.Remotes.Update(remote, r => r.FetchRefSpecs = fetchRefSpecs); + using (var remote = repo.Network.Remotes["origin"]) + { + repo.Network.Remotes.Update(remote, r => r.FetchRefSpecs = fetchRefSpecs); + } } using (var repo = new Repository(path)) @@ -127,22 +129,23 @@ public void CanAddAndRemoveRefSpecs() var path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) + using (var remote = repo.Network.Remotes["origin"]) { - var remote = repo.Network.Remotes["origin"]; - - remote = repo.Network.Remotes.Update(remote, + using (var updatedRemote = repo.Network.Remotes.Update(remote, r => r.FetchRefSpecs.Add(newRefSpec), - r => r.PushRefSpecs.Add(newRefSpec)); - - Assert.Contains(newRefSpec, remote.FetchRefSpecs.Select(r => r.Specification)); - Assert.Contains(newRefSpec, remote.PushRefSpecs.Select(r => r.Specification)); - - remote = repo.Network.Remotes.Update(remote, - r => r.FetchRefSpecs.Remove(newRefSpec), - r => r.PushRefSpecs.Remove(newRefSpec)); - - Assert.DoesNotContain(newRefSpec, remote.FetchRefSpecs.Select(r => r.Specification)); - Assert.DoesNotContain(newRefSpec, remote.PushRefSpecs.Select(r => r.Specification)); + r => r.PushRefSpecs.Add(newRefSpec))) + { + Assert.Contains(newRefSpec, updatedRemote.FetchRefSpecs.Select(r => r.Specification)); + Assert.Contains(newRefSpec, updatedRemote.PushRefSpecs.Select(r => r.Specification)); + + using (var updatedRemote2 = repo.Network.Remotes.Update(updatedRemote, + r => r.FetchRefSpecs.Remove(newRefSpec), + r => r.PushRefSpecs.Remove(newRefSpec))) + { + Assert.DoesNotContain(newRefSpec, updatedRemote2.FetchRefSpecs.Select(r => r.Specification)); + Assert.DoesNotContain(newRefSpec, updatedRemote2.PushRefSpecs.Select(r => r.Specification)); + } + } } } diff --git a/LibGit2Sharp/RepositoryExtensions.cs b/LibGit2Sharp/RepositoryExtensions.cs index 447470bac..5f162325b 100644 --- a/LibGit2Sharp/RepositoryExtensions.cs +++ b/LibGit2Sharp/RepositoryExtensions.cs @@ -221,8 +221,10 @@ public static void Fetch(this IRepository repository, string remoteName, FetchOp Ensure.ArgumentNotNull(repository, "repository"); Ensure.ArgumentNotNullOrEmptyString(remoteName, "remoteName"); - Remote remote = repository.Network.Remotes.RemoteForName(remoteName, true); - repository.Network.Fetch(remote, options); + using (Remote remote = repository.Network.Remotes.RemoteForName(remoteName, true)) + { + repository.Network.Fetch(remote, options); + } } /// From 395616b19d998280288c5bd8e511f9c33400065c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 21 Mar 2016 14:42:54 +0100 Subject: [PATCH 48/50] Register Remotes for cleanup with the repo --- LibGit2Sharp/Remote.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/LibGit2Sharp/Remote.cs b/LibGit2Sharp/Remote.cs index 327b9bec3..3930fdd28 100644 --- a/LibGit2Sharp/Remote.cs +++ b/LibGit2Sharp/Remote.cs @@ -39,6 +39,7 @@ internal Remote(RemoteHandle handle, Repository repository) PushUrl = Proxy.git_remote_pushurl(handle); TagFetchMode = Proxy.git_remote_autotag(handle); refSpecs = new RefSpecCollection(this, handle); + repository.RegisterForCleanup(this); } ~Remote() From 04fe088444e8a475205f476a893feaa9e67bcc46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 21 Mar 2016 14:49:03 +0100 Subject: [PATCH 49/50] fixup! Merge remote-tracking branch 'upstream/master' into pointers --- LibGit2Sharp/Core/NativeMethods.cs | 2 -- LibGit2Sharp/RefSpecCollection.cs | 1 - 2 files changed, 3 deletions(-) diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index f61bd8761..326e8997e 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -1116,7 +1116,6 @@ internal static extern unsafe UIntPtr git_reflog_entrycount internal static extern unsafe string git_reflog_entry_message(git_reflog_entry* entry); [DllImport(libgit2)] - [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern int git_refspec_transform( GitBuf buf, IntPtr refspec, @@ -1124,7 +1123,6 @@ internal static extern int git_refspec_transform( [DllImport(libgit2)] - [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern int git_refspec_rtransform( GitBuf buf, IntPtr refspec, diff --git a/LibGit2Sharp/RefSpecCollection.cs b/LibGit2Sharp/RefSpecCollection.cs index b7aa3dfca..6ba813e47 100644 --- a/LibGit2Sharp/RefSpecCollection.cs +++ b/LibGit2Sharp/RefSpecCollection.cs @@ -45,7 +45,6 @@ static unsafe IList RetrieveRefSpecs(Remote remote, RemoteHandle remote for (int i = 0; i < count; i++) { - git_refspec* handle = Proxy.git_remote_get_refspec(remoteHandle, i); refSpecs.Add(new RefSpec(remote, Proxy.git_remote_get_refspec(remoteHandle, i))); } From 93e1d46f47e030729904e08c4c30694632c8dfbc Mon Sep 17 00:00:00 2001 From: Carlos Martin Nieto Date: Mon, 21 Mar 2016 14:38:20 -0700 Subject: [PATCH 50/50] Do convert unsafe paths into native This lets us have the platform-specific path separators. --- LibGit2Sharp/Core/FilePathMarshaler.cs | 5 +++++ LibGit2Sharp/IndexNameEntry.cs | 6 +++--- LibGit2Sharp/RepositoryStatus.cs | 10 +++++----- LibGit2Sharp/TreeEntryChanges.cs | 4 ++-- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/LibGit2Sharp/Core/FilePathMarshaler.cs b/LibGit2Sharp/Core/FilePathMarshaler.cs index db28409c1..9d238a46d 100644 --- a/LibGit2Sharp/Core/FilePathMarshaler.cs +++ b/LibGit2Sharp/Core/FilePathMarshaler.cs @@ -117,6 +117,11 @@ public override Object MarshalNativeToManaged(IntPtr pNativeData) return LaxUtf8Marshaler.FromNative(pNativeData); } + public new static unsafe FilePath FromNative(char* buffer) + { + return LaxUtf8Marshaler.FromNative(buffer); + } + public new static FilePath FromBuffer(byte[] buffer) { return LaxUtf8Marshaler.FromBuffer(buffer); diff --git a/LibGit2Sharp/IndexNameEntry.cs b/LibGit2Sharp/IndexNameEntry.cs index 8cc4f5396..79b3f6993 100644 --- a/LibGit2Sharp/IndexNameEntry.cs +++ b/LibGit2Sharp/IndexNameEntry.cs @@ -30,13 +30,13 @@ internal static unsafe IndexNameEntry BuildFromPtr(git_index_name_entry* entry) } string ancestor = entry->ancestor != null - ? LaxFilePathMarshaler.FromNative(entry->ancestor) + ? LaxFilePathMarshaler.FromNative(entry->ancestor).Native : null; string ours = entry->ours != null - ? LaxFilePathMarshaler.FromNative(entry->ours) + ? LaxFilePathMarshaler.FromNative(entry->ours).Native : null; string theirs = entry->theirs != null - ? LaxFilePathMarshaler.FromNative(entry->theirs) + ? LaxFilePathMarshaler.FromNative(entry->theirs).Native : null; return new IndexNameEntry diff --git a/LibGit2Sharp/RepositoryStatus.cs b/LibGit2Sharp/RepositoryStatus.cs index 9a8e662c9..a70212844 100644 --- a/LibGit2Sharp/RepositoryStatus.cs +++ b/LibGit2Sharp/RepositoryStatus.cs @@ -138,16 +138,16 @@ private unsafe void AddStatusEntryForDelta(FileStatus gitStatus, git_diff_delta* if ((gitStatus & FileStatus.RenamedInIndex) == FileStatus.RenamedInIndex) { headToIndexRenameDetails = - new RenameDetails(LaxFilePathMarshaler.FromNative(deltaHeadToIndex->old_file.Path), - LaxFilePathMarshaler.FromNative(deltaHeadToIndex->new_file.Path), + new RenameDetails(LaxFilePathMarshaler.FromNative(deltaHeadToIndex->old_file.Path).Native, + LaxFilePathMarshaler.FromNative(deltaHeadToIndex->new_file.Path).Native, (int)deltaHeadToIndex->similarity); } if ((gitStatus & FileStatus.RenamedInWorkdir) == FileStatus.RenamedInWorkdir) { indexToWorkDirRenameDetails = - new RenameDetails(LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->old_file.Path), - LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->new_file.Path), + new RenameDetails(LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->old_file.Path).Native, + LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->new_file.Path).Native, (int)deltaIndexToWorkDir->similarity); } @@ -155,7 +155,7 @@ private unsafe void AddStatusEntryForDelta(FileStatus gitStatus, git_diff_delta* ? LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->new_file.Path) : LaxFilePathMarshaler.FromNative(deltaHeadToIndex->new_file.Path); - StatusEntry statusEntry = new StatusEntry(filePath, gitStatus, headToIndexRenameDetails, indexToWorkDirRenameDetails); + StatusEntry statusEntry = new StatusEntry(filePath.Native, gitStatus, headToIndexRenameDetails, indexToWorkDirRenameDetails); if (gitStatus == FileStatus.Unaltered) { diff --git a/LibGit2Sharp/TreeEntryChanges.cs b/LibGit2Sharp/TreeEntryChanges.cs index 4fdf83fea..53f2ce49e 100644 --- a/LibGit2Sharp/TreeEntryChanges.cs +++ b/LibGit2Sharp/TreeEntryChanges.cs @@ -18,8 +18,8 @@ protected TreeEntryChanges() internal unsafe TreeEntryChanges(git_diff_delta* delta) { - Path = LaxFilePathMarshaler.FromNative(delta->new_file.Path); - OldPath = LaxFilePathMarshaler.FromNative(delta->old_file.Path); + Path = LaxFilePathMarshaler.FromNative(delta->new_file.Path).Native; + OldPath = LaxFilePathMarshaler.FromNative(delta->old_file.Path).Native; Mode = (Mode)delta->new_file.Mode; OldMode = (Mode)delta->old_file.Mode;