From 637fee10913a1a4ee9636c510b896a85c2603a95 Mon Sep 17 00:00:00 2001 From: Tim Clem Date: Fri, 1 Jun 2012 11:08:28 -0700 Subject: [PATCH 1/2] Use csharp friendly names for error classes/codes This also introduces a new marshaler for GitError along with a distinction between exception (errors) in libgit2 vs. exceptions in libgit2sharp. See LibGit2SharpException and LibGit2Exception This has been done in a way to not break the public API. --- LibGit2Sharp.Tests/BranchFixture.cs | 16 +++---- LibGit2Sharp.Tests/CommitFixture.cs | 10 ++--- LibGit2Sharp.Tests/ConfigurationFixture.cs | 2 +- LibGit2Sharp.Tests/IndexFixture.cs | 18 ++++++-- LibGit2Sharp.Tests/RepositoryFixture.cs | 2 +- LibGit2Sharp.Tests/ResetFixture.cs | 6 +-- LibGit2Sharp.Tests/TagFixture.cs | 12 ++--- LibGit2Sharp/BranchCollection.cs | 2 +- LibGit2Sharp/CommitCollection.cs | 8 ++-- LibGit2Sharp/Configuration.cs | 14 +++--- LibGit2Sharp/Core/Ensure.cs | 29 ++---------- LibGit2Sharp/Core/GitError.cs | 26 ++--------- LibGit2Sharp/Core/GitErrorClass.cs | 21 +++++++++ LibGit2Sharp/Core/GitErrorCode.cs | 40 +++++++++++++---- LibGit2Sharp/Core/GitErrorMarshaler.cs | 44 +++++++++++++++++++ LibGit2Sharp/Core/GitObjectExtensions.cs | 2 +- .../Core/Handles/GitErrorSafeHandle.cs | 12 ----- LibGit2Sharp/Core/NativeMethods.cs | 3 +- LibGit2Sharp/GitObject.cs | 2 +- LibGit2Sharp/Index.cs | 12 ++--- LibGit2Sharp/LibGit2Exception.cs | 33 ++++++++------ LibGit2Sharp/LibGit2Sharp.csproj | 3 +- LibGit2Sharp/NoteCollection.cs | 4 +- LibGit2Sharp/ObjectDatabase.cs | 2 +- LibGit2Sharp/Reference.cs | 4 +- LibGit2Sharp/ReferenceCollection.cs | 6 +-- LibGit2Sharp/RemoteCollection.cs | 2 +- LibGit2Sharp/Repository.cs | 8 ++-- LibGit2Sharp/RepositoryExtensions.cs | 2 +- LibGit2Sharp/Tree.cs | 2 +- 30 files changed, 201 insertions(+), 146 deletions(-) create mode 100644 LibGit2Sharp/Core/GitErrorClass.cs create mode 100644 LibGit2Sharp/Core/GitErrorMarshaler.cs delete mode 100644 LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs diff --git a/LibGit2Sharp.Tests/BranchFixture.cs b/LibGit2Sharp.Tests/BranchFixture.cs index 60c1126a5..e956fbf1a 100644 --- a/LibGit2Sharp.Tests/BranchFixture.cs +++ b/LibGit2Sharp.Tests/BranchFixture.cs @@ -125,9 +125,9 @@ public void CreatingABranchFromANonCommitObjectThrows() using (var repo = new Repository(BareTestRepoPath)) { const string name = "sorry-dude-i-do-not-do-blobs-nor-trees"; - Assert.Throws(() => repo.CreateBranch(name, "refs/tags/point_to_blob")); - Assert.Throws(() => repo.CreateBranch(name, "53fc32d")); - Assert.Throws(() => repo.CreateBranch(name, "0266163")); + Assert.Throws(() => repo.CreateBranch(name, "refs/tags/point_to_blob")); + Assert.Throws(() => repo.CreateBranch(name, "53fc32d")); + Assert.Throws(() => repo.CreateBranch(name, "0266163")); } } @@ -136,7 +136,7 @@ public void CreatingBranchWithUnknownNamedTargetThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Branches.Create("my_new_branch", "my_old_branch")); + Assert.Throws(() => repo.Branches.Create("my_new_branch", "my_old_branch")); } } @@ -145,8 +145,8 @@ public void CreatingBranchWithUnknownShaTargetThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Branches.Create("my_new_branch", Constants.UnknownSha)); - Assert.Throws(() => repo.Branches.Create("my_new_branch", Constants.UnknownSha.Substring(0, 7))); + Assert.Throws(() => repo.Branches.Create("my_new_branch", Constants.UnknownSha)); + Assert.Throws(() => repo.Branches.Create("my_new_branch", Constants.UnknownSha.Substring(0, 7))); } } @@ -155,7 +155,7 @@ public void CreatingABranchPointingAtANonCanonicalReferenceThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Branches.Create("nocanonicaltarget", "br2")); + Assert.Throws(() => repo.Branches.Create("nocanonicaltarget", "br2")); } } @@ -414,7 +414,7 @@ public void CheckingOutANonExistingBranchThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Checkout("i-do-not-exist")); + Assert.Throws(() => repo.Checkout("i-do-not-exist")); } } diff --git a/LibGit2Sharp.Tests/CommitFixture.cs b/LibGit2Sharp.Tests/CommitFixture.cs index 7ac93d1e5..43e9393f0 100644 --- a/LibGit2Sharp.Tests/CommitFixture.cs +++ b/LibGit2Sharp.Tests/CommitFixture.cs @@ -96,8 +96,8 @@ public void QueryingTheCommitHistoryWithUnknownShaOrInvalidEntryPointThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = Constants.UnknownSha }).Count()); - Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = "refs/heads/deadbeef" }).Count()); + Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = Constants.UnknownSha }).Count()); + Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = "refs/heads/deadbeef" }).Count()); Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = null }).Count()); } } @@ -110,8 +110,8 @@ public void QueryingTheCommitHistoryFromACorruptedReferenceThrows() { CreateCorruptedDeadBeefHead(repo.Info.Path); - Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = repo.Branches["deadbeef"] }).Count()); - Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = repo.Refs["refs/heads/deadbeef"] }).Count()); + Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = repo.Branches["deadbeef"] }).Count()); + Assert.Throws(() => repo.Commits.QueryBy(new Filter { Since = repo.Refs["refs/heads/deadbeef"] }).Count()); } } @@ -647,7 +647,7 @@ public void CanNotAmendAnEmptyRepository() using (Repository repo = Repository.Init(scd.DirectoryPath)) { - Assert.Throws(() => repo.Commit("I can not amend anything !:(", DummySignature, DummySignature, true)); + Assert.Throws(() => repo.Commit("I can not amend anything !:(", DummySignature, DummySignature, true)); } } diff --git a/LibGit2Sharp.Tests/ConfigurationFixture.cs b/LibGit2Sharp.Tests/ConfigurationFixture.cs index 7356edaff..6a33daf7a 100644 --- a/LibGit2Sharp.Tests/ConfigurationFixture.cs +++ b/LibGit2Sharp.Tests/ConfigurationFixture.cs @@ -220,7 +220,7 @@ public void SettingLocalConfigurationOutsideAReposThrows() { using (var config = new Configuration()) { - Assert.Throws(() => config.Set("unittests.intsetting", 3)); + Assert.Throws(() => config.Set("unittests.intsetting", 3)); } } diff --git a/LibGit2Sharp.Tests/IndexFixture.cs b/LibGit2Sharp.Tests/IndexFixture.cs index bd51d91eb..f3112b299 100644 --- a/LibGit2Sharp.Tests/IndexFixture.cs +++ b/LibGit2Sharp.Tests/IndexFixture.cs @@ -132,7 +132,6 @@ public void CanStageTheUpdationOfAStagedFile() [Theory] [InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)] - [InlineData("deleted_staged_file.txt", FileStatus.Removed)] public void StagingAnUnknownFileThrows(string relativePath, FileStatus status) { using (var repo = new Repository(StandardTestRepoPath)) @@ -140,6 +139,19 @@ public void StagingAnUnknownFileThrows(string relativePath, FileStatus status) Assert.Null(repo.Index[relativePath]); Assert.Equal(status, repo.Index.RetrieveStatus(relativePath)); + Assert.Throws(() => repo.Index.Stage(relativePath)); + } + } + + [Theory] + [InlineData("deleted_staged_file.txt", FileStatus.Removed)] + public void StagingARemovedFileThrows(string relativePath, FileStatus status) + { + using (var repo = new Repository(StandardTestRepoPath)) + { + Assert.Null(repo.Index[relativePath]); + Assert.Equal(repo.Index.RetrieveStatus(relativePath), status); + Assert.Throws(() => repo.Index.Stage(relativePath)); } } @@ -457,7 +469,7 @@ private static void InvalidMoveUseCases(string sourcePath, FileStatus sourceStat foreach (var destPath in destPaths) { string path = destPath; - Assert.Throws(() => repo.Index.Move(sourcePath, path)); + Assert.Throws(() => repo.Index.Move(sourcePath, path)); } } } @@ -493,7 +505,7 @@ public void RemovingAInvalidFileThrows(string filepath) { using (var repo = new Repository(StandardTestRepoPath)) { - Assert.Throws(() => repo.Index.Remove(filepath)); + Assert.Throws(() => repo.Index.Remove(filepath)); } } diff --git a/LibGit2Sharp.Tests/RepositoryFixture.cs b/LibGit2Sharp.Tests/RepositoryFixture.cs index e3fed6ceb..2d0c43903 100644 --- a/LibGit2Sharp.Tests/RepositoryFixture.cs +++ b/LibGit2Sharp.Tests/RepositoryFixture.cs @@ -34,7 +34,7 @@ public void AccessingTheIndexInABareRepoThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Index); + Assert.Throws(() => repo.Index); } } diff --git a/LibGit2Sharp.Tests/ResetFixture.cs b/LibGit2Sharp.Tests/ResetFixture.cs index dada45bdf..f6c961bd9 100644 --- a/LibGit2Sharp.Tests/ResetFixture.cs +++ b/LibGit2Sharp.Tests/ResetFixture.cs @@ -17,7 +17,7 @@ public void ResetANewlyInitializedRepositoryThrows(bool isBare) using (var repo = Repository.Init(scd.DirectoryPath, isBare)) { - Assert.Throws(() => repo.Reset(ResetOptions.Soft, repo.Head.CanonicalName)); + Assert.Throws(() => repo.Reset(ResetOptions.Soft, repo.Head.CanonicalName)); } } @@ -54,7 +54,7 @@ public void ResettingWithBadParamsThrows() { Assert.Throws(() => repo.Reset(ResetOptions.Soft, null)); Assert.Throws(() => repo.Reset(ResetOptions.Soft, "")); - Assert.Throws(() => repo.Reset(ResetOptions.Soft, Constants.UnknownSha)); + Assert.Throws(() => repo.Reset(ResetOptions.Soft, Constants.UnknownSha)); } } @@ -149,7 +149,7 @@ public void MixedResetInABareRepositoryThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Reset(ResetOptions.Mixed, repo.Head.Tip.Sha)); + Assert.Throws(() => repo.Reset(ResetOptions.Mixed, repo.Head.Tip.Sha)); } } } diff --git a/LibGit2Sharp.Tests/TagFixture.cs b/LibGit2Sharp.Tests/TagFixture.cs index 96d013734..ccb7dbf34 100644 --- a/LibGit2Sharp.Tests/TagFixture.cs +++ b/LibGit2Sharp.Tests/TagFixture.cs @@ -175,7 +175,7 @@ public void CreatingATagInAEmptyRepositoryThrows() using (var repo = Repository.Init(scd.DirectoryPath)) { - Assert.Throws(() => repo.ApplyTag("mynotag")); + Assert.Throws(() => repo.ApplyTag("mynotag")); } } @@ -187,7 +187,7 @@ public void CreatingATagForHeadInAEmptyRepositoryThrows() using (var repo = Repository.Init(scd.DirectoryPath)) { - Assert.Throws(() => repo.ApplyTag("mytaghead", "HEAD")); + Assert.Throws(() => repo.ApplyTag("mytaghead", "HEAD")); } } @@ -197,7 +197,7 @@ public void CreatingATagForAnUnknowReferenceThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.ApplyTag("mytagnorev", "aaaaaaaaaaa")); + Assert.Throws(() => repo.ApplyTag("mytagnorev", "aaaaaaaaaaa")); } } @@ -206,7 +206,7 @@ public void CreatingATagForANonCanonicalReferenceThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.ApplyTag("noncanonicaltarget", "br2")); + Assert.Throws(() => repo.ApplyTag("noncanonicaltarget", "br2")); } } @@ -216,7 +216,7 @@ public void CreatingATagForAnUnknowObjectIdThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.ApplyTag("mytagnorev", Constants.UnknownSha)); + Assert.Throws(() => repo.ApplyTag("mytagnorev", Constants.UnknownSha)); } } @@ -408,7 +408,7 @@ public void CreateTagWithNotExistingTargetThrows() { using (var repo = new Repository(BareTestRepoPath)) { - Assert.Throws(() => repo.Tags.Create("test_tag", Constants.UnknownSha, signatureTim, "message")); + Assert.Throws(() => repo.Tags.Create("test_tag", Constants.UnknownSha, signatureTim, "message")); } } diff --git a/LibGit2Sharp/BranchCollection.cs b/LibGit2Sharp/BranchCollection.cs index 381ee5c15..c69be0a2e 100644 --- a/LibGit2Sharp/BranchCollection.cs +++ b/LibGit2Sharp/BranchCollection.cs @@ -121,7 +121,7 @@ public void Delete(string name, bool isRemote = false) int res = NativeMethods.git_branch_delete(repo.Handle, name, isRemote ? GitBranchType.GIT_BRANCH_REMOTE : GitBranchType.GIT_BRANCH_LOCAL); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return; } diff --git a/LibGit2Sharp/CommitCollection.cs b/LibGit2Sharp/CommitCollection.cs index d58a9f408..4799e4b61 100644 --- a/LibGit2Sharp/CommitCollection.cs +++ b/LibGit2Sharp/CommitCollection.cs @@ -141,7 +141,7 @@ public Commit FindCommonAncestor(Commit first, Commit second) GitOid ret; int result = NativeMethods.git_merge_base(out ret, repo.Handle, osw1.ObjectPtr, osw2.ObjectPtr); - if (result == (int)GitErrorCode.GIT_ENOTFOUND) + if (result == (int)GitErrorCode.NotFound) { return null; } @@ -207,7 +207,7 @@ public Commit Create(string message, Signature author, Signature committer, bool { if (amendPreviousCommit && repo.Info.IsEmpty) { - throw new LibGit2Exception("Can not amend anything. The Head doesn't point at any commit."); + throw new LibGit2SharpException("Can not amend anything. The Head doesn't point at any commit."); } GitOid treeOid; @@ -270,7 +270,7 @@ public bool MoveNext() GitOid oid; int res = NativeMethods.git_revwalk_next(out oid, handle); - if (res == (int)GitErrorCode.GIT_EREVWALKOVER) + if (res == (int)GitErrorCode.RevWalkOver) { return false; } @@ -404,7 +404,7 @@ private IEnumerable RetrieveCommitOids(object identifier) yield break; } - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Unexpected kind of identifier '{0}'.", identifier)); + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected kind of identifier '{0}'.", identifier)); } } } diff --git a/LibGit2Sharp/Configuration.cs b/LibGit2Sharp/Configuration.cs index fa2d9781c..22d3e57ef 100644 --- a/LibGit2Sharp/Configuration.cs +++ b/LibGit2Sharp/Configuration.cs @@ -109,7 +109,7 @@ private static string ConvertPath(Func pathRetriever) int result = pathRetriever(buffer, NativeMethods.GIT_PATH_MAX); - if (result == (int)GitErrorCode.GIT_ENOTFOUND) + if (result == (int)GitErrorCode.NotFound) { return null; } @@ -149,7 +149,7 @@ public void Delete(string key, ConfigurationLevel level = ConfigurationLevel.Loc int res = NativeMethods.git_config_delete(h, key); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return; } @@ -201,7 +201,7 @@ public T Get(string key, T defaultValue) ConfigurationSafeHandle handle = (LocalHandle ?? globalHandle) ?? systemHandle; if (handle == null) { - throw new LibGit2Exception("Could not find a local, global or system level configuration."); + throw new LibGit2SharpException("Could not find a local, global or system level configuration."); } return (T)configurationTypedRetriever[typeof(T)](key, defaultValue, handle); @@ -339,17 +339,17 @@ private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel l { if (level == ConfigurationLevel.Local && !HasLocalConfig) { - throw new LibGit2Exception("No local configuration file has been found. You must use ConfigurationLevel.Global when accessing configuration outside of repository."); + throw new LibGit2SharpException("No local configuration file has been found. You must use ConfigurationLevel.Global when accessing configuration outside of repository."); } if (level == ConfigurationLevel.Global && !HasGlobalConfig) { - throw new LibGit2Exception("No global configuration file has been found."); + throw new LibGit2SharpException("No global configuration file has been found."); } if (level == ConfigurationLevel.System && !HasSystemConfig) { - throw new LibGit2Exception("No system configuration file has been found."); + throw new LibGit2SharpException("No system configuration file has been found."); } ConfigurationSafeHandle h; @@ -382,7 +382,7 @@ private static Func GetRetrieve { T value; var res = getter(out value, handle, key); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return defaultValue; } diff --git a/LibGit2Sharp/Core/Ensure.cs b/LibGit2Sharp/Core/Ensure.cs index 91a759c1d..c8c25255b 100644 --- a/LibGit2Sharp/Core/Ensure.cs +++ b/LibGit2Sharp/Core/Ensure.cs @@ -10,8 +10,6 @@ namespace LibGit2Sharp.Core [DebuggerStepThrough] internal static class Ensure { - private static readonly Utf8Marshaler marshaler = (Utf8Marshaler)Utf8Marshaler.GetInstance(string.Empty); - /// /// Checks an argument to ensure it isn't null. /// @@ -54,36 +52,17 @@ public static void ArgumentNotNullOrEmptyString(string argumentValue, string arg /// True when positive values are allowed as well. public static void Success(int result, bool allowPositiveResult = false) { - if (result == (int)GitErrorCode.GIT_OK) + if (result == (int)GitErrorCode.Ok) { return; } - if (allowPositiveResult && result > (int)GitErrorCode.GIT_OK) + if (allowPositiveResult && result > (int)GitErrorCode.Ok) { return; } - string errorMessage; - GitError error = NativeMethods.giterr_last().MarshalAsGitError(); - - - if (error == null) - { - error = new GitError { Klass = -1, Message = IntPtr.Zero }; - errorMessage = "No error message has been provided by the native library"; - } - else - { - errorMessage = (string)marshaler.MarshalNativeToManaged(error.Message); - } - - throw new LibGit2Exception( - String.Format(CultureInfo.InvariantCulture, "An error was raised by libgit2. Class = {0} ({1}).{2}{3}", - Enum.GetName(typeof(GitErrorType), error.Klass), - result, - Environment.NewLine, - errorMessage)); + throw new LibGit2Exception(NativeMethods.giterr_last()); } /// @@ -109,7 +88,7 @@ public static void GitObjectIsNotNull(GitObject gitObject, string identifier) return; } - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "No valid git object identified by '{0}' exists in the repository.", identifier)); } diff --git a/LibGit2Sharp/Core/GitError.cs b/LibGit2Sharp/Core/GitError.cs index 5d72dce65..f37afafe1 100644 --- a/LibGit2Sharp/Core/GitError.cs +++ b/LibGit2Sharp/Core/GitError.cs @@ -1,31 +1,11 @@ -using System; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitError + public class GitError { - public IntPtr Message; - public int Klass; - } - - internal enum GitErrorType - { - GITERR_NOMEMORY, - GITERR_OS, - GITERR_INVALID, - GITERR_REFERENCE, - GITERR_ZLIB, - GITERR_REPOSITORY, - GITERR_CONFIG, - GITERR_REGEX, - GITERR_ODB, - GITERR_INDEX, - GITERR_OBJECT, - GITERR_NET, - GITERR_TAG, - GITERR_TREE, - GITERR_INDEXER, + public string Message; + public GitErrorClass Class; } } diff --git a/LibGit2Sharp/Core/GitErrorClass.cs b/LibGit2Sharp/Core/GitErrorClass.cs new file mode 100644 index 000000000..9485a7e29 --- /dev/null +++ b/LibGit2Sharp/Core/GitErrorClass.cs @@ -0,0 +1,21 @@ +namespace LibGit2Sharp.Core +{ + public enum GitErrorClass + { + NoMemory, + Os, + Invalid, + Reference, + Zlib, + Repository, + Config, + Regex, + Odb, + Index, + Object, + Net, + Tag, + Tree, + Indexer + } +} diff --git a/LibGit2Sharp/Core/GitErrorCode.cs b/LibGit2Sharp/Core/GitErrorCode.cs index 8ef3baae0..ae49fc360 100644 --- a/LibGit2Sharp/Core/GitErrorCode.cs +++ b/LibGit2Sharp/Core/GitErrorCode.cs @@ -2,13 +2,37 @@ { internal enum GitErrorCode { - GIT_OK = 0, - GIT_ERROR = -1, - GIT_ENOTFOUND = -3, - GIT_EEXISTS = -4, - GIT_EAMBIGUOUS = -5, - GIT_EBUFS = -6, - GIT_EPASSTHROUGH = -30, - GIT_EREVWALKOVER = -31, + Ok = 0, + Error = -1, + + /// + /// Input does not exist in the scope searched. + /// + NotFound = -3, + + /// + /// A reference with this name already exists. + /// + Exists = -4, + + /// + /// The given short oid is ambiguous. + /// + Ambiguous = -5, + + /// + /// Bufs + /// + Bufs = -6, + + /// + /// Skip and passthrough the given ODB backend. + /// + PassThrough = -30, + + /// + /// The revision walker is empty; there are no more commits left to iterate. + /// + RevWalkOver = -31 } } diff --git a/LibGit2Sharp/Core/GitErrorMarshaler.cs b/LibGit2Sharp/Core/GitErrorMarshaler.cs new file mode 100644 index 000000000..df121691a --- /dev/null +++ b/LibGit2Sharp/Core/GitErrorMarshaler.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.InteropServices; + +namespace LibGit2Sharp.Core +{ + internal class GitErrorMarshaler : ICustomMarshaler + { + static readonly GitErrorMarshaler staticInstance = new GitErrorMarshaler(); + + public void CleanUpManagedData(object managedObj) + { + } + + public void CleanUpNativeData(IntPtr pNativeData) + { + Marshal.FreeHGlobal(pNativeData); + } + + public int GetNativeDataSize() + { + return -1; + } + + public IntPtr MarshalManagedToNative(object managedObj) + { + throw new NotImplementedException(); + } + + public object MarshalNativeToManaged(IntPtr pNativeData) + { + return NativeToGitError(pNativeData); + } + + protected GitError NativeToGitError(IntPtr pNativeData) + { + return (GitError)Marshal.PtrToStructure(pNativeData, typeof(GitError)); + } + + public static ICustomMarshaler GetInstance(string cookie) + { + return staticInstance; + } + } +} diff --git a/LibGit2Sharp/Core/GitObjectExtensions.cs b/LibGit2Sharp/Core/GitObjectExtensions.cs index 59e12500c..2af3fd6ac 100644 --- a/LibGit2Sharp/Core/GitObjectExtensions.cs +++ b/LibGit2Sharp/Core/GitObjectExtensions.cs @@ -27,7 +27,7 @@ public static Commit DereferenceToCommit(this GitObject gitObject, string ident return null; } - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "The Git object pointed at by '{0}' can not be dereferenced to a commit.", identifier)); } diff --git a/LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs b/LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs deleted file mode 100644 index 9a222a482..000000000 --- a/LibGit2Sharp/Core/Handles/GitErrorSafeHandle.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Runtime.InteropServices; - -namespace LibGit2Sharp.Core.Handles -{ - internal class GitErrorSafeHandle : NotOwnedSafeHandleBase - { - public GitError MarshalAsGitError() - { - return (GitError)Marshal.PtrToStructure(handle, typeof(GitError)); - } - } -} diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index 164562e1d..c3762c3ea 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -65,7 +65,8 @@ public static bool RepositoryStateChecker(RepositorySafeHandle repositoryPtr, Fu } [DllImport(libgit2)] - public static extern GitErrorSafeHandle giterr_last(); + [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(GitErrorMarshaler))] + public static extern GitError giterr_last(); [DllImport(libgit2)] public static extern int git_blob_create_fromdisk( diff --git a/LibGit2Sharp/GitObject.cs b/LibGit2Sharp/GitObject.cs index 9418f3f05..47ffd05f4 100644 --- a/LibGit2Sharp/GitObject.cs +++ b/LibGit2Sharp/GitObject.cs @@ -59,7 +59,7 @@ internal static GitObject CreateFromPtr(GitObjectSafeHandle obj, ObjectId id, Re case GitObjectType.Blob: return Blob.BuildFromPtr(obj, id, repo); default: - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' for object '{1}'.", type, id)); + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' for object '{1}'.", type, id)); } } diff --git a/LibGit2Sharp/Index.cs b/LibGit2Sharp/Index.cs index 69d9fa169..1cc999775 100644 --- a/LibGit2Sharp/Index.cs +++ b/LibGit2Sharp/Index.cs @@ -63,7 +63,7 @@ public IndexEntry this[string path] int res = NativeMethods.git_index_find(handle, path); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return null; } @@ -142,7 +142,7 @@ public void Stage(IEnumerable paths) continue; } - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Can not stage '{0}'. The file does not exist.", kvp.Key)); + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Can not stage '{0}'. The file does not exist.", kvp.Key)); } foreach (KeyValuePair kvp in batch) @@ -254,7 +254,7 @@ public void Move(IEnumerable sourcePaths, IEnumerable destinatio FileStatus sourceStatus = keyValuePair.Key.Item2; if (sourceStatus.HasAny(new[] { FileStatus.Nonexistent, FileStatus.Removed, FileStatus.Untracked, FileStatus.Missing })) { - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Unable to move file '{0}'. Its current status is '{1}'.", sourcePath, Enum.GetName(typeof(FileStatus), sourceStatus))); + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unable to move file '{0}'. Its current status is '{1}'.", sourcePath, Enum.GetName(typeof(FileStatus), sourceStatus))); } FileStatus desStatus = keyValuePair.Value.Item2; @@ -263,7 +263,7 @@ public void Move(IEnumerable sourcePaths, IEnumerable destinatio continue; } - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Unable to overwrite file '{0}'. Its current status is '{1}'.", destPath, Enum.GetName(typeof(FileStatus), desStatus))); + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unable to overwrite file '{0}'. Its current status is '{1}'.", destPath, Enum.GetName(typeof(FileStatus), desStatus))); } string wd = repo.Info.WorkingDirectory; @@ -322,7 +322,7 @@ public void Remove(IEnumerable paths) continue; } - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Unable to remove file '{0}'. Its current status is '{1}'.", keyValuePair.Key, Enum.GetName(typeof(FileStatus), keyValuePair.Value))); + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unable to remove file '{0}'. Its current status is '{1}'.", keyValuePair.Key, Enum.GetName(typeof(FileStatus), keyValuePair.Value))); } string wd = repo.Info.WorkingDirectory; @@ -476,7 +476,7 @@ public FileStatus RetrieveStatus(string filePath) FileStatus status; int res = NativeMethods.git_status_file(out status, repo.Handle, relativePath); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return FileStatus.Nonexistent; } diff --git a/LibGit2Sharp/LibGit2Exception.cs b/LibGit2Sharp/LibGit2Exception.cs index 1419b799a..742f1b795 100644 --- a/LibGit2Sharp/LibGit2Exception.cs +++ b/LibGit2Sharp/LibGit2Exception.cs @@ -1,34 +1,39 @@ using System; +using LibGit2Sharp.Core; namespace LibGit2Sharp { /// - /// The exception that is thrown when an error occurs during application execution. + /// The exception that is thrown when an error occurs in libgit2. /// - public class LibGit2Exception : Exception + public class LibGit2Exception : LibGit2SharpException { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class with a specified error message. /// - public LibGit2Exception() + /// The libgit2 error + public LibGit2Exception(GitError gitError) + : base(gitError.Message) { + GitError = gitError; } /// - /// Initializes a new instance of the class with a specified error message. + /// The underlying libgit2 error /// - /// A message that describes the error. - public LibGit2Exception(string message) - : base(message) - { - } + public GitError GitError { get; set; } + } + /// + /// The exception that is thrown when an error occurs in libgit2sharp. + /// + public class LibGit2SharpException : Exception + { /// - /// 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. + /// Initializes a new instance of the class with a specified error message. /// - /// 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 LibGit2Exception(string message, Exception innerException) : base(message, innerException) + /// The error message + public LibGit2SharpException(string message) : base(message) { } } diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index b840ad90b..26dd4182c 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -74,9 +74,10 @@ + + - diff --git a/LibGit2Sharp/NoteCollection.cs b/LibGit2Sharp/NoteCollection.cs index 5759075b3..c6a845b78 100644 --- a/LibGit2Sharp/NoteCollection.cs +++ b/LibGit2Sharp/NoteCollection.cs @@ -137,7 +137,7 @@ private NoteSafeHandle BuildNoteSafeHandle(ObjectId id, string canonicalNamespac int res = NativeMethods.git_note_read(out noteHandle, repo.Handle, canonicalNamespace, ref oid); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return null; } @@ -229,7 +229,7 @@ public void Delete(ObjectId targetId, Signature author, Signature committer, str res = NativeMethods.git_note_remove(repo.Handle, canonicalNamespace, authorHandle, committerHandle, ref oid); } - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return; } diff --git a/LibGit2Sharp/ObjectDatabase.cs b/LibGit2Sharp/ObjectDatabase.cs index 898eb828f..3154d7c1b 100644 --- a/LibGit2Sharp/ObjectDatabase.cs +++ b/LibGit2Sharp/ObjectDatabase.cs @@ -33,7 +33,7 @@ public bool Contains(ObjectId objectId) { var oid = objectId.Oid; - return NativeMethods.git_odb_exists(handle, ref oid) != (int)GitErrorCode.GIT_OK; + return NativeMethods.git_odb_exists(handle, ref oid) != (int)GitErrorCode.Ok; } /// diff --git a/LibGit2Sharp/Reference.cs b/LibGit2Sharp/Reference.cs index 84c416010..9c5306247 100644 --- a/LibGit2Sharp/Reference.cs +++ b/LibGit2Sharp/Reference.cs @@ -52,7 +52,7 @@ internal static T BuildFromPtr(ReferenceSafeHandle handle, Repository repo) w break; default: - throw new LibGit2Exception(String.Format(CultureInfo.InvariantCulture, "Unable to build a new reference from a type '{0}'.", Enum.GetName(typeof(GitReferenceType), type))); + throw new LibGit2SharpException(String.Format(CultureInfo.InvariantCulture, "Unable to build a new reference from a type '{0}'.", Enum.GetName(typeof(GitReferenceType), type))); } return reference as T; @@ -63,7 +63,7 @@ private static ReferenceSafeHandle PeelToDirectReference(ReferenceSafeHandle han ReferenceSafeHandle resolvedHandle; int res = NativeMethods.git_reference_resolve(out resolvedHandle, handle); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return null; } diff --git a/LibGit2Sharp/ReferenceCollection.cs b/LibGit2Sharp/ReferenceCollection.cs index 5b5b8a5dd..8c4915f8e 100644 --- a/LibGit2Sharp/ReferenceCollection.cs +++ b/LibGit2Sharp/ReferenceCollection.cs @@ -118,7 +118,7 @@ private ObjectId Unabbreviate(ObjectId targetId) if (obj == null) { - Ensure.Success((int)GitErrorCode.GIT_ENOTFOUND); + Ensure.Success((int)GitErrorCode.NotFound); } return obj.Id; @@ -219,7 +219,7 @@ public Reference UpdateTarget(string name, string target) break; default: - throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Reference '{0}' has an unexpected type ('{1}').", name, Enum.GetName(typeof(GitReferenceType), type))); + throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Reference '{0}' has an unexpected type ('{1}').", name, Enum.GetName(typeof(GitReferenceType), type))); } Ensure.Success(res); @@ -233,7 +233,7 @@ private ReferenceSafeHandle RetrieveReferencePtr(string referenceName, bool shou ReferenceSafeHandle reference; int res = NativeMethods.git_reference_lookup(out reference, repo.Handle, referenceName); - if (!shouldThrowIfNotFound && res == (int)GitErrorCode.GIT_ENOTFOUND) + if (!shouldThrowIfNotFound && res == (int)GitErrorCode.NotFound) { return null; } diff --git a/LibGit2Sharp/RemoteCollection.cs b/LibGit2Sharp/RemoteCollection.cs index 61b8c72bd..e40ccd37b 100644 --- a/LibGit2Sharp/RemoteCollection.cs +++ b/LibGit2Sharp/RemoteCollection.cs @@ -34,7 +34,7 @@ internal RemoteSafeHandle LoadRemote(string name, bool throwsIfNotFound) int res = NativeMethods.git_remote_load(out handle, repository.Handle, name); - if (res == (int)GitErrorCode.GIT_ENOTFOUND && !throwsIfNotFound) + if (res == (int)GitErrorCode.NotFound && !throwsIfNotFound) { return null; } diff --git a/LibGit2Sharp/Repository.cs b/LibGit2Sharp/Repository.cs index e4ee702fe..0d9be941a 100644 --- a/LibGit2Sharp/Repository.cs +++ b/LibGit2Sharp/Repository.cs @@ -146,7 +146,7 @@ public Index Index { if (index == null) { - throw new LibGit2Exception("Index is not available in a bare repository."); + throw new LibGit2SharpException("Index is not available in a bare repository."); } return index; @@ -308,7 +308,7 @@ internal GitObject LookupInternal(ObjectId id, GitObjectType type, FilePath know res = NativeMethods.git_object_lookup(out obj, handle, ref oid, type); } - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return null; } @@ -400,7 +400,7 @@ public static string Discover(string startingPath) int result = NativeMethods.git_repository_discover(buffer, buffer.Length, startingPath, false, null); - if ((GitErrorCode)result == GitErrorCode.GIT_ENOTFOUND) + if ((GitErrorCode)result == GitErrorCode.NotFound) { return null; } @@ -457,7 +457,7 @@ public void Reset(ResetOptions resetOptions, string shaOrReferenceName) if (resetOptions.Has(ResetOptions.Mixed) && Info.IsBare) { - throw new LibGit2Exception("Mixed reset is not allowed in a bare repository"); + throw new LibGit2SharpException("Mixed reset is not allowed in a bare repository"); } var commit = LookupCommit(shaOrReferenceName); diff --git a/LibGit2Sharp/RepositoryExtensions.cs b/LibGit2Sharp/RepositoryExtensions.cs index 47a4aa16a..3e2f44b7c 100644 --- a/LibGit2Sharp/RepositoryExtensions.cs +++ b/LibGit2Sharp/RepositoryExtensions.cs @@ -169,7 +169,7 @@ private static Signature BuildSignatureFromGlobalConfiguration(Repository reposi if ((name == null) || (email == null)) { - throw new LibGit2Exception("Can not find Name and Email settings of the current user in Git configuration."); + throw new LibGit2SharpException("Can not find Name and Email settings of the current user in Git configuration."); } return new Signature(name, email, now); diff --git a/LibGit2Sharp/Tree.cs b/LibGit2Sharp/Tree.cs index 59b11527b..702d208d4 100644 --- a/LibGit2Sharp/Tree.cs +++ b/LibGit2Sharp/Tree.cs @@ -50,7 +50,7 @@ private TreeEntry RetrieveFromPath(FilePath relativePath) int res = NativeMethods.git_tree_get_subtree(out objectPtr, obj.ObjectPtr, relativePath); - if (res == (int)GitErrorCode.GIT_ENOTFOUND) + if (res == (int)GitErrorCode.NotFound) { return null; } From feed822a795b49e604f378b10efb1fc3ab12a530 Mon Sep 17 00:00:00 2001 From: Tim Clem Date: Fri, 1 Jun 2012 11:13:43 -0700 Subject: [PATCH 2/2] Remove BOM and cleanup .gitattributes There is no need to call out Lib and other directories specifically in here because we have .gitattributes files in those dirs. --- .gitattributes | 42 ++++++++---------------------------------- 1 file changed, 8 insertions(+), 34 deletions(-) diff --git a/.gitattributes b/.gitattributes index aceda01ba..7417c36d5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,36 +1,10 @@ -# Catch all for anything we forgot. Add rules if you get CRLF to LF warnings. +# Auto detect text files and perform LF normalization * text=auto -# Text files that should be normalized to LF in odb. -*.cs text diff=csharp -*.config text - -*.sln text -*.csproj text - -*.md text -*.sh text -*.ps1 text -*.cmd text -*.bat text -*.markdown text -*.msbuild text - -Lib/* binary -GitHub.Tests.Integration/Resources/* binary - - -# Binary files that should not be normalized or diffed -*.png binary -*.jpg binary -*.gif binary - -*.pfx binary -*.snk binary -*.dll binary -*.exe binary -*.lib binary -*.exp binary -*.pdb binary -*.sdf binary -*.7z binary +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union