diff --git a/CHANGES.md b/CHANGES.md index 22a41d5b2..4c71613e1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,16 @@ - Windows (x86/amd64): - Linux/Mac OS X: +## v0.22 + 1 + +### Additions + +### Changes + + - Obsolete the config paths in RepositoryOptions + +### Fixes + ## v0.22 - ([diff](https://github.com/libgit2/libgit2sharp/compare/v0.21.1...v0.22)) ### Additions 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/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.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 30c8b207f..ee49fd249 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); @@ -143,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); @@ -200,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()); } } @@ -331,12 +323,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 +344,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)); @@ -387,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); @@ -418,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/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] 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/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/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/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/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 dc82a5fc3..b9ac369e9 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,17 @@ 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 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,25 +126,26 @@ public void RemoteUpdaterSavesRefSpecsPermanently() public void CanAddAndRemoveRefSpecs() { string newRefSpec = "+refs/heads/test:refs/heads/other-test"; - var path = SandboxStandardTestRepo(); - using (var repo = InitIsolatedRepository(path)) - { - var remote = repo.Network.Remotes["origin"]; - remote = repo.Network.Remotes.Update(remote, + using (var repo = new Repository(path)) + using (var remote = repo.Network.Remotes["origin"]) + { + 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)); + } + } } } @@ -150,7 +153,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 +181,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(); @@ -190,5 +193,41 @@ 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) + { + using (var repo = new Repository(InitNewRepository())) + { + 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) + { + using (var repo = new Repository(InitNewRepository())) + { + 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.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/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.Tests/TestHelpers/BaseFixture.cs b/LibGit2Sharp.Tests/TestHelpers/BaseFixture.cs index c1fbefb7f..44aafabb4 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,41 @@ 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, programData = null; + BuildFakeRepositoryOptions(scd, out global, out xdg, out system, out programData); + + 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()); + + 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) { var oldTestRepos = new DirectoryInfo(Constants.TemporaryReposPath) @@ -207,14 +244,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); @@ -234,7 +263,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 @@ -293,42 +322,19 @@ protected static void AssertValueInConfigFile(string configFilePath, string rege Assert.True(r.Success, text); } - public RepositoryOptions BuildFakeConfigs(SelfCleaningDirectory scd, RepositoryOptions options = null) + private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out string global, out string xdg, out string system, out string programData) { - 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) - { - 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); + programData = Path.Combine(confs, "my-programdata-config"); + Directory.CreateDirectory(programData); } /// @@ -337,18 +343,14 @@ private static RepositoryOptions BuildFakeRepositoryOptions(SelfCleaningDirector /// 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) { @@ -360,8 +362,6 @@ protected string CreateConfigurationWithDummyUser(string name, string email) config.Set("user.email", email); } } - - return configFilePath; } /// diff --git a/LibGit2Sharp/BlameHunk.cs b/LibGit2Sharp/BlameHunk.cs index 7f05a0b30..553efb14e 100644 --- a/LibGit2Sharp/BlameHunk.cs +++ b/LibGit2Sharp/BlameHunk.cs @@ -19,31 +19,35 @@ public class BlameHunk : IEquatable x => x.InitialSignature, x => x.InitialCommit); - - internal 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.ConvertToInt(); + + LineCount = (int)rawHunk->lines_in_hunk.ToUInt32(); // Libgit2's line numbers are 1-based - FinalStartLineNumber = rawHunk.FinalStartLineNumber.ConvertToInt() - 1; - InitialStartLineNumber = rawHunk.OrigStartLineNumber.ConvertToInt() - 1; + FinalStartLineNumber = (int)rawHunk->final_start_line_number.ToUInt32() - 1; + InitialStartLineNumber = (int)rawHunk->orig_start_line_number.ToUInt32() - 1; // Signature objects need to have ownership of their native pointers - if (rawHunk.FinalSignature != IntPtr.Zero) + if (rawHunk->final_signature != null) { - FinalSignature = new Signature(Proxy.git_signature_dup(rawHunk.FinalSignature)); + FinalSignature = new Signature(rawHunk->final_signature); } - if (rawHunk.OrigSignature != IntPtr.Zero) + 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 ef647eb37..869daf527 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, RepositorySafeHandle 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 = new UIntPtr((uint)options.MinLine), - MaxLine = new UIntPtr((uint)options.MaxLine), + min_line = new UIntPtr((uint)options.MinLine), + max_line = new UIntPtr((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/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/BranchCollection.cs b/LibGit2Sharp/BranchCollection.cs index 803e28d00..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 (ReferenceSafeHandle 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 (ReferenceSafeHandle 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/CertificateSsh.cs b/LibGit2Sharp/CertificateSsh.cs index 763a9f0b4..3c66bd995 100644 --- a/LibGit2Sharp/CertificateSsh.cs +++ b/LibGit2Sharp/CertificateSsh.cs @@ -1,6 +1,6 @@ -using LibGit2Sharp.Core; -using System; +using System; using System.Runtime.InteropServices; +using LibGit2Sharp.Core; namespace LibGit2Sharp { @@ -39,20 +39,32 @@ 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++) + { + HashSHA1[i] = p[i]; + } + } } - internal IntPtr ToPointer() + internal unsafe IntPtr ToPointer() { GitCertificateSshType sshCertType = 0; if (HasMD5) @@ -64,13 +76,27 @@ internal IntPtr ToPointer() sshCertType |= GitCertificateSshType.SHA1; } - var gitCert = new GitCertificateSsh + var gitCert = new git_certificate_ssh() { cert_type = GitCertificateType.Hostkey, type = sshCertType, }; - HashMD5.CopyTo(gitCert.HashMD5, 0); - HashSHA1.CopyTo(gitCert.HashSHA1, 0); + + fixed (byte *p = &HashMD5[0]) + { + for (var i = 0; i < HashMD5.Length; i++) + { + gitCert.HashMD5[i] = p[i]; + } + } + + fixed (byte *p = &HashSHA1[0]) + { + for (var i = 0; i < HashSHA1.Length; i++) + { + gitCert.HashSHA1[i] = p[i]; + } + } var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(gitCert)); Marshal.StructureToPtr(gitCert, ptr, false); diff --git a/LibGit2Sharp/CertificateX509.cs b/LibGit2Sharp/CertificateX509.cs index 8c65cfa68..b48d3fc55 100644 --- a/LibGit2Sharp/CertificateX509.cs +++ b/LibGit2Sharp/CertificateX509.cs @@ -22,23 +22,23 @@ 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); } - internal IntPtr ToPointers(out IntPtr dataPtr) + internal unsafe IntPtr ToPointers(out IntPtr dataPtr) { var certData = Certificate.Export(X509ContentType.Cert); dataPtr = Marshal.AllocHGlobal(certData.Length); Marshal.Copy(certData, 0, dataPtr, certData.Length); - var gitCert = new GitCertificateX509() + var gitCert = new git_certificate_x509() { cert_type = GitCertificateType.X509, - data = dataPtr, + data = (byte*) dataPtr.ToPointer(), len = (UIntPtr)certData.LongLength, }; 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/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/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..3f9567745 100644 --- a/LibGit2Sharp/CommitLog.cs +++ b/LibGit2Sharp/CommitLog.cs @@ -105,34 +105,10 @@ 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; - private readonly RevWalkerSafeHandle handle; + private readonly RevWalkerHandle handle; private ObjectId currentOid; public CommitEnumerator(Repository repo, CommitFilter filter) @@ -191,7 +167,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/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..63065841a 100644 --- a/LibGit2Sharp/Configuration.cs +++ b/LibGit2Sharp/Configuration.cs @@ -19,8 +19,9 @@ public class Configuration : IDisposable, private readonly FilePath globalConfigPath; private readonly FilePath xdgConfigPath; private readonly FilePath systemConfigPath; + private readonly FilePath programDataConfigPath; - private ConfigurationSafeHandle configHandle; + private ConfigurationHandle configHandle; /// /// Needed for mocking purposes. @@ -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) @@ -195,43 +202,13 @@ 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. /// 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 +246,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 +256,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 +361,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 +392,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 +622,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 +653,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, BuildConfigEntry).ToList(); + 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 +677,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) }, @@ -732,13 +709,12 @@ private IEnumerable> BuildConfigEntries() return Proxy.git_config_foreach(configHandle, BuildConfigEntry); } - private static ConfigurationEntry BuildConfigEntry(IntPtr entryPtr) + internal 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); } /// @@ -779,7 +755,7 @@ internal Signature BuildSignatureOrThrow(DateTimeOffset now) return signature; } - private ConfigurationSafeHandle Snapshot() + private ConfigurationHandle Snapshot() { return Proxy.git_config_snapshot(configHandle); } 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, } } 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/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/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/Core/GitBlame.cs b/LibGit2Sharp/Core/GitBlame.cs index b14632c40..df99f44b7 100644 --- a/LibGit2Sharp/Core/GitBlame.cs +++ b/LibGit2Sharp/Core/GitBlame.cs @@ -41,32 +41,33 @@ 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 UIntPtr MinLine; - public UIntPtr MaxLine; + + public UInt16 min_match_characters; + public git_oid newest_commit; + public git_oid oldest_commit; + public UIntPtr min_line; + public UIntPtr max_line; } [StructLayout(LayoutKind.Sequential)] - internal class GitBlameHunk + internal unsafe struct git_blame_hunk { - public UIntPtr LinesInHunk; - - public GitOid FinalCommitId; - public UIntPtr FinalStartLineNumber; - public IntPtr FinalSignature; + public UIntPtr lines_in_hunk; - public GitOid OrigCommitId; - public IntPtr OrigPath; - public UIntPtr OrigStartLineNumber; - public IntPtr OrigSignature; + public git_oid final_commit_id; + public UIntPtr final_start_line_number; + public git_signature* final_signature; + + public git_oid orig_commit_id; + public char* orig_path; + public UIntPtr 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/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/GitCredential.cs b/LibGit2Sharp/Core/GitCredential.cs index b3fefcaf1..f3c6605fd 100644 --- a/LibGit2Sharp/Core/GitCredential.cs +++ b/LibGit2Sharp/Core/GitCredential.cs @@ -4,7 +4,7 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitCredential + internal struct GitCredential { public GitCredentialType credtype; public IntPtr free; diff --git a/LibGit2Sharp/Core/GitCredentialUserpass.cs b/LibGit2Sharp/Core/GitCredentialUserpass.cs index 5d807b12e..ab6cf6c7a 100644 --- a/LibGit2Sharp/Core/GitCredentialUserpass.cs +++ b/LibGit2Sharp/Core/GitCredentialUserpass.cs @@ -4,11 +4,11 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitCredentialUserpass + internal unsafe struct GitCredentialUserpass { public GitCredential parent; - public IntPtr username; - public IntPtr password; + public char* username; + public char* password; } } diff --git a/LibGit2Sharp/Core/GitDiff.cs b/LibGit2Sharp/Core/GitDiff.cs index 8236a5b85..294bbeebe 100644 --- a/LibGit2Sharp/Core/GitDiff.cs +++ b/LibGit2Sharp/Core/GitDiff.cs @@ -242,24 +242,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/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/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/GitIndexEntry.cs b/LibGit2Sharp/Core/GitIndexEntry.cs index 11bee09ea..ac0c141ed 100644 --- a/LibGit2Sharp/Core/GitIndexEntry.cs +++ b/LibGit2Sharp/Core/GitIndexEntry.cs @@ -4,21 +4,28 @@ namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] - internal class GitIndexEntry + internal unsafe struct git_index_mtime + { + public int seconds; + public uint nanoseconds; + } + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct git_index_entry { 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 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 GitOid Id; - public ushort Flags; - public ushort ExtendedFlags; - public IntPtr Path; + public git_oid id; + public ushort flags; + public ushort extended_flags; + public char* path; } } 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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/Libgit2Object.cs b/LibGit2Sharp/Core/Handles/Libgit2Object.cs new file mode 100644 index 000000000..cbb431a98 --- /dev/null +++ b/LibGit2Sharp/Core/Handles/Libgit2Object.cs @@ -0,0 +1,181 @@ +// 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 + { + get + { + return ptr; + } + } + + bool owned; + bool disposed; + + 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) + { + } + + ~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 LEAKS_IDENTIFYING + bool leaked = !disposing && ptr != null; + + if (leaked) + { + LeaksContainer.Add(GetType().Name); + } +#endif + + if (!disposed) + { + if (owned) + { + Free(); + } + + ptr = null; + } + + 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() + { + Dispose(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/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/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 new file mode 100644 index 000000000..f904b75b9 --- /dev/null +++ b/LibGit2Sharp/Core/Handles/Objects.cs @@ -0,0 +1,559 @@ + +using System; + +namespace LibGit2Sharp.Core.Handles +{ + + internal unsafe class TreeEntryHandle : Libgit2Object + { + internal TreeEntryHandle(git_tree_entry *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal TreeEntryHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_tree_entry_free((git_tree_entry*) ptr); + } + + public static implicit operator git_tree_entry*(TreeEntryHandle handle) + { + return (git_tree_entry*) handle.Handle; + } + } + + internal unsafe class ReferenceHandle : Libgit2Object + { + internal ReferenceHandle(git_reference *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal ReferenceHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_reference_free((git_reference*) ptr); + } + + public static implicit operator git_reference*(ReferenceHandle handle) + { + return (git_reference*) handle.Handle; + } + } + + internal unsafe class RepositoryHandle : Libgit2Object + { + internal RepositoryHandle(git_repository *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal RepositoryHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_repository_free((git_repository*) ptr); + } + + public static implicit operator git_repository*(RepositoryHandle handle) + { + return (git_repository*) handle.Handle; + } + } + + internal unsafe class SignatureHandle : Libgit2Object + { + internal SignatureHandle(git_signature *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal SignatureHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_signature_free((git_signature*) ptr); + } + + public static implicit operator git_signature*(SignatureHandle handle) + { + return (git_signature*) handle.Handle; + } + } + + internal unsafe class StatusListHandle : Libgit2Object + { + internal StatusListHandle(git_status_list *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal StatusListHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_status_list_free((git_status_list*) ptr); + } + + public static implicit operator git_status_list*(StatusListHandle handle) + { + return (git_status_list*) handle.Handle; + } + } + + internal unsafe class BlameHandle : Libgit2Object + { + internal BlameHandle(git_blame *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal BlameHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_blame_free((git_blame*) ptr); + } + + public static implicit operator git_blame*(BlameHandle handle) + { + return (git_blame*) handle.Handle; + } + } + + internal unsafe class DiffHandle : Libgit2Object + { + internal DiffHandle(git_diff *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal DiffHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_diff_free((git_diff*) ptr); + } + + public static implicit operator git_diff*(DiffHandle handle) + { + return (git_diff*) handle.Handle; + } + } + + internal unsafe class PatchHandle : Libgit2Object + { + internal PatchHandle(git_patch *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal PatchHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_patch_free((git_patch*) ptr); + } + + public static implicit operator git_patch*(PatchHandle handle) + { + return (git_patch*) handle.Handle; + } + } + + internal unsafe class ConfigurationHandle : Libgit2Object + { + internal ConfigurationHandle(git_config *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal ConfigurationHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_config_free((git_config*) ptr); + } + + public static implicit operator git_config*(ConfigurationHandle handle) + { + return (git_config*) handle.Handle; + } + } + + internal unsafe class ConflictIteratorHandle : Libgit2Object + { + internal ConflictIteratorHandle(git_index_conflict_iterator *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal ConflictIteratorHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_index_conflict_iterator_free((git_index_conflict_iterator*) ptr); + } + + public static implicit operator git_index_conflict_iterator*(ConflictIteratorHandle handle) + { + return (git_index_conflict_iterator*) handle.Handle; + } + } + + internal unsafe class IndexHandle : Libgit2Object + { + internal IndexHandle(git_index *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal IndexHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_index_free((git_index*) ptr); + } + + public static implicit operator git_index*(IndexHandle handle) + { + return (git_index*) handle.Handle; + } + } + + internal unsafe class ReflogHandle : Libgit2Object + { + internal ReflogHandle(git_reflog *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal ReflogHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_reflog_free((git_reflog*) ptr); + } + + public static implicit operator git_reflog*(ReflogHandle handle) + { + return (git_reflog*) handle.Handle; + } + } + + internal unsafe class TreeBuilderHandle : Libgit2Object + { + internal TreeBuilderHandle(git_treebuilder *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal TreeBuilderHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_treebuilder_free((git_treebuilder*) ptr); + } + + public static implicit operator git_treebuilder*(TreeBuilderHandle handle) + { + return (git_treebuilder*) handle.Handle; + } + } + + internal unsafe class PackBuilderHandle : Libgit2Object + { + internal PackBuilderHandle(git_packbuilder *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal PackBuilderHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_packbuilder_free((git_packbuilder*) ptr); + } + + public static implicit operator git_packbuilder*(PackBuilderHandle handle) + { + return (git_packbuilder*) handle.Handle; + } + } + + internal unsafe class NoteHandle : Libgit2Object + { + internal NoteHandle(git_note *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal NoteHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_note_free((git_note*) ptr); + } + + public static implicit operator git_note*(NoteHandle handle) + { + return (git_note*) handle.Handle; + } + } + + internal unsafe class DescribeResultHandle : Libgit2Object + { + internal DescribeResultHandle(git_describe_result *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal DescribeResultHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_describe_result_free((git_describe_result*) ptr); + } + + public static implicit operator git_describe_result*(DescribeResultHandle handle) + { + return (git_describe_result*) handle.Handle; + } + } + + internal unsafe class SubmoduleHandle : Libgit2Object + { + internal SubmoduleHandle(git_submodule *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal SubmoduleHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_submodule_free((git_submodule*) ptr); + } + + public static implicit operator git_submodule*(SubmoduleHandle handle) + { + return (git_submodule*) handle.Handle; + } + } + + internal unsafe class AnnotatedCommitHandle : Libgit2Object + { + internal AnnotatedCommitHandle(git_annotated_commit *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal AnnotatedCommitHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_annotated_commit_free((git_annotated_commit*) ptr); + } + + public static implicit operator git_annotated_commit*(AnnotatedCommitHandle handle) + { + return (git_annotated_commit*) handle.Handle; + } + } + + internal unsafe class ObjectDatabaseHandle : Libgit2Object + { + internal ObjectDatabaseHandle(git_odb *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal ObjectDatabaseHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_odb_free((git_odb*) ptr); + } + + public static implicit operator git_odb*(ObjectDatabaseHandle handle) + { + return (git_odb*) handle.Handle; + } + } + + internal unsafe class RevWalkerHandle : Libgit2Object + { + internal RevWalkerHandle(git_revwalk *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal RevWalkerHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_revwalk_free((git_revwalk*) ptr); + } + + public static implicit operator git_revwalk*(RevWalkerHandle handle) + { + return (git_revwalk*) handle.Handle; + } + } + + internal unsafe class RemoteHandle : Libgit2Object + { + internal RemoteHandle(git_remote *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal RemoteHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_remote_free((git_remote*) ptr); + } + + public static implicit operator git_remote*(RemoteHandle handle) + { + return (git_remote*) handle.Handle; + } + } + + internal unsafe class ObjectHandle : Libgit2Object + { + internal ObjectHandle(git_object *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal ObjectHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_object_free((git_object*) ptr); + } + + public static implicit operator git_object*(ObjectHandle handle) + { + return (git_object*) handle.Handle; + } + } + + internal unsafe class RebaseHandle : Libgit2Object + { + internal RebaseHandle(git_rebase *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal RebaseHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_rebase_free((git_rebase*) ptr); + } + + public static implicit operator git_rebase*(RebaseHandle handle) + { + return (git_rebase*) handle.Handle; + } + } + + internal unsafe class OdbStreamHandle : Libgit2Object + { + internal OdbStreamHandle(git_odb_stream *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal OdbStreamHandle(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.git_odb_stream_free((git_odb_stream*) ptr); + } + + public static implicit operator git_odb_stream*(OdbStreamHandle handle) + { + return (git_odb_stream*) handle.Handle; + } + } + +} diff --git a/LibGit2Sharp/Core/Handles/Objects.tt b/LibGit2Sharp/Core/Handles/Objects.tt new file mode 100644 index 000000000..3ecfe811e --- /dev/null +++ b/LibGit2Sharp/Core/Handles/Objects.tt @@ -0,0 +1,97 @@ +<#@ 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.Handles +{ + +<# +var cNames = new[] { + "git_tree_entry", + "git_reference", + "git_repository", + "git_signature", + "git_status_list", + "git_blame", + "git_diff", + "git_patch", + "git_config", + "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[] { + "TreeEntryHandle", + "ReferenceHandle", + "RepositoryHandle", + "SignatureHandle", + "StatusListHandle", + "BlameHandle", + "DiffHandle", + "PatchHandle", + "ConfigurationHandle", + "ConflictIteratorHandle", + "IndexHandle", + "ReflogHandle", + "TreeBuilderHandle", + "PackBuilderHandle", + "NoteHandle", + "DescribeResultHandle", + "SubmoduleHandle", + "AnnotatedCommitHandle", + "ObjectDatabaseHandle", + "RevWalkerHandle", + "RemoteHandle", + "ObjectHandle", + "RebaseHandle", + "OdbStreamHandle", +}; + +for (var i = 0; i < cNames.Length; i++) +{ +#> + internal unsafe class <#= csNames[i] #> : Libgit2Object + { + internal <#= csNames[i] #>(<#= cNames[i] #> *ptr, bool owned) + : base((void *) ptr, owned) + { + } + + internal <#= csNames[i] #>(IntPtr ptr, bool owned) + : base(ptr, owned) + { + } + + public override void Free() + { + NativeMethods.<#= cNames[i] #>_free((<#= cNames[i] #>*) ptr); + } + + public static implicit operator <#= cNames[i] #>*(<#= csNames[i] #> handle) + { + return (<#= cNames[i] #>*) handle.Handle; + } + } + +<# +} +#> +} 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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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 8978abda4..326e8997e 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; /// @@ -79,7 +82,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( @@ -90,32 +93,32 @@ 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 int git_blame_file( - out BlameSafeHandle blame, - RepositorySafeHandle repo, + internal static extern unsafe int git_blame_file( + 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 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,37 +127,37 @@ 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); [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 int git_branch_create_from_annotated( - out ReferenceSafeHandle ref_out, - RepositorySafeHandle repo, + 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)] - 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, @@ -166,89 +169,88 @@ internal static extern void git_branch_iterator_free( IntPtr iterator); [DllImport(libgit2)] - internal static extern int git_branch_iterator_new( - out BranchIteratorSafeHandle iter_out, - RepositorySafeHandle repo, + internal static extern int git_branch_iterator_new( + out IntPtr iter_out, + IntPtr repo, 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); + 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( - out RebaseSafeHandle rebase, - RepositorySafeHandle repo, - GitAnnotatedCommitHandle branch, - GitAnnotatedCommitHandle upstream, - GitAnnotatedCommitHandle onto, + internal static extern unsafe int git_rebase_init( + out git_rebase* rebase, + git_repository* repo, + git_annotated_commit* branch, + git_annotated_commit* upstream, + git_annotated_commit* onto, GitRebaseOptions options); [DllImport(libgit2)] - internal static extern int git_rebase_open( - out RebaseSafeHandle rebase, - RepositorySafeHandle repo, + internal static extern unsafe int git_rebase_open( + 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 IntPtr git_rebase_operation_byindex( - RebaseSafeHandle rebase, + internal static extern unsafe git_rebase_operation* git_rebase_operation_byindex( + git_rebase* rebase, UIntPtr index); [DllImport(libgit2)] - internal static extern int git_rebase_next( - out IntPtr operation, - RebaseSafeHandle rebase); + internal static extern unsafe int git_rebase_next( + out git_rebase_operation* operation, + git_rebase* 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_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 int git_rebase_finish( - RebaseSafeHandle repo, - SignatureSafeHandle signature); + internal static extern unsafe int git_rebase_finish( + 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 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,46 +259,46 @@ 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, - GitObjectSafeHandle treeish, + internal static extern unsafe int git_checkout_tree( + git_repository* repo, + git_object* treeish, ref GitCheckoutOpts opts); [DllImport(libgit2)] - internal static extern int git_checkout_index( - RepositorySafeHandle repo, - GitObjectSafeHandle treeish, + internal static extern unsafe int git_checkout_index( + git_repository* repo, + git_object* 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); [DllImport(libgit2)] - internal static extern IntPtr git_commit_author(GitObjectSafeHandle commit); + internal static extern unsafe git_signature* git_commit_author(git_object* commit); [DllImport(libgit2)] - internal static extern IntPtr git_commit_committer(GitObjectSafeHandle commit); + internal static extern unsafe git_signature* git_commit_committer(git_object* 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, + 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, @@ -305,33 +307,33 @@ internal static extern 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 OidSafeHandle 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 OidSafeHandle git_commit_tree_id(GitObjectSafeHandle commit); + internal static extern unsafe git_oid* git_commit_tree_id(git_object* 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,31 +347,34 @@ 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 int git_config_find_programdata(GitBuf programdata_config_path); [DllImport(libgit2)] - internal static extern void git_config_entry_free(IntPtr entry); + internal static extern unsafe void git_config_free(git_config *cfg); [DllImport(libgit2)] - internal static extern int git_config_get_entry( - out GitConfigEntryHandle entry, - ConfigurationSafeHandle cfg, + internal static extern unsafe void git_config_entry_free(GitConfigEntry* entry); + + [DllImport(libgit2)] + internal static extern unsafe int git_config_get_entry( + out GitConfigEntry* entry, + 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 +393,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 +421,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 @@ -461,86 +466,86 @@ internal static extern int git_cred_userpass_plaintext_new( [DllImport(libgit2)] internal static extern void git_cred_free(IntPtr cred); - + [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 void git_diff_free(IntPtr diff); + internal static extern unsafe void git_diff_free(git_diff* diff); [DllImport(libgit2)] - internal static extern int git_diff_tree_to_tree( - out DiffSafeHandle diff, - RepositorySafeHandle repo, - GitObjectSafeHandle oldTree, - GitObjectSafeHandle newTree, + internal static extern unsafe int git_diff_tree_to_tree( + out git_diff* diff, + git_repository* repo, + git_object* oldTree, + git_object* newTree, GitDiffOptions options); [DllImport(libgit2)] - internal static extern int git_diff_tree_to_index( - out DiffSafeHandle diff, - RepositorySafeHandle repo, - GitObjectSafeHandle oldTree, - IndexSafeHandle index, + internal static extern unsafe int git_diff_tree_to_index( + out git_diff* diff, + git_repository* repo, + git_object* oldTree, + git_index* 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 int git_diff_index_to_workdir( - out DiffSafeHandle diff, - RepositorySafeHandle repo, - IndexSafeHandle index, + internal static extern unsafe int git_diff_index_to_workdir( + out git_diff* diff, + git_repository* repo, + git_index* index, GitDiffOptions options); [DllImport(libgit2)] - internal static extern int git_diff_tree_to_workdir( - out DiffSafeHandle diff, - RepositorySafeHandle repo, - GitObjectSafeHandle oldTree, + internal static extern unsafe int git_diff_tree_to_workdir( + out git_diff* diff, + git_repository* repo, + git_object* 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, - [In] GitDiffBinary binary, - IntPtr payload); + internal unsafe delegate int git_diff_binary_cb( + [In] git_diff_delta* delta, + [In] GitDiffBinary binary, + 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, @@ -550,8 +555,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, @@ -559,15 +564,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 IntPtr 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( @@ -579,7 +584,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(); @@ -604,202 +609,201 @@ 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)] - 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 int git_index_add( - IndexSafeHandle index, - GitIndexEntry entry); + internal static extern unsafe int git_index_add( + git_index* index, + git_index_entry* entry); [DllImport(libgit2)] - internal static extern int git_index_conflict_get( - out IndexEntrySafeHandle ancestor, - out IndexEntrySafeHandle ours, - out IndexEntrySafeHandle theirs, - IndexSafeHandle index, + internal static extern unsafe int git_index_conflict_get( + out git_index_entry* ancestor, + out git_index_entry* ours, + out git_index_entry* theirs, + 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 int git_index_conflict_next( - out IndexEntrySafeHandle ancestor, - out IndexEntrySafeHandle ours, - out IndexEntrySafeHandle theirs, - ConflictIteratorSafeHandle iterator); + internal static extern unsafe int git_index_conflict_next( + out git_index_entry* ancestor, + out git_index_entry* ours, + out git_index_entry* theirs, + 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 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); + internal static extern unsafe void git_index_free(git_index* 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(git_index* index, UIntPtr n); [DllImport(libgit2)] - internal static extern IndexEntrySafeHandle git_index_get_bypath( - IndexSafeHandle index, + internal static extern unsafe git_index_entry* git_index_get_bypath( + 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 IndexNameEntrySafeHandle 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 IndexReucEntrySafeHandle 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 IndexReucEntrySafeHandle git_index_reuc_get_bypath( - IndexSafeHandle handle, + internal static extern unsafe git_index_reuc_entry* git_index_reuc_get_bypath( + 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 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, 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, git_object* 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 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 int git_annotated_commit_from_ref( - out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, - ReferenceSafeHandle reference); + internal static extern unsafe int git_annotated_commit_from_ref( + out git_annotated_commit* annotatedCommit, + git_repository* repo, + git_reference* reference); [DllImport(libgit2)] - internal static extern int git_annotated_commit_from_fetchhead( - out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, + internal static extern unsafe int git_annotated_commit_from_fetchhead( + 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, ref GitOid oid); [DllImport(libgit2)] - internal static extern int git_annotated_commit_from_revspec( - out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, + internal static extern unsafe int git_annotated_commit_from_revspec( + out git_annotated_commit* annotatedCommit, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string revspec); [DllImport(libgit2)] - internal static extern int git_annotated_commit_lookup( - out GitAnnotatedCommitHandle annotatedCommit, - RepositorySafeHandle repo, + internal static extern unsafe int git_annotated_commit_lookup( + out git_annotated_commit* annotatedCommit, + git_repository* repo, ref GitOid id); [DllImport(libgit2)] - internal static extern OidSafeHandle git_annotated_commit_id( - GitAnnotatedCommitHandle annotatedCommit); + internal static extern unsafe git_oid* git_annotated_commit_id( + git_annotated_commit* 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( - out IndexSafeHandle index, - RepositorySafeHandle repo, - GitObjectSafeHandle our_commit, - GitObjectSafeHandle their_commit, + internal static extern unsafe int git_merge_commits( + out git_index* index, + git_repository* repo, + git_object* our_commit, + git_object* 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); [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( @@ -809,45 +813,45 @@ 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, + git_signature* author, + git_signature* committer, ref GitOid oid, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string note, 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 OidSafeHandle git_note_id(NoteSafeHandle note); + internal static extern unsafe git_oid* git_note_id(git_note* note); [DllImport(libgit2)] - internal static extern int git_note_read( - out NoteSafeHandle note, - RepositorySafeHandle repo, + internal static extern unsafe int git_note_read( + out git_note* note, + 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, + git_signature* author, + git_signature* 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, @@ -855,150 +859,150 @@ 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); [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 OidSafeHandle git_object_id(GitObjectSafeHandle obj); + internal static extern unsafe git_oid* git_object_id(git_object* 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 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 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); 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 int git_packbuilder_new(out PackBuilderSafeHandle packbuilder, RepositorySafeHandle 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 int git_reference_create( - out ReferenceSafeHandle reference, - RepositorySafeHandle repo, + internal static extern unsafe int git_reference_create( + out git_reference* reference, + git_repository* repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, ref GitOid oid, [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_symbolic_create( - out ReferenceSafeHandle reference, - RepositorySafeHandle repo, + internal static extern unsafe int git_reference_symbolic_create( + out git_reference* reference, + 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, @@ -1009,228 +1013,238 @@ 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); [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( [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 int git_reference_lookup( - out ReferenceSafeHandle reference, - RepositorySafeHandle repo, + internal static extern unsafe int git_reference_lookup( + out git_reference* reference, + git_repository* 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( - 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)] - internal static extern OidSafeHandle git_reference_target(ReferenceSafeHandle reference); + internal static extern unsafe git_oid* 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( - 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)] - 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 int git_reflog_read( - out ReflogSafeHandle ref_out, - RepositorySafeHandle repo, + internal static extern unsafe int git_reflog_read( + 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 OidSafeHandle git_reflog_entry_id_old( - SafeHandle entry); + internal static extern unsafe git_oid* git_reflog_entry_id_old( + git_reflog_entry* entry); [DllImport(libgit2)] - internal static extern OidSafeHandle git_reflog_entry_id_new( - SafeHandle entry); + internal static extern unsafe git_oid* git_reflog_entry_id_new( + git_reflog_entry* entry); [DllImport(libgit2)] - internal static extern IntPtr git_reflog_entry_committer( - SafeHandle entry); + internal static extern unsafe git_signature* git_reflog_entry_committer( + 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 int git_refspec_transform( + GitBuf buf, + IntPtr refspec, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); + [DllImport(libgit2)] internal static extern int git_refspec_rtransform( GitBuf buf, - GitRefSpecHandle refSpec, + IntPtr 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); + IntPtr refSpec); [DllImport(libgit2)] - internal static extern RefSpecDirection git_refspec_direction(GitRefSpecHandle refSpec); + internal static extern unsafe RefSpecDirection git_refspec_direction(IntPtr 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( + IntPtr 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( + IntPtr refspec); [DllImport(libgit2)] - internal static extern bool git_refspec_force(GitRefSpecHandle refSpec); + internal static extern bool git_refspec_force(IntPtr refSpec); [DllImport(libgit2)] - internal static extern int git_remote_autotag(RemoteSafeHandle remote); + internal static extern unsafe bool git_refspec_src_matches( + IntPtr refspec, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string reference); + + [DllImport(libgit2)] + internal static extern unsafe bool git_refspec_dst_matches( + IntPtr refspec, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string reference); + + [DllImport(libgit2)] + 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 int git_remote_create( - out RemoteSafeHandle remote, - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_create( + 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 int git_remote_create_anonymous( - out RemoteSafeHandle remote, - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_create_anonymous( + out git_remote* remote, + 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( - out RemoteSafeHandle remote, - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_create_with_fetchspec( + 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, [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)] - 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 GitRefSpecHandle 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 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); @@ -1239,34 +1253,32 @@ 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( - out RemoteSafeHandle remote, - RepositorySafeHandle repo, + internal static extern unsafe int git_remote_lookup( + out git_remote* remote, + git_repository* 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, 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 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); @@ -1306,200 +1318,200 @@ 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 git_index* 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 git_odb* 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, - ConfigurationSafeHandle config); + internal static extern unsafe void git_repository_set_config( + git_repository* repository, + git_config* 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, - IndexSafeHandle index); + internal static extern unsafe void git_repository_set_index( + git_repository* repository, + git_index* 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, - GitAnnotatedCommitHandle commit); + internal static extern unsafe int git_repository_set_head_detached_from_annotated( + git_repository* repo, + git_annotated_commit* 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, - GitObjectSafeHandle target, + internal static extern unsafe int git_reset( + git_repository* repo, + git_object* target, ResetMode reset_type, ref GitCheckoutOpts opts); [DllImport(libgit2)] - internal static extern int git_revert( - RepositorySafeHandle repo, - GitObjectSafeHandle commit, + internal static extern unsafe int git_revert( + git_repository* repo, + git_object* commit, GitRevertOpts opts); [DllImport(libgit2)] - internal static extern int git_revparse_ext( - out GitObjectSafeHandle obj, - out ReferenceSafeHandle reference, - RepositorySafeHandle repo, + internal static extern unsafe int git_revparse_ext( + 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 int git_revwalk_new(out RevWalkerSafeHandle walker, RepositorySafeHandle 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 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 int git_stash_save( + internal static extern unsafe int git_stash_save( out GitOid id, - RepositorySafeHandle repo, - SignatureSafeHandle stasher, + git_repository* repo, + git_signature* stasher, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, StashModifiers flags); @@ -1510,71 +1522,71 @@ 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( - out StatusListSafeHandle git_status_list, - RepositorySafeHandle repo, + internal static extern unsafe int git_status_list_new( + 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 StatusEntrySafeHandle git_status_byindex( - StatusListSafeHandle list, + internal static extern unsafe git_status_entry* git_status_byindex( + 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( ref GitStrArray array); [DllImport(libgit2)] - internal static extern int git_submodule_lookup( - out SubmoduleSafeHandle reference, - RepositorySafeHandle repo, + internal static extern unsafe int git_submodule_lookup( + out git_submodule* reference, + 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)] - 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,124 +1596,123 @@ 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); [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 OidSafeHandle git_submodule_index_id( - SubmoduleSafeHandle submodule); + internal static extern unsafe git_oid* git_submodule_index_id( + git_submodule* submodule); [DllImport(libgit2)] - internal static extern OidSafeHandle git_submodule_head_id( - SubmoduleSafeHandle submodule); + internal static extern unsafe git_oid* git_submodule_head_id( + git_submodule* submodule); [DllImport(libgit2)] - internal static extern OidSafeHandle git_submodule_wd_id( - SubmoduleSafeHandle submodule); + internal static extern unsafe git_oid* git_submodule_wd_id( + 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)] - 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); [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)] - 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, + git_object* target, + git_signature* 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, + git_object* target, + git_signature* signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, [MarshalAs(UnmanagedType.Bool)] 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, + git_object* 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))] - 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 IntPtr git_tag_tagger(GitObjectSafeHandle tag); + internal static extern unsafe git_signature* git_tag_tagger(git_object* tag); [DllImport(libgit2)] - internal static extern OidSafeHandle 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(); @@ -1721,7 +1732,7 @@ internal static extern 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( @@ -1754,55 +1765,55 @@ 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(git_object* tree, UIntPtr idx); [DllImport(libgit2)] - internal static extern int git_tree_entry_bypath( - out TreeEntrySafeHandle_Owned tree, - GitObjectSafeHandle root, + internal static extern unsafe int git_tree_entry_bypath( + out git_tree_entry* tree, + git_object* 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 git_oid* 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); + internal static extern unsafe UIntPtr git_tree_entrycount(git_object* 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 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 int git_cherrypick(RepositorySafeHandle 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 e7f610772..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, RepositorySafeHandle 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, RepositorySafeHandle handle, bool allowNul } } - public GitObjectSafeHandle ObjectPtr + public ObjectHandle ObjectPtr { get { return objectPtr; } } diff --git a/LibGit2Sharp/Core/Opaques.cs b/LibGit2Sharp/Core/Opaques.cs new file mode 100644 index 000000000..0d0bb55f0 --- /dev/null +++ b/LibGit2Sharp/Core/Opaques.cs @@ -0,0 +1,31 @@ +using System; + +namespace LibGit2Sharp.Core +{ + internal struct git_tree_entry {} + internal struct git_reference { } + 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 {} + internal struct git_config {} + 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 35371d886..698dad7a4 100644 --- a/LibGit2Sharp/Core/Proxy.cs +++ b/LibGit2Sharp/Core/Proxy.cs @@ -95,32 +95,27 @@ private static void BuildErrorMessageFromException(StringBuilder sb, int level, #region git_blame_ - public static BlameSafeHandle git_blame_file( - RepositorySafeHandle repo, + 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 #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 +130,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 +139,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 +148,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 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; @@ -167,18 +162,18 @@ 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 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); @@ -190,9 +185,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 ReferenceHandle git_branch_create_from_annotated(RepositoryHandle repo, string branch_name, string targetIdentifier, bool force) { - ReferenceSafeHandle reference; + git_reference* reference; using (var annotatedCommit = git_annotated_commit_from_revspec(repo, targetIdentifier)) { @@ -200,10 +195,10 @@ public static ReferenceSafeHandle git_branch_create_from_annotated(RepositorySaf Ensure.ZeroResult(res); } - return reference; + return new ReferenceHandle(reference, true); } - public static void git_branch_delete(ReferenceSafeHandle reference) + public static unsafe void git_branch_delete(ReferenceHandle reference) { int res = NativeMethods.git_branch_delete(reference); Ensure.ZeroResult(res); @@ -211,19 +206,35 @@ public static void git_branch_delete(ReferenceSafeHandle reference) public static 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) => - { - GitBranchType type_out; - res = NativeMethods.git_branch_next(out ref_out, out type_out, iter); - return new { BranchType = type_out }; - }, - (handle, payload) => - { - var reference = Reference.BuildFromPtr(handle, repo); - return new Branch(repo, reference, reference.CanonicalName); - }); + IntPtr iter; + var res = NativeMethods.git_branch_iterator_new(out iter, repo.Handle.AsIntPtr(), branchType); + Ensure.ZeroResult(res); + + try + { + 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 ReferenceHandle(refPtr, true)) + { + reference = Reference.BuildFromPtr(refHandle, repo); + } + yield return new Branch(repo, reference, reference.CanonicalName); + } + } + finally + { + NativeMethods.git_branch_iterator_free(iter); + } } public static void git_branch_iterator_free(IntPtr iter) @@ -231,15 +242,15 @@ 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 ReferenceHandle git_branch_move(ReferenceHandle reference, string new_branch_name, bool force) { - ReferenceSafeHandle ref_out; + git_reference* ref_out; int res = NativeMethods.git_branch_move(out ref_out, reference, new_branch_name, force); Ensure.ZeroResult(res); - return ref_out; + 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()) { @@ -256,7 +267,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()) { @@ -284,8 +295,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) { @@ -296,7 +307,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, ObjectHandle treeish, ref GitCheckoutOpts opts) { int res = NativeMethods.git_checkout_index(repo, treeish, ref opts); Ensure.ZeroResult(res); @@ -306,7 +317,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)) { @@ -318,33 +329,33 @@ 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 #region git_commit_ - public static 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 Signature git_commit_committer(GitObjectSafeHandle obj) + public static unsafe Signature git_commit_committer(ObjectHandle 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, @@ -352,8 +363,8 @@ public static 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; @@ -377,27 +388,27 @@ public static 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 ObjectId git_commit_parent_id(GitObjectSafeHandle obj, uint i) + public static unsafe ObjectId git_commit_parent_id(ObjectHandle 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) + public static int git_commit_parentcount(RepositoryHandle repo, ObjectId id) { using (var obj = new ObjectSafeWrapper(id, repo)) { @@ -405,27 +416,27 @@ public static int git_commit_parentcount(RepositorySafeHandle 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 ObjectId git_commit_tree_id(GitObjectSafeHandle obj) + public static unsafe ObjectId git_commit_tree_id(ObjectHandle obj) { - return NativeMethods.git_commit_tree_id(obj).MarshalAsObjectId(); + return ObjectId.BuildFromPtr(NativeMethods.git_commit_tree_id(obj)); } #endregion #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); @@ -440,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); @@ -468,61 +479,55 @@ public static FilePath git_config_find_xdg() return ConvertPath(NativeMethods.git_config_find_xdg); } - public static void git_config_free(IntPtr config) + public static FilePath git_config_find_programdata() { - NativeMethods.git_config_free(config); + return ConvertPath(NativeMethods.git_config_find_programdata); } - - public static void git_config_entry_free(IntPtr entry) + + public static unsafe void git_config_free(git_config *config) { - NativeMethods.git_config_entry_free(entry); + NativeMethods.git_config_free(config); } - public static ConfigurationEntry git_config_get_entry(ConfigurationSafeHandle config, string key) + public static unsafe ConfigurationEntry git_config_get_entry(ConfigurationHandle 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() + 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 +537,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,68 +567,72 @@ 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, - string regexp, - Func> resultSelector) + ConfigurationHandle config, + string regexp) { - return git_iterator((out ConfigurationIteratorSafeHandle iter) => - NativeMethods.git_config_iterator_glob_new(out iter, config, regexp), - (ConfigurationIteratorSafeHandle iter, out SafeHandleBase handle, out int res) => - { - handle = null; - - IntPtr entry; - res = NativeMethods.git_config_next(out entry, iter); - return new { EntryPtr = entry }; - }, - (handle, payload) => - resultSelector(payload.EntryPtr)); - } + IntPtr iter; + var res = NativeMethods.git_config_iterator_glob_new(out iter, config.AsIntPtr(), regexp); + Ensure.ZeroResult(res); + try + { + while (true) + { + IntPtr entry; + res = NativeMethods.git_config_next(out entry, iter); + if (res == (int)GitErrorCode.IterOver) + { + yield break; + } + Ensure.ZeroResult(res); - public static void git_config_iterator_free(IntPtr iter) - { - NativeMethods.git_config_iterator_free(iter); + yield return Configuration.BuildConfigEntry(entry); + } + } + finally + { + 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 @@ -639,8 +648,8 @@ public static void git_cred_free(IntPtr cred) #region git_describe_ - public static string git_describe_commit( - RepositorySafeHandle repo, + public static unsafe string git_describe_commit( + RepositoryHandle repo, ObjectId committishId, DescribeOptions options) { @@ -657,12 +666,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()) { @@ -690,17 +701,12 @@ 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( - RepositorySafeHandle repo, + public static unsafe void git_diff_blobs( + RepositoryHandle repo, ObjectId oldBlob, ObjectId newBlob, GitDiffOptions options, @@ -726,8 +732,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) @@ -736,35 +742,30 @@ public static void git_diff_foreach( Ensure.ZeroResult(res); } - public static DiffSafeHandle git_diff_tree_to_index( - RepositorySafeHandle repo, - IndexSafeHandle index, + public static unsafe DiffHandle git_diff_tree_to_index( + RepositoryHandle repo, + IndexHandle index, ObjectId oldTree, GitDiffOptions options) { 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 DiffSafeHandle git_diff_tree_to_tree( - RepositorySafeHandle repo, + public static unsafe DiffHandle git_diff_tree_to_tree( + RepositoryHandle repo, ObjectId oldTree, ObjectId newTree, GitDiffOptions options) @@ -772,55 +773,55 @@ public static 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 DiffSafeHandle git_diff_index_to_workdir( - RepositorySafeHandle repo, - IndexSafeHandle index, + public static unsafe DiffHandle git_diff_index_to_workdir( + RepositoryHandle repo, + IndexHandle 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 DiffSafeHandle git_diff_tree_to_workdir( - RepositorySafeHandle repo, + 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 GitDiffDelta 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).MarshalAs(false); + return NativeMethods.git_diff_get_delta(diff, (UIntPtr)idx); } #endregion @@ -843,7 +844,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; @@ -853,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) { @@ -873,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; @@ -888,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); @@ -913,23 +914,23 @@ 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(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 Conflict git_index_conflict_get( - IndexSafeHandle index, + public static unsafe Conflict git_index_conflict_get( + IndexHandle index, FilePath path) { - IndexEntrySafeHandle ancestor, ours, theirs; + git_index_entry* ancestor, ours, theirs; int res = NativeMethods.git_index_conflict_get(out ancestor, out ours, @@ -949,18 +950,18 @@ public static 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 Conflict git_index_conflict_next(ConflictIteratorSafeHandle iterator) + public static unsafe Conflict git_index_conflict_next(ConflictIteratorHandle 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); @@ -971,50 +972,33 @@ 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)); - } - } - - public static void git_index_conflict_iterator_free(IntPtr iterator) - { - NativeMethods.git_index_conflict_iterator_free(iterator); + return new Conflict(IndexEntry.BuildFromPtr(ancestor), + IndexEntry.BuildFromPtr(ours), + IndexEntry.BuildFromPtr(theirs)); } - public static int git_index_entrycount(IndexSafeHandle index) + public static unsafe int git_index_entrycount(IndexHandle index) { return NativeMethods.git_index_entrycount(index) .ConvertToInt(); } - public static StageLevel git_index_entry_stage(IndexEntrySafeHandle index) - { - return (StageLevel)NativeMethods.git_index_entry_stage(index); - } - - public static void git_index_free(IntPtr index) + public static unsafe StageLevel git_index_entry_stage(git_index_entry* entry) { - NativeMethods.git_index_free(index); + return (StageLevel)NativeMethods.git_index_entry_stage(entry); } - public static IndexEntrySafeHandle 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 IndexEntrySafeHandle 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) { - 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) + public static unsafe bool git_index_has_conflicts(IndexHandle index) { int res = NativeMethods.git_index_has_conflicts(index); Ensure.BooleanResult(res); @@ -1022,61 +1006,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 IndexNameEntrySafeHandle 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 IndexReucEntrySafeHandle 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 IndexReucEntrySafeHandle 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); @@ -1085,7 +1069,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(IndexHandle index, RepositoryHandle repo) { GitOid treeOid; int res = NativeMethods.git_index_write_tree_to(out treeOid, index, repo); @@ -1094,13 +1078,13 @@ public static ObjectId git_index_write_tree_to(IndexSafeHandle index, Repository return treeOid; } - public static 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); } - 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); @@ -1110,9 +1094,9 @@ 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, out bool earlyStop) + public static unsafe IndexHandle git_merge_commits(RepositoryHandle repo, ObjectHandle ourCommit, ObjectHandle theirCommit, GitMergeOpts opts, out bool earlyStop) { - IndexSafeHandle index; + git_index* index; int res = NativeMethods.git_merge_commits(out index, repo, ourCommit, theirCommit, ref opts); if (res == (int)GitErrorCode.MergeConflict) { @@ -1124,10 +1108,10 @@ public static IndexSafeHandle git_merge_commits(RepositorySafeHandle repo, GitOb Ensure.ZeroResult(res); } - return index; + return new IndexHandle(index, true); } - 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); @@ -1142,7 +1126,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); @@ -1157,58 +1141,58 @@ 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 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 GitAnnotatedCommitHandle git_annotated_commit_lookup(RepositorySafeHandle 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 GitAnnotatedCommitHandle git_annotated_commit_from_ref(RepositorySafeHandle repo, ReferenceSafeHandle 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); + int res = NativeMethods.git_annotated_commit_from_ref(out commit, repo, reference); Ensure.ZeroResult(res); - return their_head; + return new AnnotatedCommitHandle(commit, true); } - public static GitAnnotatedCommitHandle git_annotated_commit_from_revspec(RepositorySafeHandle 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 ObjectId git_annotated_commit_id(GitAnnotatedCommitHandle mergeHead) + public static unsafe ObjectId git_annotated_commit_id(AnnotatedCommitHandle 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, out bool earlyStop) + public static unsafe void git_merge(RepositoryHandle repo, AnnotatedCommitHandle[] heads, GitMergeOpts mergeOptions, GitCheckoutOpts checkoutOptions, out bool earlyStop) { - 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, @@ -1227,13 +1211,13 @@ public static void git_merge(RepositorySafeHandle repo, GitAnnotatedCommitHandle } } - public static void git_merge_analysis( - RepositorySafeHandle repo, - GitAnnotatedCommitHandle[] heads, + public static unsafe void git_merge_analysis( + RepositoryHandle repo, + 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, @@ -1244,11 +1228,6 @@ public static 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_ @@ -1279,8 +1258,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, @@ -1288,8 +1267,8 @@ public static 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; @@ -1301,7 +1280,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()) { @@ -1312,7 +1291,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, @@ -1320,25 +1299,20 @@ public static ICollection git_note_foreach(RepositorySafeHandl 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 ObjectId git_note_id(NoteSafeHandle note) + public static unsafe ObjectId git_note_id(NoteHandle 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) + 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); @@ -1349,13 +1323,13 @@ public static NoteSafeHandle git_note_read(RepositorySafeHandle repo, string not Ensure.ZeroResult(res); - return note; + return new NoteHandle(note, true); } - 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()) + using (SignatureHandle authorHandle = author.BuildHandle()) + using (SignatureHandle committerHandle = committer.BuildHandle()) { GitOid oid = targetId.Oid; @@ -1374,19 +1348,14 @@ public static void git_note_remove(RepositorySafeHandle repo, string notes_ref, #region git_object_ - public static ObjectId git_object_id(GitObjectSafeHandle obj) - { - return NativeMethods.git_object_id(obj).MarshalAsObjectId(); - } - - public static void git_object_free(IntPtr obj) + public static unsafe ObjectId git_object_id(ObjectHandle obj) { - NativeMethods.git_object_free(obj); + return ObjectId.BuildFromPtr(NativeMethods.git_object_id(obj)); } - public static GitObjectSafeHandle git_object_lookup(RepositorySafeHandle 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); @@ -1400,12 +1369,12 @@ public static GitObjectSafeHandle git_object_lookup(RepositorySafeHandle repo, O break; } - return handle; + return new ObjectHandle(handle, true); } - public static GitObjectSafeHandle git_object_peel(RepositorySafeHandle 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)) @@ -1421,10 +1390,10 @@ public static GitObjectSafeHandle git_object_peel(RepositorySafeHandle repo, Obj } Ensure.ZeroResult(res); - return peeled; + return new ObjectHandle(peeled, true); } - public static string git_object_short_id(RepositorySafeHandle 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()) @@ -1436,7 +1405,7 @@ public static string git_object_short_id(RepositorySafeHandle 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); } @@ -1445,7 +1414,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)); } @@ -1465,7 +1434,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; @@ -1475,7 +1444,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; @@ -1487,31 +1456,29 @@ 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(ObjectDatabaseHandle 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) + 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; + return new OdbStreamHandle(stream, true); } - public static void git_odb_free(IntPtr odb) - { - NativeMethods.git_odb_free(odb); - } - - 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 @@ -1525,7 +1492,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); @@ -1534,35 +1501,25 @@ 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_ - 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); @@ -1574,22 +1531,17 @@ public static Tuple git_patch_line_stats(PatchSafeHandle patch) #region git_packbuilder_ - public static void git_packbuilder_free(IntPtr packbuilder) - { - NativeMethods.git_packbuilder_free(packbuilder); - } - - public static PackBuilderSafeHandle git_packbuilder_new(RepositorySafeHandle 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; @@ -1597,7 +1549,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; @@ -1605,7 +1557,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; @@ -1613,7 +1565,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; @@ -1621,23 +1573,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); } @@ -1645,37 +1597,37 @@ public static uint git_packbuilder_written(PackBuilderSafeHandle packbuilder) #region git_rebase - public static RebaseSafeHandle git_rebase_init( - RepositorySafeHandle repo, - GitAnnotatedCommitHandle branch, - GitAnnotatedCommitHandle upstream, - GitAnnotatedCommitHandle onto, + public static unsafe RebaseHandle git_rebase_init( + RepositoryHandle repo, + 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 RebaseSafeHandle git_rebase_open(RepositorySafeHandle 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); @@ -1702,15 +1654,12 @@ private static UIntPtr GIT_REBASE_NO_OPERATION public const long RebaseNoOperation = -1; - public static GitRebaseOperation git_rebase_operation_byindex( - RebaseSafeHandle rebase, + public static unsafe git_rebase_operation* git_rebase_operation_byindex( + RebaseHandle 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)); } /// @@ -1718,10 +1667,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(RebaseHandle rebase) { - GitRebaseOperation operation = null; - IntPtr ptr; + git_rebase_operation* ptr; int result = NativeMethods.git_rebase_next(out ptr, rebase); if (result == (int)GitErrorCode.IterOver) { @@ -1729,22 +1677,19 @@ 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 GitRebaseCommitResult git_rebase_commit( - RebaseSafeHandle rebase, + public static unsafe GitRebaseCommitResult git_rebase_commit( + RebaseHandle rebase, Identity author, Identity committer) { 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(); @@ -1781,8 +1726,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"); @@ -1790,8 +1735,8 @@ public static void git_rebase_abort( Ensure.ZeroResult(result); } - public static void git_rebase_finish( - RebaseSafeHandle rebase, + public static unsafe void git_rebase_finish( + RebaseHandle rebase, Identity committer) { Ensure.ArgumentNotNull(rebase, "rebase"); @@ -1804,59 +1749,49 @@ public static void git_rebase_finish( } } - public static void git_rebase_free(IntPtr rebase) - { - NativeMethods.git_rebase_free(rebase); - } - #endregion #region git_reference_ - public static ReferenceSafeHandle git_reference_create( - RepositorySafeHandle repo, + public static unsafe ReferenceHandle git_reference_create( + RepositoryHandle repo, string name, ObjectId targetId, bool allowOverwrite, 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 ReferenceHandle(handle, true); } - public static ReferenceSafeHandle git_reference_symbolic_create( - RepositorySafeHandle repo, + public static unsafe ReferenceHandle git_reference_symbolic_create( + RepositoryHandle 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 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) { 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); @@ -1865,7 +1800,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(); @@ -1882,9 +1817,9 @@ public static IList git_reference_list(RepositorySafeHandle repo) } } - public static ReferenceSafeHandle git_reference_lookup(RepositorySafeHandle repo, string name, bool shouldThrowIfNotFound) + public static unsafe ReferenceHandle git_reference_lookup(RepositoryHandle 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) @@ -1894,71 +1829,71 @@ public static ReferenceSafeHandle git_reference_lookup(RepositorySafeHandle repo Ensure.ZeroResult(res); - return handle; + return new ReferenceHandle(handle, true); } - public static string git_reference_name(ReferenceSafeHandle reference) + 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); } - 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(); + return ObjectId.BuildFromPtr(NativeMethods.git_reference_target(reference)); } - public static ReferenceSafeHandle git_reference_rename( - ReferenceSafeHandle reference, + public static unsafe ReferenceHandle git_reference_rename( + ReferenceHandle 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); Ensure.ZeroResult(res); - return ref_out; + return new ReferenceHandle(ref_out, true); } - public static ReferenceSafeHandle git_reference_set_target(ReferenceSafeHandle reference, ObjectId id, string logMessage) + public static unsafe ReferenceHandle git_reference_set_target(ReferenceHandle 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); Ensure.ZeroResult(res); - return ref_out; + return new ReferenceHandle(ref_out, true); } - public static ReferenceSafeHandle git_reference_symbolic_set_target(ReferenceSafeHandle reference, string target, string logMessage) + public static unsafe ReferenceHandle git_reference_symbolic_set_target(ReferenceHandle 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); Ensure.ZeroResult(res); - return ref_out; + return new ReferenceHandle(ref_out, true); } - 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); } - 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); @@ -1968,47 +1903,42 @@ public static void git_reference_ensure_log(RepositorySafeHandle repo, string re #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 ReflogSafeHandle git_reflog_read(RepositorySafeHandle 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 ObjectId git_reflog_entry_id_old(SafeHandle entry) + public static unsafe ObjectId git_reflog_entry_id_old(git_reflog_entry* 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(git_reflog_entry* 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) + 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); } @@ -2017,7 +1947,18 @@ 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_transform(IntPtr 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 unsafe string git_refspec_rtransform(IntPtr refSpecPtr, string name) { using (var buf = new GitBuf()) { @@ -2028,68 +1969,78 @@ public static string git_refspec_rtransform(GitRefSpecHandle refSpecPtr, string } } - public static string git_refspec_string(GitRefSpecHandle refSpec) + public static unsafe string git_refspec_string(IntPtr refspec) { - return NativeMethods.git_refspec_string(refSpec); + return NativeMethods.git_refspec_string(refspec); } - public static string git_refspec_src(GitRefSpecHandle refSpec) + public static unsafe string git_refspec_src(IntPtr refSpec) { return NativeMethods.git_refspec_src(refSpec); } - public static string git_refspec_dst(GitRefSpecHandle refSpec) + public static unsafe string git_refspec_dst(IntPtr refSpec) { return NativeMethods.git_refspec_dst(refSpec); } - public static RefSpecDirection git_refspec_direction(GitRefSpecHandle refSpec) + public static unsafe RefSpecDirection git_refspec_direction(IntPtr refSpec) { return NativeMethods.git_refspec_direction(refSpec); } - public static bool git_refspec_force(GitRefSpecHandle refSpec) + public static unsafe bool git_refspec_force(IntPtr refSpec) { return NativeMethods.git_refspec_force(refSpec); } + public static bool git_refspec_src_matches(IntPtr refspec, string reference) + { + return NativeMethods.git_refspec_src_matches(refspec, reference); + } + + public static bool git_refspec_dst_matches(IntPtr refspec, string reference) + { + return NativeMethods.git_refspec_dst_matches(refspec, reference); + } + #endregion #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 RemoteSafeHandle git_remote_create(RepositorySafeHandle 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 RemoteSafeHandle git_remote_create_with_fetchspec(RepositorySafeHandle 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 RemoteSafeHandle git_remote_create_anonymous(RepositorySafeHandle 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(); @@ -2104,7 +2055,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); @@ -2116,17 +2067,17 @@ 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(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(); @@ -2143,7 +2094,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(); @@ -2160,7 +2111,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(); @@ -2177,32 +2128,32 @@ 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); } - 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(); @@ -2220,11 +2171,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); @@ -2233,7 +2179,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(); @@ -2250,32 +2196,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, RemoteHandle 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). @@ -2290,10 +2227,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++) @@ -2314,9 +2249,9 @@ public static IEnumerable git_remote_ls(Repository repository, Remote return refs; } - public static RemoteSafeHandle git_remote_lookup(RepositorySafeHandle 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) @@ -2325,15 +2260,15 @@ public static RemoteSafeHandle git_remote_lookup(RepositorySafeHandle repo, stri } 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); } - 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) { @@ -2367,17 +2302,17 @@ 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); } - 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); } @@ -2391,13 +2326,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, @@ -2408,58 +2343,53 @@ 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 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 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, @@ -2468,7 +2398,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()) { @@ -2483,18 +2413,18 @@ public static string git_repository_message(RepositorySafeHandle repo) } } - public static ObjectDatabaseSafeHandle git_repository_odb(RepositorySafeHandle 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 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) @@ -2505,27 +2435,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) { @@ -2536,41 +2465,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, ConfigurationHandle 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, IndexHandle 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); } @@ -2580,20 +2509,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, AnnotatedCommitHandle 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); @@ -2603,8 +2532,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) @@ -2620,8 +2549,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) { @@ -2636,10 +2565,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(RepositoryHandle repo, string objectish) { - GitObjectSafeHandle obj; - ReferenceSafeHandle reference; + git_object* obj; + git_reference* reference; int res = NativeMethods.git_revparse_ext(out obj, out reference, repo, objectish); switch (res) @@ -2656,10 +2585,10 @@ public static Tuple git_revparse_ext(R break; } - return new Tuple(obj, reference); + return new Tuple(new ObjectHandle(obj, true), new ReferenceHandle(reference, true)); } - public static GitObjectSafeHandle git_revparse_single(RepositorySafeHandle repo, string objectish) + public static ObjectHandle git_revparse_single(RepositoryHandle repo, string objectish) { var handles = git_revparse_ext(repo, objectish); @@ -2677,28 +2606,23 @@ public static GitObjectSafeHandle git_revparse_single(RepositorySafeHandle repo, #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 RevWalkerSafeHandle git_revwalk_new(RepositorySafeHandle 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); @@ -2713,24 +2637,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); } @@ -2739,34 +2663,29 @@ public static void git_revwalk_simplify_first_parent(RevWalkerSafeHandle walker) #region git_signature_ - public static void git_signature_free(IntPtr signature) - { - NativeMethods.git_signature_free(signature); - } - - public static SignatureSafeHandle git_signature_new(string name, string email, DateTimeOffset when) + public static unsafe SignatureHandle 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; @@ -2776,13 +2695,13 @@ 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) { - using (SignatureSafeHandle sigHandle = stasher.BuildHandle()) + using (SignatureHandle sigHandle = stasher.BuildHandle()) { GitOid stashOid; @@ -2799,8 +2718,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, @@ -2811,7 +2730,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); @@ -2838,16 +2757,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) { @@ -2858,7 +2777,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); @@ -2882,31 +2801,26 @@ 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 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 StatusEntrySafeHandle 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_ @@ -2915,10 +2829,10 @@ 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 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) { @@ -2929,11 +2843,11 @@ public static SubmoduleSafeHandle git_submodule_lookup(RepositorySafeHandle repo default: Ensure.ZeroResult(res); - return reference; + return new SubmoduleHandle(submodule, true); } } - 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()) { @@ -2944,75 +2858,71 @@ 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)); } - 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 ObjectId git_submodule_index_id(SubmoduleSafeHandle submodule) + public static unsafe ObjectId git_submodule_index_id(SubmoduleHandle 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(SubmoduleHandle 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(SubmoduleHandle 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) + 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); } - 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); @@ -3020,7 +2930,7 @@ public static SubmoduleStatus git_submodule_status(RepositorySafeHandle repo, st 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); @@ -3030,15 +2940,15 @@ 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, 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); @@ -3048,8 +2958,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, @@ -3057,7 +2967,7 @@ public static 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); @@ -3067,7 +2977,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)) { @@ -3079,13 +2989,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(); @@ -3102,24 +3012,24 @@ public static IList git_tag_list(RepositorySafeHandle 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 Signature git_tag_tagger(GitObjectSafeHandle tag) + public static unsafe Signature git_tag_tagger(ObjectHandle 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); } @@ -3127,12 +3037,12 @@ 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(ObjectHandle 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) + public static unsafe GitObjectType git_tag_target_type(ObjectHandle tag) { return NativeMethods.git_tag_target_type(tag); } @@ -3201,21 +3111,27 @@ public static int git_transport_smart_credentials(out IntPtr cred, IntPtr transp #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 TreeEntryHandle git_tree_entry_byindex(ObjectHandle 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 TreeEntrySafeHandle_Owned 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)) { - 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) @@ -3225,31 +3141,26 @@ public static TreeEntrySafeHandle_Owned git_tree_entry_bypath(RepositorySafeHand Ensure.ZeroResult(res); - return treeEntryPtr; + return new TreeEntryHandle(treeEntryPtr, true); } } - public static void git_tree_entry_free(IntPtr treeEntry) + public static unsafe ObjectId git_tree_entry_id(git_tree_entry* entry) { - NativeMethods.git_tree_entry_free(treeEntry); + return ObjectId.BuildFromPtr(NativeMethods.git_tree_entry_id(entry)); } - public static ObjectId git_tree_entry_id(SafeHandle 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); } - public static int git_tree_entrycount(GitObjectSafeHandle tree) + public static unsafe int git_tree_entrycount(ObjectHandle tree) { return (int)NativeMethods.git_tree_entrycount(tree); } @@ -3258,21 +3169,16 @@ public static int git_tree_entrycount(GitObjectSafeHandle tree) #region git_treebuilder_ - public static TreeBuilderSafeHandle git_treebuilder_new(RepositorySafeHandle 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; + return new TreeBuilderHandle(builder, true); } - public static void git_treebuilder_free(IntPtr bld) - { - NativeMethods.git_treebuilder_free(bld); - } - - 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, @@ -3280,7 +3186,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); @@ -3443,67 +3349,9 @@ 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) - where THandle : SafeHandleBase - { - while (true) - { - var next = default(THandle); - 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 - { - next.SafeDispose(); - } - } - } - - private static IEnumerable git_iterator( - IteratorNew newFunc, - IteratorNext nextFunc, - Func resultSelector - ) - where TIterator : SafeHandleBase - where THandle : 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) + 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/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/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/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/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/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/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/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/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/Index.cs b/LibGit2Sharp/Index.cs index f63c91d7c..8128741ac 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; @@ -15,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; @@ -46,7 +47,7 @@ internal Index(Repository repo, string indexPath) repo.RegisterForCleanup(handle); } - internal IndexSafeHandle Handle + internal IndexHandle Handle { get { return handle; } } @@ -70,22 +71,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); } } @@ -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 501d12717..dc652dfcf 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 = (git_index_entry.GIT_IDXENTRY_VALID & entry->flags) == git_index_entry.GIT_IDXENTRY_VALID }; } diff --git a/LibGit2Sharp/IndexNameEntry.cs b/LibGit2Sharp/IndexNameEntry.cs index 5ba24f9c3..79b3f6993 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).Native : null; - string ours = entry.Ours != IntPtr.Zero - ? LaxFilePathMarshaler.FromNative(entry.Ours).Native + string ours = entry->ours != null + ? LaxFilePathMarshaler.FromNative(entry->ours).Native : null; - string theirs = entry.Theirs != IntPtr.Zero - ? LaxFilePathMarshaler.FromNative(entry.Theirs).Native + string theirs = entry->theirs != null + ? LaxFilePathMarshaler.FromNative(entry->theirs).Native : 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 72afcc658..dcc43cb85 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 @@ -79,22 +77,16 @@ - - - - - - @@ -118,8 +110,6 @@ - - @@ -152,11 +142,7 @@ - - - - @@ -169,8 +155,6 @@ - - @@ -201,20 +185,15 @@ - - - - - @@ -243,11 +222,8 @@ - - - @@ -255,7 +231,6 @@ - @@ -280,25 +255,11 @@ - - - - - - - - - - - - - - @@ -311,7 +272,6 @@ - @@ -322,11 +282,6 @@ - - - Code - - @@ -337,7 +292,6 @@ - @@ -356,7 +310,6 @@ - @@ -374,7 +327,6 @@ - @@ -389,6 +341,11 @@ + + + Objects.tt + + @@ -401,6 +358,10 @@ + + TextTemplatingFileGenerator + Objects.cs + 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/Network.cs b/LibGit2Sharp/Network.cs index 231911ada..f014b7d61 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,57 +130,57 @@ private IEnumerable ListReferencesInternal(string url, CredentialsHan } } - static RemoteSafeHandle BuildRemoteSafeHandle(RepositorySafeHandle repoHandle, Remote remote) + static RemoteHandle BuildRemoteHandle(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)); + RemoteHandle remoteHandle = Proxy.git_remote_lookup(repoHandle, remote.Name, true); + Debug.Assert(remoteHandle != null && !(remoteHandle.IsNull)); return remoteHandle; } - static RemoteSafeHandle BuildRemoteSafeHandle(RepositorySafeHandle repoHandle, string url) + static RemoteHandle BuildRemoteHandle(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); - 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; } static void DoFetch( - RepositorySafeHandle repoHandle, + RepositoryHandle repoHandle, Remote remote, FetchOptions options, string logMessage, IEnumerable refspecs) { - using (RemoteSafeHandle remoteHandle = BuildRemoteSafeHandle(repoHandle, remote)) + using (RemoteHandle remoteHandle = BuildRemoteHandle(repoHandle, remote)) { DoFetch(options, remoteHandle, logMessage, refspecs); } } static void DoFetch( - RepositorySafeHandle repoHandle, + RepositoryHandle repoHandle, string url, FetchOptions options, 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(); @@ -526,7 +526,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..30084881d 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 @@ -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/ObjectDatabase.cs b/LibGit2Sharp/ObjectDatabase.cs index 9171e870c..3705ec5e5 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. @@ -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(); } @@ -649,7 +648,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) { diff --git a/LibGit2Sharp/ObjectId.cs b/LibGit2Sharp/ObjectId.cs index 8c4290741..c04100fe9 100644 --- a/LibGit2Sharp/ObjectId.cs +++ b/LibGit2Sharp/ObjectId.cs @@ -57,6 +57,32 @@ 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); + } + + 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. /// 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/Patch.cs b/LibGit2Sharp/Patch.cs index fce96e105..dd668eda4 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(DiffHandle 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..c5404fed5 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(DiffHandle 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/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/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 c479f12ca..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. /// @@ -85,21 +92,13 @@ 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) => - { - 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() @@ -108,13 +107,13 @@ 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 (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 (ReferenceHandle branchRefPtr = RefHandleFromBranch(branch)) + using (ReferenceHandle upstreamRefPtr = RefHandleFromBranch(upstream)) + using (ReferenceHandle ontoRefPtr = RefHandleFromBranch(onto)) + 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, @@ -134,7 +133,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"); @@ -150,7 +149,7 @@ public virtual RebaseResult Continue(Identity committer, 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)) { // TODO: Should we check the pre-conditions for committing here // for instance - what if we had failed on the git_rebase_finish call, @@ -163,11 +162,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) { @@ -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); } @@ -223,7 +222,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) { @@ -235,13 +234,13 @@ public virtual 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); - 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 +250,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) { @@ -263,12 +262,12 @@ public virtual 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)) { - 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; } } @@ -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 abb4537c3..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 @@ -14,7 +15,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 +51,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 +75,7 @@ private static RebaseResult CompleteRebase(RebaseSafeHandle rebaseOperationHandl /// /// /// - private static RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperationHandle, + private static unsafe RebaseResult RunRebaseStep(RebaseHandle rebaseOperationHandle, Repository repository, Identity committer, RebaseOptions options, @@ -84,12 +85,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 +99,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); @@ -153,7 +154,7 @@ private static RebaseResult RunRebaseStep(RebaseSafeHandle rebaseOperationHandle 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; @@ -184,13 +185,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."); @@ -212,7 +213,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/RefSpec.cs b/LibGit2Sharp/RefSpec.cs index 9c811c5f9..5819820eb 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,16 @@ 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"); + // This is here to keep the pointer alive + #pragma warning disable 0414 + readonly Remote remote; + #pragma warning restore 0414 + readonly IntPtr handle; - Specification = refSpec; - Direction = direction; - Source = source; - Destination = destination; - ForceUpdate = forceUpdate; + internal unsafe RefSpec(Remote remote, git_refspec* handle) + { + this.remote = remote; + this.handle = new IntPtr(handle); } /// @@ -30,38 +30,100 @@ 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); + } + } + + /// + /// 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 { diff --git a/LibGit2Sharp/RefSpecCollection.cs b/LibGit2Sharp/RefSpecCollection.cs index 163281a12..6ba813e47 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,12 @@ namespace LibGit2Sharp [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RefSpecCollection : IEnumerable { - readonly IList refspecs; + // These are here to keep the pointer alive + #pragma warning disable 0414 + readonly Remote remote; + readonly RemoteHandle handle; + #pragma warning restore 0414 + readonly Lazy> refspecs; /// /// Needed for mocking purposes. @@ -22,28 +28,27 @@ public class RefSpecCollection : IEnumerable protected RefSpecCollection() { } - internal RefSpecCollection(RemoteSafeHandle handle) + internal RefSpecCollection(Remote remote, RemoteHandle handle) { Ensure.ArgumentNotNull(handle, "handle"); - refspecs = RetrieveRefSpecs(handle); + this.remote = remote; + this.handle = handle; + + refspecs = new Lazy>(() => RetrieveRefSpecs(remote, handle)); } - static IList RetrieveRefSpecs(RemoteSafeHandle remoteHandle) + static unsafe IList RetrieveRefSpecs(Remote remote, RemoteHandle 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; - } /// @@ -52,7 +57,7 @@ static IList RetrieveRefSpecs(RemoteSafeHandle remoteHandle) /// An object that can be used to iterate through the collection. public virtual IEnumerator GetEnumerator() { - return refspecs.GetEnumerator(); + return refspecs.Value.GetEnumerator(); } /// diff --git a/LibGit2Sharp/Reference.cs b/LibGit2Sharp/Reference.cs index fa6d9be9e..40a85f79f 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(ReferenceHandle handle, Repository repo) where T : Reference + { + return BuildFromPtr((git_reference*) handle.Handle, 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..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 (ReferenceSafeHandle 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 (ReferenceSafeHandle 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 (ReferenceSafeHandle 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 (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(reference.CanonicalName)) - using (ReferenceSafeHandle 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 (ReferenceSafeHandle 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 (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(directRef.CanonicalName)) - using (ReferenceSafeHandle 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 (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(symbolicRef.CanonicalName)) - using (ReferenceSafeHandle 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 ReferenceSafeHandle RetrieveReferencePtr(string referenceName, bool shouldThrowIfNotFound = true) + internal ReferenceHandle RetrieveReferencePtr(string referenceName, bool shouldThrowIfNotFound = true) { - ReferenceSafeHandle 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/ReferenceWrapper.cs b/LibGit2Sharp/ReferenceWrapper.cs index 471dc1ede..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)); } @@ -59,15 +61,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/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..d5f064c5a 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); @@ -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/Remote.cs b/LibGit2Sharp/Remote.cs index 137208198..3930fdd28 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); @@ -22,29 +22,59 @@ public class Remote : IEquatable, IBelongToARepository private readonly RefSpecCollection refSpecs; private string pushUrl; + readonly RemoteHandle handle; + /// /// Needed for mocking purposes. /// protected Remote() { } - private Remote(RemoteSafeHandle handle, Repository repository) + internal Remote(RemoteHandle 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); + repository.RegisterForCleanup(this); + } + + ~Remote() + { + Dispose(false); + } + + #region IDisposable + + bool disposedValue = false; // To detect redundant calls + + /// + /// Release the unmanaged remote object + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); } - internal static Remote BuildFromPtr(RemoteSafeHandle handle, Repository repo) + void Dispose(bool disposing) { - var remote = new Remote(handle, repo); + if (!disposedValue) + { + if (handle != null) + { + handle.Dispose(); + } - return remote; + disposedValue = true; + } } + #endregion + /// /// Gets the alias of this remote repository. /// @@ -98,12 +128,12 @@ 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)) + using (RemoteHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, Name, true)) { - GitRefSpecHandle fetchSpecPtr = Proxy.git_remote_get_refspec(remoteHandle, 0); - return Proxy.git_refspec_rtransform(fetchSpecPtr, reference); + git_refspec* fetchSpecPtr = Proxy.git_remote_get_refspec(remoteHandle, 0); + return Proxy.git_refspec_rtransform(new IntPtr(fetchSpecPtr), reference); } } diff --git a/LibGit2Sharp/RemoteCallbacks.cs b/LibGit2Sharp/RemoteCallbacks.cs index 42037a22e..9958c6844 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 }; @@ -285,24 +285,35 @@ 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) + 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 +355,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; } diff --git a/LibGit2Sharp/RemoteCollection.cs b/LibGit2Sharp/RemoteCollection.cs index 6ab1a3faf..2d33ffd0f 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); - } + RemoteHandle 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); - } + RemoteHandle 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); - } + RemoteHandle handle = Proxy.git_remote_create_with_fetchspec(repository.Handle, name, url, fetchRefSpec); + return new Remote(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 bf96c206d..0ad989f94 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; @@ -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) { @@ -583,8 +583,8 @@ public static IEnumerable ListRemoteReferences(string url, Credential { Ensure.ArgumentNotNull(url, "url"); - using (RepositorySafeHandle repositoryHandle = Proxy.git_repository_new()) - using (RemoteSafeHandle remoteHandle = Proxy.git_remote_create_anonymous(repositoryHandle, url)) + using (RepositoryHandle repositoryHandle = Proxy.git_repository_new()) + using (RemoteHandle 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; } @@ -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) @@ -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. @@ -1165,7 +1150,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 +1159,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 +1190,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); } @@ -1225,8 +1210,8 @@ public MergeResult Merge(Branch branch, Signature merger, MergeOptions options) options = options ?? new MergeOptions(); - using (ReferenceSafeHandle referencePtr = Refs.RetrieveReferencePtr(branch.CanonicalName)) - using (GitAnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_from_ref(Handle, referencePtr)) + using (ReferenceHandle referencePtr = Refs.RetrieveReferencePtr(branch.CanonicalName)) + using (AnnotatedCommitHandle annotatedCommitHandle = Proxy.git_annotated_commit_from_ref(Handle, referencePtr)) { return Merge(new[] { annotatedCommitHandle }, merger, options); } @@ -1276,7 +1261,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 +1272,7 @@ public MergeResult MergeFetchedRefs(Signature merger, MergeOptions options) finally { // Cleanup. - foreach (GitAnnotatedCommitHandle annotatedCommitHandle in annotatedCommitHandles) + foreach (AnnotatedCommitHandle annotatedCommitHandle in annotatedCommitHandles) { annotatedCommitHandle.Dispose(); } @@ -1470,7 +1455,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 +1535,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; GitMergeFlag treeFlags = options.FindRenames ? GitMergeFlag.GIT_MERGE_FIND_RENAMES @@ -1613,7 +1598,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/RepositoryExtensions.cs b/LibGit2Sharp/RepositoryExtensions.cs index d3754caa3..5f162325b 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. @@ -314,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); + } } /// @@ -597,29 +506,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. /// 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; } /// diff --git a/LibGit2Sharp/RepositoryStatus.cs b/LibGit2Sharp/RepositoryStatus.cs index 8a6b2e0f6..a70212844 100644 --- a/LibGit2Sharp/RepositoryStatus.cs +++ b/LibGit2Sharp/RepositoryStatus.cs @@ -53,33 +53,19 @@ private static IDictionary> Bu protected RepositoryStatus() { } - internal RepositoryStatus(Repository repo, StatusOptions options) + 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); 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,24 +138,24 @@ 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).Native, + LaxFilePathMarshaler.FromNative(deltaHeadToIndex->new_file.Path).Native, + (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).Native, + LaxFilePathMarshaler.FromNative(deltaIndexToWorkDir->new_file.Path).Native, + (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); + StatusEntry statusEntry = new StatusEntry(filePath.Native, gitStatus, headToIndexRenameDetails, indexToWorkDirRenameDetails); if (gitStatus == FileStatus.Unaltered) { 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(); diff --git a/LibGit2Sharp/SmartSubtransport.cs b/LibGit2Sharp/SmartSubtransport.cs index c6bf1bcdf..709f0c230 100644 --- a/LibGit2Sharp/SmartSubtransport.cs +++ b/LibGit2Sharp/SmartSubtransport.cs @@ -108,14 +108,22 @@ public int AcquireCredentials(out Credentials cred, string user, params Type[] m return res; } - var baseCred = credHandle.MarshalAs(); - switch (baseCred.credtype) + if (credHandle == IntPtr.Zero) { - case GitCredentialType.UserPassPlaintext: - cred = UsernamePasswordCredentials.FromNative(credHandle.MarshalAs()); - return 0; - default: - throw new InvalidOperationException("User returned an unkown credential type"); + throw new InvalidOperationException("creditals callback indicated success but returned no credentials"); + } + + unsafe + { + var baseCred = (GitCredential*) credHandle; + switch (baseCred->credtype) + { + case GitCredentialType.UserPassPlaintext: + cred = UsernamePasswordCredentials.FromNative((GitCredentialUserpass*) credHandle); + return 0; + default: + throw new InvalidOperationException("User returned an unkown credential type"); + } } } 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/Tree.cs b/LibGit2Sharp/Tree.cs index 08e867d84..0a19f4e04 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 (TreeEntryHandle 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, Id, repo, path.Combine(parentPath)); } } @@ -75,6 +75,14 @@ internal string Path #region IEnumerable Members + unsafe TreeEntry byIndex(ObjectSafeWrapper obj, uint i, ObjectId parentTreeId, Repository repo, FilePath parentPath) + { + using (var entryHandle = Proxy.git_tree_entry_byindex(obj.ObjectPtr, i)) + { + return new TreeEntry(entryHandle, parentTreeId, repo, parentPath); + } + } + /// /// Returns an enumerator that iterates through the collection. /// @@ -83,10 +91,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/TreeChanges.cs b/LibGit2Sharp/TreeChanges.cs index dcf788556..2e317855a 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(DiffHandle 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/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) { diff --git a/LibGit2Sharp/TreeEntry.cs b/LibGit2Sharp/TreeEntry.cs index 30ced73c2..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,19 +28,19 @@ public class TreeEntry : IEquatable protected TreeEntry() { } - internal TreeEntry(SafeHandle obj, ObjectId parentTreeId, Repository repo, FilePath parentPath) + internal unsafe TreeEntry(TreeEntryHandle 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)); } diff --git a/LibGit2Sharp/TreeEntryChanges.cs b/LibGit2Sharp/TreeEntryChanges.cs index 4d57b8e50..53f2ce49e 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).Native; + OldPath = LaxFilePathMarshaler.FromNative(delta->old_file.Path).Native; - 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; } /// diff --git a/LibGit2Sharp/UsernamePasswordCredentials.cs b/LibGit2Sharp/UsernamePasswordCredentials.cs index c8043b3f1..761be5c74 100644 --- a/LibGit2Sharp/UsernamePasswordCredentials.cs +++ b/LibGit2Sharp/UsernamePasswordCredentials.cs @@ -25,12 +25,12 @@ protected internal override int GitCredentialHandler(out IntPtr cred) return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Password); } - static internal UsernamePasswordCredentials FromNative(GitCredentialUserpass gitCred) + static internal unsafe UsernamePasswordCredentials FromNative(GitCredentialUserpass* gitCred) { return new UsernamePasswordCredentials() { - Username = LaxUtf8Marshaler.FromNative(gitCred.username), - Password = LaxUtf8Marshaler.FromNative(gitCred.password), + Username = LaxUtf8Marshaler.FromNative(gitCred->username), + Password = LaxUtf8Marshaler.FromNative(gitCred->password), }; } 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