public Models.Repository GetIncomingChanges(Models.Repository repository) { try { NGit.Api.Git git = NGit.Api.Git.Open(repository.Path); Repository repo = git.GetRepository(); repo.GetIndexFile(); //Repository repo = new FileRepository(new Sharpen.FilePath(path)); //NGit.Api.Git git = new NGit.Api.Git(repo); //TODO: Find out how git works really, and fix this. FetchCommand fc = git.Fetch(); FetchResult fr = fc.Call(); LogCommand lc = git.Log(); Iterable <RevCommit> lr = lc.Call(); if (git != null && repo != null && fr != null && lr != null) { List <Watchtower.Models.Changeset> commits = new List <Watchtower.Models.Changeset>(); foreach (RevCommit rc in lr) { //TODO: Find out if these values are right. Watchtower.Models.Changeset c = new Watchtower.Models.Changeset(rc.GetParent(0).GetHashCode().ToString(), rc.GetHashCode().ToString(), rc.GetCommitterIdent().GetEmailAddress(), rc.GetCommitterIdent().GetWhen(), rc.GetCommitterIdent().GetName(), rc.GetFullMessage()); commits.Add(c); } repository.IncomingChangesets = commits; } } catch { } return(repository); }
public virtual void TestLastModifiedTimes() { Git git = new Git(db); string path = "file"; WriteTrashFile(path, "content"); string path2 = "file2"; WriteTrashFile(path2, "content2"); git.Add().AddFilepattern(path).Call(); git.Add().AddFilepattern(path2).Call(); git.Commit().SetMessage("commit").Call(); DirCache dc = db.ReadDirCache(); DirCacheEntry entry = dc.GetEntry(path); DirCacheEntry entry2 = dc.GetEntry(path); NUnit.Framework.Assert.IsTrue(entry.LastModified != 0, "last modified shall not be zero!" ); NUnit.Framework.Assert.IsTrue(entry2.LastModified != 0, "last modified shall not be zero!" ); WriteTrashFile(path, "new content"); git.Add().AddFilepattern(path).Call(); git.Commit().SetMessage("commit2").Call(); dc = db.ReadDirCache(); entry = dc.GetEntry(path); entry2 = dc.GetEntry(path); NUnit.Framework.Assert.IsTrue(entry.LastModified != 0, "last modified shall not be zero!" ); NUnit.Framework.Assert.IsTrue(entry2.LastModified != 0, "last modified shall not be zero!" ); }
public virtual void TestTaggingOnHead() { Git git = new Git(db); RevCommit commit = git.Commit().SetMessage("initial commit").Call(); RevTag tag = git.Tag().SetName("tag").Call(); NUnit.Framework.Assert.AreEqual(commit.Id, tag.GetObject().Id); }
public virtual void FailingPathsShouldNotResultInOKReturnValue() { FilePath folder1 = new FilePath(db.WorkTree, "folder1"); FileUtils.Mkdir(folder1); FilePath file = new FilePath(folder1, "file1.txt"); Write(file, "folder1--file1.txt"); file = new FilePath(folder1, "file2.txt"); Write(file, "folder1--file2.txt"); Git git = new Git(db); git.Add().AddFilepattern(folder1.GetName()).Call(); RevCommit @base = git.Commit().SetMessage("adding folder").Call(); RecursiveDelete(folder1); git.Rm().AddFilepattern("folder1/file1.txt").AddFilepattern("folder1/file2.txt"). Call(); RevCommit other = git.Commit().SetMessage("removing folders on 'other'").Call(); git.Checkout().SetName(@base.Name).Call(); file = new FilePath(db.WorkTree, "unrelated.txt"); Write(file, "unrelated"); git.Add().AddFilepattern("unrelated").Call(); RevCommit head = git.Commit().SetMessage("Adding another file").Call(); // Untracked file to cause failing path for delete() of folder1 file = new FilePath(folder1, "file3.txt"); Write(file, "folder1--file3.txt"); ResolveMerger merger = new ResolveMerger(db, false); merger.SetCommitNames(new string[] { "BASE", "HEAD", "other" }); merger.SetWorkingTreeIterator(new FileTreeIterator(db)); bool ok = merger.Merge(head.Id, other.Id); NUnit.Framework.Assert.IsFalse(merger.GetFailingPaths().IsEmpty()); NUnit.Framework.Assert.IsFalse(ok); }
public virtual void TestConflictingMergeFailsDueToDirtyIndex() { Git git = new Git(db); FilePath fileA = WriteTrashFile("a", "a"); RevCommit initialCommit = AddAllAndCommit(git); // switch branch CreateBranch(initialCommit, "refs/heads/side"); CheckoutBranch("refs/heads/side"); // modify file a Write(fileA, "a(side)"); WriteTrashFile("b", "b"); RevCommit sideCommit = AddAllAndCommit(git); // switch branch CheckoutBranch("refs/heads/master"); // modify file a - this will cause a conflict during merge Write(fileA, "a(master)"); WriteTrashFile("c", "c"); AddAllAndCommit(git); // modify and add file a Write(fileA, "a(modified)"); git.Add().AddFilepattern("a").Call(); // do not commit // get current index state string indexState = IndexState(CONTENT); // merge MergeCommandResult result = git.Merge().Include(sideCommit.Id).SetStrategy(MergeStrategy .RESOLVE).Call(); CheckMergeFailedResult(result, ResolveMerger.MergeFailureReason.DIRTY_INDEX, indexState , fileA); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="NGit.Api.Errors.NoFilepatternException"></exception> /// <exception cref="NGit.Api.Errors.NoHeadException"></exception> /// <exception cref="NGit.Api.Errors.NoMessageException"></exception> /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException"></exception> /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception> /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException"></exception> public virtual void SetupRepository() { // create initial commit git = new Git(db); initialCommit = git.Commit().SetMessage("initial commit").Call(); // create file indexFile = new FilePath(db.WorkTree, "a.txt"); FileUtils.CreateNewFile(indexFile); PrintWriter writer = new PrintWriter(indexFile); writer.Write("content"); writer.Flush(); // add file and commit it git.Add().AddFilepattern("a.txt").Call(); secondCommit = git.Commit().SetMessage("adding a.txt").Call(); prestage = DirCache.Read(db.GetIndexFile(), db.FileSystem).GetEntry(indexFile.GetName ()); // modify file and add to index writer.Write("new content"); writer.Close(); git.Add().AddFilepattern("a.txt").Call(); // create a file not added to the index untrackedFile = new FilePath(db.WorkTree, "notAddedToIndex.txt"); FileUtils.CreateNewFile(untrackedFile); PrintWriter writer2 = new PrintWriter(untrackedFile); writer2.Write("content"); writer2.Close(); }
public bool VerifyRepository(string path) { bool result = false; try { NGit.Api.Git git = NGit.Api.Git.Open(path); Repository repo = git.GetRepository(); ////Repository repo = new FileRepository(new Sharpen.FilePath(path)); ////NGit.Api.Git git = new NGit.Api.Git(repo); //FetchCommand fc = git.Fetch(); //FetchResult fr = fc.Call(); //LogCommand lc = git.Log(); //Iterable<RevCommit> lr = lc.Call(); string indexFile = repo.GetIndexFile(); //repo.GetRef(); //repo.ReadOrigHead(); if (null != git && null != repo && !string.IsNullOrEmpty(indexFile)) { result = true; } } catch { result = false; } return(result); }
internal NGitTransaction(string path) { _path = path; _git = Git.Open(path); Clean(); }
public virtual void IdOffset() { Git git = new Git(db); WriteTrashFile("fileAinfsonly", "A"); FilePath fileBinindex = WriteTrashFile("fileBinindex", "B"); FsTick(fileBinindex); git.Add().AddFilepattern("fileBinindex").Call(); WriteTrashFile("fileCinfsonly", "C"); TreeWalk tw = new TreeWalk(db); DirCacheIterator indexIter = new DirCacheIterator(db.ReadDirCache()); FileTreeIterator workTreeIter = new FileTreeIterator(db); tw.AddTree(indexIter); tw.AddTree(workTreeIter); workTreeIter.SetDirCacheIterator(tw, 0); AssertEntry("d46c305e85b630558ee19cc47e73d2e5c8c64cdc", "a,", tw); AssertEntry("58ee403f98538ec02409538b3f80adf610accdec", "a,b", tw); AssertEntry("0000000000000000000000000000000000000000", "a", tw); AssertEntry("b8d30ff397626f0f1d3538d66067edf865e201d6", "a0b", tw); // The reason for adding this test. Check that the id is correct for // mixed AssertEntry("8c7e5a667f1b771847fe88c01c3de34413a1b220", "fileAinfsonly", tw); AssertEntry("7371f47a6f8bd23a8fa1a8b2a9479cdd76380e54", "fileBinindex", tw); AssertEntry("96d80cd6c4e7158dbebd0849f4fb7ce513e5828c", "fileCinfsonly", tw); NUnit.Framework.Assert.IsFalse(tw.Next()); }
public virtual void TestPush() { // create other repository Repository db2 = CreateWorkRepository(); // setup the first repository StoredConfig config = ((FileBasedConfig)db.GetConfig()); RemoteConfig remoteConfig = new RemoteConfig(config, "test"); URIish uri = new URIish(db2.Directory.ToURI().ToURL()); remoteConfig.AddURI(uri); remoteConfig.Update(config); config.Save(); Git git1 = new Git(db); // create some refs via commits and tag RevCommit commit = git1.Commit().SetMessage("initial commit").Call(); Ref tagRef = git1.Tag().SetName("tag").Call(); try { db2.Resolve(commit.Id.GetName() + "^{commit}"); NUnit.Framework.Assert.Fail("id shouldn't exist yet"); } catch (MissingObjectException) { } // we should get here RefSpec spec = new RefSpec("refs/heads/master:refs/heads/x"); git1.Push().SetRemote("test").SetRefSpecs(spec).Call(); NUnit.Framework.Assert.AreEqual(commit.Id, db2.Resolve(commit.Id.GetName() + "^{commit}" )); NUnit.Framework.Assert.AreEqual(tagRef.GetObjectId(), db2.Resolve(tagRef.GetObjectId ().GetName())); }
public ICommandResponse Pull (string path, string destPath) { var git = new Git(new FileRepository(ToGitDirString(path))); var pullCommand = git.Pull(); ICommandResponse result = new NGitPullResultAdapter(pullCommand); return result; }
public ICommandResponse Push (string path) { Git git = new Git(new FileRepository(ToGitDirString(path))); Iterable<PushResult> pushResults = git.Push().Call(); ICommandResponse result = new NGitPushResultAdapter(pushResults); return result; }
public virtual void CommitAfterSquashMerge() { Git git = new Git(db); WriteTrashFile("file1", "file1"); git.Add().AddFilepattern("file1").Call(); RevCommit first = git.Commit().SetMessage("initial commit").Call(); NUnit.Framework.Assert.IsTrue(new FilePath(db.WorkTree, "file1").Exists()); CreateBranch(first, "refs/heads/branch1"); CheckoutBranch("refs/heads/branch1"); WriteTrashFile("file2", "file2"); git.Add().AddFilepattern("file2").Call(); git.Commit().SetMessage("second commit").Call(); NUnit.Framework.Assert.IsTrue(new FilePath(db.WorkTree, "file2").Exists()); CheckoutBranch("refs/heads/master"); MergeCommandResult result = git.Merge().Include(db.GetRef("branch1")).SetSquash(true ).Call(); NUnit.Framework.Assert.IsTrue(new FilePath(db.WorkTree, "file1").Exists()); NUnit.Framework.Assert.IsTrue(new FilePath(db.WorkTree, "file2").Exists()); NUnit.Framework.Assert.AreEqual(MergeStatus.FAST_FORWARD_SQUASHED, result.GetMergeStatus ()); // comment not set, should be inferred from SQUASH_MSG RevCommit squashedCommit = git.Commit().Call(); NUnit.Framework.Assert.AreEqual(1, squashedCommit.ParentCount); NUnit.Framework.Assert.IsNull(db.ReadSquashCommitMsg()); NUnit.Framework.Assert.AreEqual("commit: Squashed commit of the following:", db.GetReflogReader (Constants.HEAD).GetLastEntry().GetComment()); NUnit.Framework.Assert.AreEqual("commit: Squashed commit of the following:", db.GetReflogReader (db.GetBranch()).GetLastEntry().GetComment()); }
public virtual void TestSomeCommits() { // do 4 commits Git git = new Git(db); git.Commit().SetMessage("initial commit").Call(); git.Commit().SetMessage("second commit").SetCommitter(committer).Call(); git.Commit().SetMessage("third commit").SetAuthor(author).Call(); git.Commit().SetMessage("fourth commit").SetAuthor(author).SetCommitter(committer ).Call(); Iterable<RevCommit> commits = git.Log().Call(); // check that all commits came in correctly PersonIdent defaultCommitter = new PersonIdent(db); PersonIdent[] expectedAuthors = new PersonIdent[] { defaultCommitter, committer, author, author }; PersonIdent[] expectedCommitters = new PersonIdent[] { defaultCommitter, committer , defaultCommitter, committer }; string[] expectedMessages = new string[] { "initial commit", "second commit", "third commit" , "fourth commit" }; int l = expectedAuthors.Length - 1; foreach (RevCommit c in commits) { NUnit.Framework.Assert.AreEqual(expectedAuthors[l].GetName(), c.GetAuthorIdent(). GetName()); NUnit.Framework.Assert.AreEqual(expectedCommitters[l].GetName(), c.GetCommitterIdent ().GetName()); NUnit.Framework.Assert.AreEqual(c.GetFullMessage(), expectedMessages[l]); l--; } NUnit.Framework.Assert.AreEqual(l, -1); ReflogReader reader = db.GetReflogReader(Constants.HEAD); NUnit.Framework.Assert.IsTrue(reader.GetLastEntry().GetComment().StartsWith("commit:" )); }
public override void SetUp() { base.SetUp(); dbTarget = CreateWorkRepository(); source = new Git(db); target = new Git(dbTarget); // put some file in the source repo sourceFile = new FilePath(db.WorkTree, "SomeFile.txt"); WriteToFile(sourceFile, "Hello world"); // and commit it source.Add().AddFilepattern("SomeFile.txt").Call(); source.Commit().SetMessage("Initial commit for source").Call(); // configure the target repo to connect to the source via "origin" StoredConfig targetConfig = ((FileBasedConfig)dbTarget.GetConfig()); targetConfig.SetString("branch", "master", "remote", "origin"); targetConfig.SetString("branch", "master", "merge", "refs/heads/master"); RemoteConfig config = new RemoteConfig(targetConfig, "origin"); config.AddURI(new URIish(source.GetRepository().WorkTree.GetPath())); config.AddFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); config.Update(targetConfig); targetConfig.Save(); targetFile = new FilePath(dbTarget.WorkTree, "SomeFile.txt"); // make sure we have the same content target.Pull().Call(); target.Checkout().SetStartPoint("refs/remotes/origin/master").SetName("master").Call (); targetConfig.SetString("branch", "master", "merge", "refs/heads/master"); targetConfig.SetBoolean("branch", "master", "rebase", true); targetConfig.Save(); AssertFileContentsEqual(targetFile, "Hello world"); }
public virtual void ResolveUnnamedCurrentBranchCommits() { Git git = new Git(db); WriteTrashFile("file.txt", "content"); git.Add().AddFilepattern("file.txt").Call(); RevCommit c1 = git.Commit().SetMessage("create file").Call(); WriteTrashFile("file.txt", "content2"); git.Add().AddFilepattern("file.txt").Call(); RevCommit c2 = git.Commit().SetMessage("edit file").Call(); NUnit.Framework.Assert.AreEqual(c2, db.Resolve("master@{0}")); NUnit.Framework.Assert.AreEqual(c1, db.Resolve("master@{1}")); git.Checkout().SetCreateBranch(true).SetName("newbranch").SetStartPoint(c1).Call( ); // same as current branch, e.g. master NUnit.Framework.Assert.AreEqual(c1, db.Resolve("@{0}")); try { NUnit.Framework.Assert.AreEqual(c1, db.Resolve("@{1}")); NUnit.Framework.Assert.Fail(); } catch (RevisionSyntaxException e) { // Looking at wrong ref, e.g HEAD NUnit.Framework.Assert.IsNotNull(e); } // detached head, read HEAD reflog git.Checkout().SetName(c2.GetName()).Call(); NUnit.Framework.Assert.AreEqual(c2, db.Resolve("@{0}")); NUnit.Framework.Assert.AreEqual(c1, db.Resolve("@{1}")); NUnit.Framework.Assert.AreEqual(c2, db.Resolve("@{2}")); }
internal NGitTransaction(Repository repository) { _path = repository.WorkTree; _git = new Git(repository); Clean(); }
public virtual void TestAddUnstagedChanges() { FilePath file = new FilePath(db.WorkTree, "a.txt"); FileUtils.CreateNewFile(file); PrintWriter writer = new PrintWriter(file); writer.Write("content"); writer.Close(); Git git = new Git(db); git.Add().AddFilepattern("a.txt").Call(); RevCommit commit = git.Commit().SetMessage("initial commit").Call(); TreeWalk tw = TreeWalk.ForPath(db, "a.txt", commit.Tree); NUnit.Framework.Assert.AreEqual("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.GetObjectId (0).GetName()); writer = new PrintWriter(file); writer.Write("content2"); writer.Close(); commit = git.Commit().SetMessage("second commit").Call(); tw = TreeWalk.ForPath(db, "a.txt", commit.Tree); NUnit.Framework.Assert.AreEqual("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.GetObjectId (0).GetName()); commit = git.Commit().SetAll(true).SetMessage("third commit").SetAll(true).Call(); tw = TreeWalk.ForPath(db, "a.txt", commit.Tree); NUnit.Framework.Assert.AreEqual("db00fd65b218578127ea51f3dffac701f12f486a", tw.GetObjectId (0).GetName()); }
public virtual void TestRevert() { Git git = new Git(db); WriteTrashFile("a", "first line\nsec. line\nthird line\n"); git.Add().AddFilepattern("a").Call(); git.Commit().SetMessage("create a").Call(); WriteTrashFile("b", "content\n"); git.Add().AddFilepattern("b").Call(); git.Commit().SetMessage("create b").Call(); WriteTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n"); git.Add().AddFilepattern("a").Call(); git.Commit().SetMessage("enlarged a").Call(); WriteTrashFile("a", "first line\nsecond line\nthird line\nfourth line\n"); git.Add().AddFilepattern("a").Call(); RevCommit fixingA = git.Commit().SetMessage("fixed a").Call(); WriteTrashFile("b", "first line\n"); git.Add().AddFilepattern("b").Call(); git.Commit().SetMessage("fixed b").Call(); git.Revert().Include(fixingA).Call(); NUnit.Framework.Assert.IsTrue(new FilePath(db.WorkTree, "b").Exists()); CheckFile(new FilePath(db.WorkTree, "a"), "first line\nsec. line\nthird line\nfourth line\n" ); Iterator<RevCommit> history = git.Log().Call().Iterator(); RevCommit revertCommit = history.Next(); string expectedMessage = "Revert \"fixed a\"\n\n" + "This reverts commit " + fixingA .Id.GetName() + ".\n"; NUnit.Framework.Assert.AreEqual(expectedMessage, revertCommit.GetFullMessage()); NUnit.Framework.Assert.AreEqual("fixed b", history.Next().GetFullMessage()); NUnit.Framework.Assert.AreEqual("fixed a", history.Next().GetFullMessage()); NUnit.Framework.Assert.AreEqual("enlarged a", history.Next().GetFullMessage()); NUnit.Framework.Assert.AreEqual("create b", history.Next().GetFullMessage()); NUnit.Framework.Assert.AreEqual("create a", history.Next().GetFullMessage()); NUnit.Framework.Assert.IsFalse(history.HasNext()); }
public virtual void TestCherryPick() { Git git = new Git(db); WriteTrashFile("a", "first line\nsec. line\nthird line\n"); git.Add().AddFilepattern("a").Call(); RevCommit firstCommit = git.Commit().SetMessage("create a").Call(); WriteTrashFile("b", "content\n"); git.Add().AddFilepattern("b").Call(); git.Commit().SetMessage("create b").Call(); WriteTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n"); git.Add().AddFilepattern("a").Call(); git.Commit().SetMessage("enlarged a").Call(); WriteTrashFile("a", "first line\nsecond line\nthird line\nfourth line\n"); git.Add().AddFilepattern("a").Call(); RevCommit fixingA = git.Commit().SetMessage("fixed a").Call(); git.BranchCreate().SetName("side").SetStartPoint(firstCommit).Call(); CheckoutBranch("refs/heads/side"); WriteTrashFile("a", "first line\nsec. line\nthird line\nfeature++\n"); git.Add().AddFilepattern("a").Call(); git.Commit().SetMessage("enhanced a").Call(); git.CherryPick().Include(fixingA).Call(); NUnit.Framework.Assert.IsFalse(new FilePath(db.WorkTree, "b").Exists()); CheckFile(new FilePath(db.WorkTree, "a"), "first line\nsecond line\nthird line\nfeature++\n" ); Iterator<RevCommit> history = git.Log().Call().Iterator(); NUnit.Framework.Assert.AreEqual("fixed a", history.Next().GetFullMessage()); NUnit.Framework.Assert.AreEqual("enhanced a", history.Next().GetFullMessage()); NUnit.Framework.Assert.AreEqual("create a", history.Next().GetFullMessage()); NUnit.Framework.Assert.IsFalse(history.HasNext()); }
public virtual void TestMergeInItself() { Git git = new Git(db); git.Commit().SetMessage("initial commit").Call(); MergeCommandResult result = git.Merge().Include(db.GetRef(Constants.HEAD)).Call(); NUnit.Framework.Assert.AreEqual(MergeStatus.ALREADY_UP_TO_DATE, result.GetMergeStatus ()); }
private static void DoCommit(Git repository, string message) { var commit = repository.Commit(); commit.SetAuthor(GitHub.Username, "*****@*****.**"); commit.SetMessage(message); commit.SetAll(true); commit.Call(); }
public override void SetUp() { base.SetUp(); git = Git.Wrap(db); committedFile = WriteTrashFile(PATH, "content"); git.Add().AddFilepattern(PATH).Call(); head = git.Commit().SetMessage("add file").Call(); NUnit.Framework.Assert.IsNotNull(head); }
public virtual void TestTagging() { Git git = new Git(db); git.Commit().SetMessage("initial commit").Call(); RevCommit commit = git.Commit().SetMessage("second commit").Call(); git.Commit().SetMessage("third commit").Call(); Ref tagRef = git.Tag().SetObjectId(commit).SetName("tag").Call(); NUnit.Framework.Assert.AreEqual(commit.Id, db.Peel(tagRef).GetPeeledObjectId()); }
//private void UpdateRepositoryAllBranches(Git repository) //{ // string currentBranch = repository.GetRepository().GetBranch(); // gitLog.AppendLine("Currently on branch " + currentBranch + "..."); // var branches = repository.BranchList().Call().Select(x => x.GetName()).ToList(); // foreach (string branch in branches) // { // gitLog.AppendLine("Currently on branch " + branch + "..."); // //repository.Checkout().SetName(branch).Call(); // //repository.Pull().SetCredentialsProvider(credentials).Call(); // } // //repository.Checkout().SetName(currentBranch).Call(); //} public void LogRepository(Git repository) { gitLog.AppendLine("Recent changes:"); var commits = repository.Pull().SetCredentialsProvider(credentials).Call().GetMergeResult().GetMergedCommits().Select(x=>x.Name).ToList(); foreach (var commit in commits) { gitLog.AppendLine(commit); } }
public Repository(string path) { if (path == null) throw new ArgumentNullException("path"); this.git = new Git(new FileRepository(Path.Combine(path, ".git"))); this.commits = new List<Commit>(); this.commitLookup = new Dictionary<string, Commit>(); }
public override void SetUp() { base.SetUp(); git = new Git(db); // commit something WriteTrashFile(FILE, "Hello world"); git.Add().AddFilepattern(FILE).Call(); git.Commit().SetMessage("Initial commit").Call(); }
/// <exception cref="NGit.Api.Errors.JGitInternalException"></exception> /// <exception cref="NGit.Api.Errors.RefAlreadyExistsException"></exception> /// <exception cref="NGit.Api.Errors.RefNotFoundException"></exception> /// <exception cref="NGit.Api.Errors.InvalidRefNameException"></exception> public virtual Ref CreateBranch(Git actGit, string name, bool force, string startPoint , CreateBranchCommand.SetupUpstreamMode? mode) { CreateBranchCommand cmd = actGit.BranchCreate(); cmd.SetName(name); cmd.SetForce(force); cmd.SetStartPoint(startPoint); cmd.SetUpstreamMode(mode != null ? mode.Value : CreateBranchCommand.SetupUpstreamMode.NOT_SET); return cmd.Call(); }
public virtual void TestTaggingOnHead() { Git git = new Git(db); RevCommit commit = git.Commit().SetMessage("initial commit").Call(); Ref tagRef = git.Tag().SetName("tag").Call(); NUnit.Framework.Assert.AreEqual(commit.Id, db.Peel(tagRef).GetPeeledObjectId()); RevWalk walk = new RevWalk(db); NUnit.Framework.Assert.AreEqual("tag", walk.ParseTag(tagRef.GetObjectId()).GetTagName ()); }
public virtual void TestCommit() { Git git = new Git(db); revCommit = git.Commit().SetMessage("squash_me").Call(); Ref master = db.GetRef("refs/heads/master"); string message = msgFormatter.Format(Arrays.AsList(revCommit), master); NUnit.Framework.Assert.AreEqual("Squashed commit of the following:\n\ncommit " + revCommit.GetName() + "\nAuthor: " + revCommit.GetAuthorIdent().GetName() + " <" + revCommit.GetAuthorIdent().GetEmailAddress() + ">\nDate: " + dateFormatter. FormatDate(author) + "\n\n\tsquash_me\n", message); }
public virtual void TestEmptyStatus() { Git git = new Git(db); Status stat = git.Status().Call(); NUnit.Framework.Assert.AreEqual(0, stat.GetAdded().Count); NUnit.Framework.Assert.AreEqual(0, stat.GetChanged().Count); NUnit.Framework.Assert.AreEqual(0, stat.GetMissing().Count); NUnit.Framework.Assert.AreEqual(0, stat.GetModified().Count); NUnit.Framework.Assert.AreEqual(0, stat.GetRemoved().Count); NUnit.Framework.Assert.AreEqual(0, stat.GetUntracked().Count); }
public override void SetUp() { base.SetUp(); Git git = new Git(db); git.Commit().SetMessage("initial commit").Call(); WriteTrashFile("Test.txt", "Hello world"); git.Add().AddFilepattern("Test.txt").Call(); git.Commit().SetMessage("Initial commit").Call(); bareRepo = Git.CloneRepository().SetBare(true).SetURI(db.Directory.ToURI().ToString ()).SetDirectory(CreateUniqueTestGitDir(true)).Call().GetRepository(); }
public static IEnumerable <DiffEntry> CompareCommits(NGit.Repository repo, AnyObjectId reference, ObjectId compared) { var diff = new NGit.Api.Git(repo).Diff(); var firstTree = new CanonicalTreeParser(); firstTree.Reset(repo.NewObjectReader(), new RevWalk(repo).ParseTree(reference)); var secondTree = new CanonicalTreeParser(); secondTree.Reset(repo.NewObjectReader(), new RevWalk(repo).ParseTree(compared)); diff.SetNewTree(firstTree); if (compared != ObjectId.ZeroId) { diff.SetOldTree(secondTree); } return(diff.Call()); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="NGit.Api.Errors.GitAPIException"></exception> private RebaseResult InitFilesAndRewind() { // we need to store everything into files so that we can implement // --skip, --continue, and --abort Ref head = repo.GetRef(Constants.HEAD); if (head == null || head.GetObjectId() == null) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved , Constants.HEAD)); } string headName; if (head.IsSymbolic()) { headName = head.GetTarget().GetName(); } else { headName = "detached HEAD"; } ObjectId headId = head.GetObjectId(); if (headId == null) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved , Constants.HEAD)); } RevCommit headCommit = walk.LookupCommit(headId); RevCommit upstream = walk.LookupCommit(upstreamCommit.Id); if (walk.IsMergedInto(upstream, headCommit)) { return(RebaseResult.UP_TO_DATE_RESULT); } else { if (walk.IsMergedInto(headCommit, upstream)) { // head is already merged into upstream, fast-foward monitor.BeginTask(MessageFormat.Format(JGitText.Get().resettingHead, upstreamCommit .GetShortMessage()), ProgressMonitor.UNKNOWN); CheckoutCommit(upstreamCommit); monitor.EndTask(); UpdateHead(headName, upstreamCommit); return(RebaseResult.FAST_FORWARD_RESULT); } } monitor.BeginTask(JGitText.Get().obtainingCommitsForCherryPick, ProgressMonitor.UNKNOWN ); // determine the commits to be applied LogCommand cmd = new Git(repo).Log().AddRange(upstreamCommit, headCommit); Iterable <RevCommit> commitsToUse = cmd.Call(); IList <RevCommit> cherryPickList = new AList <RevCommit>(); foreach (RevCommit commit in commitsToUse) { if (commit.ParentCount != 1) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().canOnlyCherryPickCommitsWithOneParent , commit.Name, Sharpen.Extensions.ValueOf(commit.ParentCount))); } cherryPickList.AddItem(commit); } Sharpen.Collections.Reverse(cherryPickList); // create the folder for the meta information FileUtils.Mkdir(rebaseDir); repo.WriteOrigHead(headId); CreateFile(rebaseDir, REBASE_HEAD, headId.Name); CreateFile(rebaseDir, HEAD_NAME, headName); CreateFile(rebaseDir, ONTO, upstreamCommit.Name); CreateFile(rebaseDir, INTERACTIVE, string.Empty); BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream (new FilePath(rebaseDir, GIT_REBASE_TODO)), Constants.CHARACTER_ENCODING)); fw.Write("# Created by EGit: rebasing " + upstreamCommit.Name + " onto " + headId .Name); fw.NewLine(); try { StringBuilder sb = new StringBuilder(); ObjectReader reader = walk.GetObjectReader(); foreach (RevCommit commit_1 in cherryPickList) { sb.Length = 0; sb.Append(RebaseCommand.Action.PICK.ToToken()); sb.Append(" "); sb.Append(reader.Abbreviate(commit_1).Name); sb.Append(" "); sb.Append(commit_1.GetShortMessage()); fw.Write(sb.ToString()); fw.NewLine(); } } finally { fw.Close(); } monitor.EndTask(); // we rewind to the upstream commit monitor.BeginTask(MessageFormat.Format(JGitText.Get().rewinding, upstreamCommit.GetShortMessage ()), ProgressMonitor.UNKNOWN); bool checkoutOk = false; try { checkoutOk = CheckoutCommit(upstreamCommit); } finally { if (!checkoutOk) { FileUtils.Delete(rebaseDir, FileUtils.RECURSIVE); } } monitor.EndTask(); return(null); }
public static MergeCommandResult MergeTrees(ProgressMonitor monitor, NGit.Repository repo, RevCommit srcBase, RevCommit srcCommit, string sourceDisplayName, bool commitResult) { RevCommit newHead; RevWalk revWalk = new RevWalk(repo); try { // get the head commit Ref headRef = repo.GetRef(Constants.HEAD); if (headRef == null) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId()); ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger (repo)); merger.SetWorkingTreeIterator(new FileTreeIterator(repo)); merger.SetBase(srcBase); bool noProblems; IDictionary <string, MergeResult <Sequence> > lowLevelResults = null; IDictionary <string, ResolveMerger.MergeFailureReason> failingPaths = null; IList <string> modifiedFiles = null; ResolveMerger resolveMerger = merger; resolveMerger.SetCommitNames(new string[] { "BASE", "HEAD", sourceDisplayName }); noProblems = merger.Merge(headCommit, srcCommit); lowLevelResults = resolveMerger.GetMergeResults(); modifiedFiles = resolveMerger.GetModifiedFiles(); failingPaths = resolveMerger.GetFailingPaths(); if (monitor != null) { monitor.Update(50); } if (noProblems) { if (modifiedFiles != null && modifiedFiles.Count == 0) { return(new MergeCommandResult(headCommit, null, new ObjectId[] { headCommit.Id, srcCommit .Id }, MergeStatus.ALREADY_UP_TO_DATE, MergeStrategy.RESOLVE, null, null)); } DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache (), merger.GetResultTreeId()); dco.SetFailOnConflict(true); dco.Checkout(); if (commitResult) { newHead = new NGit.Api.Git(repo).Commit().SetMessage(srcCommit.GetFullMessage() ).SetAuthor(srcCommit.GetAuthorIdent()).Call(); return(new MergeCommandResult(newHead.Id, null, new ObjectId[] { headCommit.Id, srcCommit .Id }, MergeStatus.MERGED, MergeStrategy.RESOLVE, null, null)); } else { return(new MergeCommandResult(headCommit, null, new ObjectId[] { headCommit.Id, srcCommit .Id }, MergeStatus.MERGED, MergeStrategy.RESOLVE, null, null)); } } else { if (failingPaths != null) { return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] { headCommit.Id, srcCommit.Id }, MergeStatus.FAILED, MergeStrategy.RESOLVE, lowLevelResults , failingPaths, null)); } else { return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] { headCommit.Id, srcCommit.Id }, MergeStatus.CONFLICTING, MergeStrategy.RESOLVE, lowLevelResults , null)); } } } finally { revWalk.Release(); } }
public virtual void CommitSubmoduleUpdate() { Git git = new Git(db); WriteTrashFile("file.txt", "content"); git.Add().AddFilepattern("file.txt").Call(); RevCommit commit = git.Commit().SetMessage("create file").Call(); WriteTrashFile("file.txt", "content2"); git.Add().AddFilepattern("file.txt").Call(); RevCommit commit2 = git.Commit().SetMessage("edit file").Call(); SubmoduleAddCommand command = new SubmoduleAddCommand(db); string path = "sub"; command.SetPath(path); string uri = db.Directory.ToURI().ToString(); command.SetURI(uri); Repository repo = command.Call(); NUnit.Framework.Assert.IsNotNull(repo); AddRepoToClose(repo); SubmoduleWalk generator = SubmoduleWalk.ForIndex(db); NUnit.Framework.Assert.IsTrue(generator.Next()); NUnit.Framework.Assert.AreEqual(path, generator.GetPath()); NUnit.Framework.Assert.AreEqual(commit2, generator.GetObjectId()); NUnit.Framework.Assert.AreEqual(uri, generator.GetModulesUrl()); NUnit.Framework.Assert.AreEqual(path, generator.GetModulesPath()); NUnit.Framework.Assert.AreEqual(uri, generator.GetConfigUrl()); Repository subModRepo = generator.GetRepository(); AddRepoToClose(subModRepo); NUnit.Framework.Assert.IsNotNull(subModRepo); NUnit.Framework.Assert.AreEqual(commit2, repo.Resolve(Constants.HEAD)); RevCommit submoduleAddCommit = git.Commit().SetMessage("submodule add").SetOnly(path ).Call(); NUnit.Framework.Assert.IsNotNull(submoduleAddCommit); RefUpdate update = repo.UpdateRef(Constants.HEAD); update.SetNewObjectId(commit); NUnit.Framework.Assert.AreEqual(RefUpdate.Result.FORCED, update.ForceUpdate()); RevCommit submoduleEditCommit = git.Commit().SetMessage("submodule add").SetOnly( path).Call(); NUnit.Framework.Assert.IsNotNull(submoduleEditCommit); TreeWalk walk = new TreeWalk(db); walk.AddTree(submoduleAddCommit.Tree); walk.AddTree(submoduleEditCommit.Tree); walk.Filter = TreeFilter.ANY_DIFF; IList <DiffEntry> diffs = DiffEntry.Scan(walk); NUnit.Framework.Assert.AreEqual(1, diffs.Count); DiffEntry subDiff = diffs[0]; NUnit.Framework.Assert.AreEqual(FileMode.GITLINK, subDiff.GetOldMode()); NUnit.Framework.Assert.AreEqual(FileMode.GITLINK, subDiff.GetNewMode()); NUnit.Framework.Assert.AreEqual(commit2, subDiff.GetOldId().ToObjectId()); NUnit.Framework.Assert.AreEqual(commit, subDiff.GetNewId().ToObjectId()); NUnit.Framework.Assert.AreEqual(path, subDiff.GetNewPath()); NUnit.Framework.Assert.AreEqual(path, subDiff.GetOldPath()); }
/// <summary> /// Executes the /// <code>commit</code> /// command with all the options and parameters /// collected by the setter methods of this class. Each instance of this /// class should only be used for one invocation of the command (means: one /// call to /// <see cref="Call()">Call()</see> /// ) /// </summary> /// <returns> /// a /// <see cref="NGit.Revwalk.RevCommit">NGit.Revwalk.RevCommit</see> /// object representing the successful commit. /// </returns> /// <exception cref="NGit.Api.Errors.NoHeadException">when called on a git repo without a HEAD reference /// </exception> /// <exception cref="NGit.Api.Errors.NoMessageException">when called without specifying a commit message /// </exception> /// <exception cref="NGit.Errors.UnmergedPathException">when the current index contained unmerged paths (conflicts) /// </exception> /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">when repository is not in the right state for committing /// </exception> /// <exception cref="NGit.Api.Errors.JGitInternalException"> /// a low-level exception of JGit has occurred. The original /// exception can be retrieved by calling /// <see cref="System.Exception.InnerException()">System.Exception.InnerException()</see> /// . Expect only /// <code>IOException's</code> /// to be wrapped. Subclasses of /// <see cref="System.IO.IOException">System.IO.IOException</see> /// (e.g. /// <see cref="NGit.Errors.UnmergedPathException">NGit.Errors.UnmergedPathException</see> /// ) are /// typically not wrapped here but thrown as original exception /// </exception> /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException"></exception> public override RevCommit Call() { CheckCallable(); RepositoryState state = repo.GetRepositoryState(); if (!state.CanCommit()) { throw new WrongRepositoryStateException(MessageFormat.Format(JGitText.Get().cannotCommitOnARepoWithState , state.Name())); } ProcessOptions(state); try { if (all && !repo.IsBare && repo.WorkTree != null) { Git git = new Git(repo); try { git.Add().AddFilepattern(".").SetUpdate(true).Call(); } catch (NoFilepatternException e) { // should really not happen throw new JGitInternalException(e.Message, e); } } Ref head = repo.GetRef(Constants.HEAD); if (head == null) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } // determine the current HEAD and the commit it is referring to ObjectId headId = repo.Resolve(Constants.HEAD + "^{commit}"); if (headId != null) { if (amend) { RevCommit previousCommit = new RevWalk(repo).ParseCommit(headId); RevCommit[] p = previousCommit.Parents; for (int i = 0; i < p.Length; i++) { parents.Add(0, p[i].Id); } } else { parents.Add(0, headId); } } // lock the index DirCache index = repo.LockDirCache(); try { ObjectInserter odi = repo.NewObjectInserter(); try { // Write the index as tree to the object database. This may // fail for example when the index contains unmerged paths // (unresolved conflicts) ObjectId indexTreeId = index.WriteTree(odi); // Create a Commit object, populate it and write it NGit.CommitBuilder commit = new NGit.CommitBuilder(); commit.Committer = committer; commit.Author = author; commit.Message = message; commit.SetParentIds(parents); commit.TreeId = indexTreeId; ObjectId commitId = odi.Insert(commit); odi.Flush(); RevWalk revWalk = new RevWalk(repo); try { RevCommit revCommit = revWalk.ParseCommit(commitId); RefUpdate ru = repo.UpdateRef(Constants.HEAD); ru.SetNewObjectId(commitId); ru.SetRefLogMessage("commit : " + revCommit.GetShortMessage(), false); ru.SetExpectedOldObjectId(headId); RefUpdate.Result rc = ru.ForceUpdate(); switch (rc) { case RefUpdate.Result.NEW: case RefUpdate.Result.FORCED: case RefUpdate.Result.FAST_FORWARD: { SetCallable(false); if (state == RepositoryState.MERGING_RESOLVED) { // Commit was successful. Now delete the files // used for merge commits repo.WriteMergeCommitMsg(null); repo.WriteMergeHeads(null); } return(revCommit); } case RefUpdate.Result.REJECTED: case RefUpdate.Result.LOCK_FAILURE: { throw new ConcurrentRefUpdateException(JGitText.Get().couldNotLockHEAD, ru.GetRef (), rc); } default: { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().updatingRefFailed , Constants.HEAD, commitId.ToString(), rc)); } } } finally { revWalk.Release(); } } finally { odi.Release(); } } finally { index.Unlock(); } } catch (UnmergedPathException e) { // since UnmergedPathException is a subclass of IOException // which should not be wrapped by a JGitInternalException we // have to catch and re-throw it here throw; } catch (IOException e) { throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfCommitCommand , e); } }
private static string GetPatch(string modifiedFile, string originalText, string newText, Git git) { using (var stream = new MemoryStream()) { File.WriteAllText(modifiedFile, newText); git.Diff().SetOutputStream(stream).Call(); File.WriteAllText(modifiedFile, originalText); return(Encoding.ASCII.GetString(stream.ToArray())); } }
/// <summary> /// Executes the /// <code>revert</code> /// command with all the options and parameters /// collected by the setter methods (e.g. /// <see cref="Include(NGit.Ref)">Include(NGit.Ref)</see> /// of this /// class. Each instance of this class should only be used for one invocation /// of the command. Don't call this method twice on an instance. /// </summary> /// <returns> /// on success the /// <see cref="NGit.Revwalk.RevCommit">NGit.Revwalk.RevCommit</see> /// pointed to by the new HEAD is /// returned. If a failure occurred during revert <code>null</code> /// is returned. The list of successfully reverted /// <see cref="NGit.Ref">NGit.Ref</see> /// 's can /// be obtained by calling /// <see cref="GetRevertedRefs()">GetRevertedRefs()</see> /// </returns> /// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public override RevCommit Call() { RevCommit newHead = null; CheckCallable(); RevWalk revWalk = new RevWalk(repo); try { // get the head commit Ref headRef = repo.GetRef(Constants.HEAD); if (headRef == null) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId()); newHead = headCommit; // loop through all refs to be reverted foreach (Ref src in commits) { // get the commit to be reverted // handle annotated tags ObjectId srcObjectId = src.GetPeeledObjectId(); if (srcObjectId == null) { srcObjectId = src.GetObjectId(); } RevCommit srcCommit = revWalk.ParseCommit(srcObjectId); // get the parent of the commit to revert if (srcCommit.ParentCount != 1) { throw new MultipleParentsNotAllowedException(JGitText.Get().canOnlyRevertCommitsWithOneParent ); } RevCommit srcParent = srcCommit.GetParent(0); revWalk.ParseHeaders(srcParent); ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger (repo)); merger.SetWorkingTreeIterator(new FileTreeIterator(repo)); merger.SetBase(srcCommit.Tree); if (merger.Merge(headCommit, srcParent)) { if (AnyObjectId.Equals(headCommit.Tree.Id, merger.GetResultTreeId())) { continue; } DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache (), merger.GetResultTreeId()); dco.SetFailOnConflict(true); dco.Checkout(); string newMessage = "Revert \"" + srcCommit.GetShortMessage() + "\"" + "\n\n" + "This reverts commit " + srcCommit.Id.GetName() + ".\n"; newHead = new Git(GetRepository()).Commit().SetMessage(newMessage).Call(); revertedRefs.AddItem(src); } else { return(null); } } } catch (IOException e) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionCaughtDuringExecutionOfRevertCommand , e), e); } finally { revWalk.Release(); } return(newHead); }
/// <summary> /// Executes the /// <code>Merge</code> /// command with all the options and parameters /// collected by the setter methods (e.g. /// <see cref="Include(NGit.Ref)">Include(NGit.Ref)</see> /// ) of this /// class. Each instance of this class should only be used for one invocation /// of the command. Don't call this method twice on an instance. /// </summary> /// <returns>the result of the merge</returns> /// <exception cref="NGit.Api.Errors.NoHeadException"></exception> /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException"></exception> /// <exception cref="NGit.Api.Errors.CheckoutConflictException"></exception> /// <exception cref="NGit.Api.Errors.InvalidMergeHeadsException"></exception> /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException"></exception> /// <exception cref="NGit.Api.Errors.NoMessageException"></exception> public override MergeCommandResult Call() { CheckCallable(); if (commits.Count != 1) { throw new InvalidMergeHeadsException(commits.IsEmpty() ? JGitText.Get().noMergeHeadSpecified : MessageFormat.Format(JGitText.Get().mergeStrategyDoesNotSupportHeads, mergeStrategy .GetName(), Sharpen.Extensions.ValueOf(commits.Count))); } RevWalk revWalk = null; try { Ref head = repo.GetRef(Constants.HEAD); if (head == null) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } StringBuilder refLogMessage = new StringBuilder("merge "); // Check for FAST_FORWARD, ALREADY_UP_TO_DATE revWalk = new RevWalk(repo); // we know for now there is only one commit Ref @ref = commits[0]; refLogMessage.Append(@ref.GetName()); // handle annotated tags ObjectId objectId = @ref.GetPeeledObjectId(); if (objectId == null) { objectId = @ref.GetObjectId(); } RevCommit srcCommit = revWalk.LookupCommit(objectId); ObjectId headId = head.GetObjectId(); if (headId == null) { revWalk.ParseHeaders(srcCommit); DirCacheCheckout dco = new DirCacheCheckout(repo, repo.LockDirCache(), srcCommit. Tree); dco.SetFailOnConflict(true); dco.Checkout(); RefUpdate refUpdate = repo.UpdateRef(head.GetTarget().GetName()); refUpdate.SetNewObjectId(objectId); refUpdate.SetExpectedOldObjectId(null); refUpdate.SetRefLogMessage("initial pull", false); if (refUpdate.Update() != RefUpdate.Result.NEW) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } SetCallable(false); return(new MergeCommandResult(srcCommit, srcCommit, new ObjectId[] { null, srcCommit }, MergeStatus.FAST_FORWARD, mergeStrategy, null, null)); } RevCommit headCommit = revWalk.LookupCommit(headId); if (revWalk.IsMergedInto(srcCommit, headCommit)) { SetCallable(false); return(new MergeCommandResult(headCommit, srcCommit, new ObjectId[] { headCommit, srcCommit }, MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null, null)); } else { if (revWalk.IsMergedInto(headCommit, srcCommit)) { // FAST_FORWARD detected: skip doing a real merge but only // update HEAD refLogMessage.Append(": " + MergeStatus.FAST_FORWARD); DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache (), srcCommit.Tree); dco.SetFailOnConflict(true); dco.Checkout(); UpdateHead(refLogMessage, srcCommit, headId); SetCallable(false); return(new MergeCommandResult(srcCommit, srcCommit, new ObjectId[] { headCommit, srcCommit }, MergeStatus.FAST_FORWARD, mergeStrategy, null, null)); } else { string mergeMessage = new MergeMessageFormatter().Format(commits, head); repo.WriteMergeCommitMsg(mergeMessage); repo.WriteMergeHeads(Arrays.AsList(@ref.GetObjectId())); ThreeWayMerger merger = (ThreeWayMerger)mergeStrategy.NewMerger(repo); bool noProblems; IDictionary <string, MergeResult <NGit.Diff.Sequence> > lowLevelResults = null; IDictionary <string, ResolveMerger.MergeFailureReason> failingPaths = null; IList <string> unmergedPaths = null; if (merger is ResolveMerger) { ResolveMerger resolveMerger = (ResolveMerger)merger; resolveMerger.SetCommitNames(new string[] { "BASE", "HEAD", @ref.GetName() }); resolveMerger.SetWorkingTreeIterator(new FileTreeIterator(repo)); noProblems = merger.Merge(headCommit, srcCommit); lowLevelResults = resolveMerger.GetMergeResults(); failingPaths = resolveMerger.GetFailingPaths(); unmergedPaths = resolveMerger.GetUnmergedPaths(); } else { noProblems = merger.Merge(headCommit, srcCommit); } if (noProblems) { DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache (), merger.GetResultTreeId()); dco.SetFailOnConflict(true); dco.Checkout(); RevCommit newHead = new Git(GetRepository()).Commit().Call(); return(new MergeCommandResult(newHead.Id, null, new ObjectId[] { headCommit.Id, srcCommit .Id }, MergeStatus.MERGED, mergeStrategy, null, null)); } else { if (failingPaths != null) { repo.WriteMergeCommitMsg(null); repo.WriteMergeHeads(null); return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] { headCommit.Id, srcCommit.Id }, MergeStatus.FAILED, mergeStrategy, lowLevelResults , failingPaths, null)); } else { string mergeMessageWithConflicts = new MergeMessageFormatter().FormatWithConflicts (mergeMessage, unmergedPaths); repo.WriteMergeCommitMsg(mergeMessageWithConflicts); return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] { headCommit.Id, srcCommit.Id }, MergeStatus.CONFLICTING, mergeStrategy, lowLevelResults , null)); } } } } } catch (IOException e) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionCaughtDuringExecutionOfMergeCommand , e), e); } finally { if (revWalk != null) { revWalk.Release(); } } }
/// <summary> /// Executes the /// <code>Rebase</code> /// command with all the options and parameters /// collected by the setter methods of this class. Each instance of this /// class should only be used for one invocation of the command. Don't call /// this method twice on an instance. /// </summary> /// <returns>an object describing the result of this command</returns> /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException /// </exception> /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">NGit.Api.Errors.WrongRepositoryStateException /// </exception> /// <exception cref="NGit.Api.Errors.NoHeadException">NGit.Api.Errors.NoHeadException /// </exception> /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException /// </exception> public override RebaseResult Call() { RevCommit newHead = null; bool lastStepWasForward = false; CheckCallable(); CheckParameters(); try { switch (operation) { case RebaseCommand.Operation.ABORT: { try { return(Abort(RebaseResult.ABORTED_RESULT)); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } goto case RebaseCommand.Operation.SKIP; } case RebaseCommand.Operation.SKIP: case RebaseCommand.Operation.CONTINUE: { // fall through string upstreamCommitName = ReadFile(rebaseDir, ONTO); this.upstreamCommit = walk.ParseCommit(repo.Resolve(upstreamCommitName)); break; } case RebaseCommand.Operation.BEGIN: { RebaseResult res = InitFilesAndRewind(); if (res != null) { return(res); } break; } } if (monitor.IsCancelled()) { return(Abort(RebaseResult.ABORTED_RESULT)); } if (operation == RebaseCommand.Operation.CONTINUE) { newHead = ContinueRebase(); if (newHead == null) { // continueRebase() returns null only if no commit was // neccessary. This means that no changes where left over // after resolving all conflicts. In this case, cgit stops // and displays a nice message to the user, telling him to // either do changes or skip the commit instead of continue. return(RebaseResult.NOTHING_TO_COMMIT_RESULT); } } if (operation == RebaseCommand.Operation.SKIP) { newHead = CheckoutCurrentHead(); } ObjectReader or = repo.NewObjectReader(); IList <RebaseCommand.Step> steps = LoadSteps(); foreach (RebaseCommand.Step step in steps) { PopSteps(1); ICollection <ObjectId> ids = or.Resolve(step.commit); if (ids.Count != 1) { throw new JGitInternalException("Could not resolve uniquely the abbreviated object ID" ); } RevCommit commitToPick = walk.ParseCommit(ids.Iterator().Next()); if (monitor.IsCancelled()) { return(new RebaseResult(commitToPick)); } try { monitor.BeginTask(MessageFormat.Format(JGitText.Get().applyingCommit, commitToPick .GetShortMessage()), ProgressMonitor.UNKNOWN); // if the first parent of commitToPick is the current HEAD, // we do a fast-forward instead of cherry-pick to avoid // unnecessary object rewriting newHead = TryFastForward(commitToPick); lastStepWasForward = newHead != null; if (!lastStepWasForward) { // TODO if the content of this commit is already merged // here we should skip this step in order to avoid // confusing pseudo-changed CherryPickResult cherryPickResult = new Git(repo).CherryPick().Include(commitToPick ).Call(); switch (cherryPickResult.GetStatus()) { case CherryPickResult.CherryPickStatus.FAILED: { if (operation == RebaseCommand.Operation.BEGIN) { return(Abort(new RebaseResult(cherryPickResult.GetFailingPaths()))); } else { return(Stop(commitToPick)); } goto case CherryPickResult.CherryPickStatus.CONFLICTING; } case CherryPickResult.CherryPickStatus.CONFLICTING: { return(Stop(commitToPick)); } case CherryPickResult.CherryPickStatus.OK: { newHead = cherryPickResult.GetNewHead(); break; } } } } finally { monitor.EndTask(); } } if (newHead != null) { string headName = ReadFile(rebaseDir, HEAD_NAME); UpdateHead(headName, newHead); FileUtils.Delete(rebaseDir, FileUtils.RECURSIVE); if (lastStepWasForward) { return(RebaseResult.FAST_FORWARD_RESULT); } return(RebaseResult.OK_RESULT); } return(RebaseResult.FAST_FORWARD_RESULT); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } }
public virtual void TestListAllBranchesShouldNotDie() { Git git = SetUpRepoWithRemote(); git.BranchList().SetListMode(ListBranchCommand.ListMode.ALL).Call(); }
/// <summary> /// Executes the /// <code>Cherry-Pick</code> /// command with all the options and /// parameters collected by the setter methods (e.g. /// <see cref="Include(NGit.Ref)">Include(NGit.Ref)</see> /// of /// this class. Each instance of this class should only be used for one /// invocation of the command. Don't call this method twice on an instance. /// </summary> /// <returns>the result of the cherry-pick</returns> /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException /// </exception> /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">NGit.Api.Errors.WrongRepositoryStateException /// </exception> /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException">NGit.Api.Errors.ConcurrentRefUpdateException /// </exception> /// <exception cref="NGit.Api.Errors.UnmergedPathsException">NGit.Api.Errors.UnmergedPathsException /// </exception> /// <exception cref="NGit.Api.Errors.NoMessageException">NGit.Api.Errors.NoMessageException /// </exception> /// <exception cref="NGit.Api.Errors.NoHeadException">NGit.Api.Errors.NoHeadException /// </exception> public override CherryPickResult Call() { RevCommit newHead = null; IList <Ref> cherryPickedRefs = new List <Ref>(); CheckCallable(); RevWalk revWalk = new RevWalk(repo); try { // get the head commit Ref headRef = repo.GetRef(Constants.HEAD); if (headRef == null) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId()); newHead = headCommit; // loop through all refs to be cherry-picked foreach (Ref src in commits) { // get the commit to be cherry-picked // handle annotated tags ObjectId srcObjectId = src.GetPeeledObjectId(); if (srcObjectId == null) { srcObjectId = src.GetObjectId(); } RevCommit srcCommit = revWalk.ParseCommit(srcObjectId); // get the parent of the commit to cherry-pick if (srcCommit.ParentCount != 1) { throw new MultipleParentsNotAllowedException(MessageFormat.Format(JGitText.Get(). canOnlyCherryPickCommitsWithOneParent, srcCommit.Name, Sharpen.Extensions.ValueOf (srcCommit.ParentCount))); } RevCommit srcParent = srcCommit.GetParent(0); revWalk.ParseHeaders(srcParent); ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger (repo)); merger.SetWorkingTreeIterator(new FileTreeIterator(repo)); merger.SetBase(srcParent.Tree); if (merger.Merge(headCommit, srcCommit)) { if (AnyObjectId.Equals(headCommit.Tree.Id, merger.GetResultTreeId())) { continue; } DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache (), merger.GetResultTreeId()); dco.SetFailOnConflict(true); dco.Checkout(); newHead = new Git(GetRepository()).Commit().SetMessage(srcCommit.GetFullMessage() ).SetReflogComment("cherry-pick: " + srcCommit.GetShortMessage()).SetAuthor(srcCommit .GetAuthorIdent()).Call(); cherryPickedRefs.AddItem(src); } else { if (merger.Failed()) { return(new CherryPickResult(merger.GetFailingPaths())); } // there are merge conflicts string message = new MergeMessageFormatter().FormatWithConflicts(srcCommit.GetFullMessage (), merger.GetUnmergedPaths()); repo.WriteCherryPickHead(srcCommit.Id); repo.WriteMergeCommitMsg(message); return(CherryPickResult.CONFLICT); } } } catch (IOException e) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionCaughtDuringExecutionOfCherryPickCommand , e), e); } finally { revWalk.Release(); } return(new CherryPickResult(newHead, cherryPickedRefs)); }
/// <exception cref="NGit.Api.Errors.RefAlreadyExistsException"> /// when trying to create (without force) a branch with a name /// that already exists /// </exception> /// <exception cref="NGit.Api.Errors.RefNotFoundException">if the start point or branch can not be found /// </exception> /// <exception cref="NGit.Api.Errors.InvalidRefNameException"> /// if the provided name is <code>null</code> or otherwise /// invalid /// </exception> /// <returns>the newly created branch</returns> /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception> public override Ref Call() { CheckCallable(); ProcessOptions(); try { if (!paths.IsEmpty()) { CheckoutPaths(); status = CheckoutResult.OK_RESULT; SetCallable(false); return(null); } if (createBranch) { Git git = new Git(repo); CreateBranchCommand command = git.BranchCreate(); command.SetName(name); command.SetStartPoint(GetStartPoint().Name); if (upstreamMode != null) { command.SetUpstreamMode(upstreamMode); } command.Call(); } Ref headRef = repo.GetRef(Constants.HEAD); string refLogMessage = "checkout: moving from " + headRef.GetTarget().GetName(); ObjectId branch = repo.Resolve(name); if (branch == null) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved , name)); } RevWalk revWalk = new RevWalk(repo); AnyObjectId headId = headRef.GetObjectId(); RevCommit headCommit = headId == null ? null : revWalk.ParseCommit(headId); RevCommit newCommit = revWalk.ParseCommit(branch); RevTree headTree = headCommit == null ? null : headCommit.Tree; DirCacheCheckout dco = new DirCacheCheckout(repo, headTree, repo.LockDirCache(), newCommit.Tree); dco.SetFailOnConflict(true); try { dco.Checkout(); } catch (NGit.Errors.CheckoutConflictException e) { status = new CheckoutResult(CheckoutResult.Status.CONFLICTS, dco.GetConflicts()); throw; } Ref @ref = repo.GetRef(name); if (@ref != null && [email protected]().StartsWith(Constants.R_HEADS)) { @ref = null; } RefUpdate refUpdate = repo.UpdateRef(Constants.HEAD, @ref == null); refUpdate.SetForceUpdate(force); refUpdate.SetRefLogMessage(refLogMessage + " to " + newCommit.GetName(), false); RefUpdate.Result updateResult; if (@ref != null) { updateResult = refUpdate.Link(@ref.GetName()); } else { refUpdate.SetNewObjectId(newCommit); updateResult = refUpdate.ForceUpdate(); } SetCallable(false); bool ok = false; switch (updateResult) { case RefUpdate.Result.NEW: { ok = true; break; } case RefUpdate.Result.NO_CHANGE: case RefUpdate.Result.FAST_FORWARD: case RefUpdate.Result.FORCED: { ok = true; break; } default: { break; break; } } if (!ok) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().checkoutUnexpectedResult , updateResult.ToString())); } if (!dco.GetToBeDeleted().IsEmpty()) { status = new CheckoutResult(CheckoutResult.Status.NONDELETED, dco.GetToBeDeleted( )); } else { status = CheckoutResult.OK_RESULT; } return(@ref); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } finally { if (status == null) { status = CheckoutResult.ERROR_RESULT; } } }
/// <exception cref="System.Exception"></exception> public virtual void CommitAmendOnInitialShouldFail() { Git git = new Git(db); git.Commit().SetAmend(true).SetMessage("initial commit").Call(); }
/// <summary>Execute the SubmoduleUpdateCommand command.</summary> /// <remarks>Execute the SubmoduleUpdateCommand command.</remarks> /// <returns>a collection of updated submodule paths</returns> /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException">NGit.Api.Errors.ConcurrentRefUpdateException /// </exception> /// <exception cref="NGit.Api.Errors.CheckoutConflictException">NGit.Api.Errors.CheckoutConflictException /// </exception> /// <exception cref="NGit.Api.Errors.InvalidMergeHeadsException">NGit.Api.Errors.InvalidMergeHeadsException /// </exception> /// <exception cref="NGit.Api.Errors.InvalidConfigurationException">NGit.Api.Errors.InvalidConfigurationException /// </exception> /// <exception cref="NGit.Api.Errors.NoHeadException">NGit.Api.Errors.NoHeadException /// </exception> /// <exception cref="NGit.Api.Errors.NoMessageException">NGit.Api.Errors.NoMessageException /// </exception> /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException /// </exception> /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">NGit.Api.Errors.WrongRepositoryStateException /// </exception> /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException /// </exception> public override ICollection <string> Call() { CheckCallable(); try { SubmoduleWalk generator = SubmoduleWalk.ForIndex(repo); if (!paths.IsEmpty()) { generator.SetFilter(PathFilterGroup.CreateFromStrings(paths)); } IList <string> updated = new AList <string>(); while (generator.Next()) { // Skip submodules not registered in .gitmodules file if (generator.GetModulesPath() == null) { continue; } // Skip submodules not registered in parent repository's config string url = generator.GetConfigUrl(); if (url == null) { continue; } Repository submoduleRepo = generator.GetRepository(); // Clone repository is not present if (submoduleRepo == null) { CloneCommand clone = Git.CloneRepository(); Configure(clone); clone.SetURI(url); clone.SetDirectory(generator.GetDirectory()); if (monitor != null) { clone.SetProgressMonitor(monitor); } submoduleRepo = clone.Call().GetRepository(); } try { RevWalk walk = new RevWalk(submoduleRepo); RevCommit commit = walk.ParseCommit(generator.GetObjectId()); string update = generator.GetConfigUpdate(); if (ConfigConstants.CONFIG_KEY_MERGE.Equals(update)) { MergeCommand merge = new MergeCommand(submoduleRepo); merge.Include(commit); merge.Call(); } else { if (ConfigConstants.CONFIG_KEY_REBASE.Equals(update)) { RebaseCommand rebase = new RebaseCommand(submoduleRepo); rebase.SetUpstream(commit); rebase.Call(); } else { // Checkout commit referenced in parent repository's // index as a detached HEAD DirCacheCheckout co = new DirCacheCheckout(submoduleRepo, submoduleRepo.LockDirCache (), commit.Tree); co.SetFailOnConflict(true); co.Checkout(); RefUpdate refUpdate = submoduleRepo.UpdateRef(Constants.HEAD, true); refUpdate.SetNewObjectId(commit); refUpdate.ForceUpdate(); } } } finally { submoduleRepo.Close(); } updated.AddItem(generator.GetPath()); } return(updated); } catch (IOException e) { throw new JGitInternalException(e.Message, e); } catch (ConfigInvalidException e) { throw new InvalidConfigurationException(e.Message, e); } }