/// <summary>Core validation to be performed on all stashed commits</summary> /// <param name="commit"></param> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> private void ValidateStashedCommit(RevCommit commit) { NUnit.Framework.Assert.IsNotNull(commit); Ref stashRef = db.GetRef(Constants.R_STASH); NUnit.Framework.Assert.IsNotNull(stashRef); NUnit.Framework.Assert.AreEqual(commit, stashRef.GetObjectId()); NUnit.Framework.Assert.IsNotNull(commit.GetAuthorIdent()); NUnit.Framework.Assert.AreEqual(commit.GetAuthorIdent(), commit.GetCommitterIdent ()); NUnit.Framework.Assert.AreEqual(2, commit.ParentCount); // Load parents RevWalk walk = new RevWalk(db); try { foreach (RevCommit parent in commit.Parents) { walk.ParseBody(parent); } } finally { walk.Release(); } NUnit.Framework.Assert.AreEqual(1, commit.GetParent(1).ParentCount); NUnit.Framework.Assert.AreEqual(head, commit.GetParent(1).GetParent(0)); NUnit.Framework.Assert.IsFalse(commit.Tree.Equals(head.Tree), "Head tree matches stashed commit tree" ); NUnit.Framework.Assert.AreEqual(head, commit.GetParent(0)); NUnit.Framework.Assert.IsFalse(commit.GetFullMessage().Equals(commit.GetParent(1) .GetFullMessage())); }
public virtual void TestSuccessfulContentMergeAndDirtyworkingTree() { Git git = new Git(db); WriteTrashFile("a", "1\na\n3\n"); WriteTrashFile("b", "1\nb\n3\n"); WriteTrashFile("d", "1\nd\n3\n"); WriteTrashFile("c/c/c", "1\nc\n3\n"); git.Add().AddFilepattern("a").AddFilepattern("b").AddFilepattern("c/c/c").AddFilepattern ("d").Call(); RevCommit initialCommit = git.Commit().SetMessage("initial").Call(); CreateBranch(initialCommit, "refs/heads/side"); CheckoutBranch("refs/heads/side"); WriteTrashFile("a", "1(side)\na\n3\n"); WriteTrashFile("b", "1\nb(side)\n3\n"); git.Add().AddFilepattern("a").AddFilepattern("b").Call(); RevCommit secondCommit = git.Commit().SetMessage("side").Call(); NUnit.Framework.Assert.AreEqual("1\nb(side)\n3\n", Read(new FilePath(db.WorkTree, "b"))); CheckoutBranch("refs/heads/master"); NUnit.Framework.Assert.AreEqual("1\nb\n3\n", Read(new FilePath(db.WorkTree, "b")) ); WriteTrashFile("a", "1\na\n3(main)\n"); WriteTrashFile("c/c/c", "1\nc(main)\n3\n"); git.Add().AddFilepattern("a").AddFilepattern("c/c/c").Call(); RevCommit thirdCommit = git.Commit().SetMessage("main").Call(); WriteTrashFile("d", "--- dirty ---"); MergeCommandResult result = git.Merge().Include(secondCommit.Id).SetStrategy(MergeStrategy .RESOLVE).Call(); NUnit.Framework.Assert.AreEqual(MergeStatus.MERGED, result.GetMergeStatus()); NUnit.Framework.Assert.AreEqual("1(side)\na\n3(main)\n", Read(new FilePath(db.WorkTree , "a"))); NUnit.Framework.Assert.AreEqual("1\nb(side)\n3\n", Read(new FilePath(db.WorkTree, "b"))); NUnit.Framework.Assert.AreEqual("1\nc(main)\n3\n", Read(new FilePath(db.WorkTree, "c/c/c"))); NUnit.Framework.Assert.AreEqual("--- dirty ---", Read(new FilePath(db.WorkTree, "d" ))); NUnit.Framework.Assert.AreEqual(null, result.GetConflicts()); NUnit.Framework.Assert.IsTrue(2 == result.GetMergedCommits().Length); NUnit.Framework.Assert.AreEqual(thirdCommit, result.GetMergedCommits()[0]); NUnit.Framework.Assert.AreEqual(secondCommit, result.GetMergedCommits()[1]); Iterator <RevCommit> it = git.Log().Call().Iterator(); RevCommit newHead = it.Next(); NUnit.Framework.Assert.AreEqual(newHead, result.GetNewHead()); NUnit.Framework.Assert.AreEqual(2, newHead.ParentCount); NUnit.Framework.Assert.AreEqual(thirdCommit, newHead.GetParent(0)); NUnit.Framework.Assert.AreEqual(secondCommit, newHead.GetParent(1)); NUnit.Framework.Assert.AreEqual("Merge commit '064d54d98a4cdb0fed1802a21c656bfda67fe879'" , newHead.GetFullMessage()); NUnit.Framework.Assert.AreEqual(RepositoryState.SAFE, db.GetRepositoryState()); }
/// <exception cref="System.IO.IOException"></exception> private IList <DiffEntry> DiffIndexAgainstHead(RevCommit commit) { TreeWalk walk = CreateTreeWalk(); try { walk.AddTree(commit.GetParent(0).Tree); walk.AddTree(commit.GetParent(1).Tree); return(DiffEntry.Scan(walk)); } finally { walk.Release(); } }
public virtual void WorkingDirectoryDeleteIndexEdit() { FilePath edited = WriteTrashFile("file.txt", "content2"); git.Add().AddFilepattern("file.txt").Call(); FileUtils.Delete(edited); NUnit.Framework.Assert.IsFalse(edited.Exists()); RevCommit stashed = Git.Wrap(db).StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.AreEqual("content", Read(committedFile)); ValidateStashedCommit(stashed); NUnit.Framework.Assert.IsFalse(stashed.Tree.Equals(stashed.GetParent(1).Tree)); IList <DiffEntry> workingDiffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, workingDiffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.DELETE, workingDiffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("file.txt", workingDiffs[0].GetOldPath()); IList <DiffEntry> indexDiffs = DiffIndexAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, indexDiffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, indexDiffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("file.txt", indexDiffs[0].GetNewPath()); NUnit.Framework.Assert.AreEqual(workingDiffs[0].GetOldId(), indexDiffs[0].GetOldId ()); NUnit.Framework.Assert.IsFalse(workingDiffs[0].GetNewId().Equals(indexDiffs[0].GetNewId ())); }
public void testStringOfPearls_FilePath3() { RevCommit a = Commit(tree(File("d/f", blob("a")))); RevCommit b = Commit(tree(File("d/f", blob("a"))), a); RevCommit c = Commit(tree(File("d/f", blob("b"))), b); RevCommit d = Commit(tree(File("d/f", blob("b"))), c); RevCommit e = Commit(tree(File("d/f", blob("b"))), d); RevCommit f = Commit(tree(File("d/f", blob("b"))), e); RevCommit g = Commit(tree(File("d/f", blob("b"))), f); RevCommit h = Commit(tree(File("d/f", blob("b"))), g); RevCommit i = Commit(tree(File("d/f", blob("c"))), h); filter("d/f"); MarkStart(i); AssertCommit(i, rw.next()); Assert.AreEqual(1, i.ParentCount); AssertCommit(c, i.GetParent(0)); // h..d was skipped AssertCommit(c, rw.next()); Assert.AreEqual(1, c.ParentCount); AssertCommit(a, c.GetParent(0)); // b was skipped AssertCommit(a, rw.next()); Assert.AreEqual(0, a.ParentCount); Assert.IsNull(rw.next()); }
protected void OnButtonBranchClicked(object sender, System.EventArgs e) { Stash s = GetSelected(); if (s != null) { var dlg = new EditBranchDialog(repository, null, true); try { if (MessageService.RunCustomDialog(dlg) == (int)ResponseType.Ok) { ObjectId commit = repository.RootRepository.Resolve(s.CommitId); var rw = new RevWalk(repository.RootRepository); RevCommit c = rw.ParseCommit(commit); RevCommit old = c.GetParent(0); rw.ParseHeaders(old); repository.CreateBranchFromCommit(dlg.BranchName, old); GitService.SwitchToBranch(repository, dlg.BranchName); ApplyStashAndRemove(s); } } finally { dlg.Destroy(); } Respond(ResponseType.Ok); } }
public virtual void WorkingDirectoryDeleteIndexAdd() { string path = "file2.txt"; FilePath added = WriteTrashFile(path, "content2"); NUnit.Framework.Assert.IsTrue(added.Exists()); git.Add().AddFilepattern(path).Call(); FileUtils.Delete(added); NUnit.Framework.Assert.IsFalse(added.Exists()); RevCommit stashed = Git.Wrap(db).StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.IsFalse(added.Exists()); ValidateStashedCommit(stashed); NUnit.Framework.Assert.IsTrue(stashed.Tree.Equals(stashed.GetParent(1).Tree)); IList <DiffEntry> workingDiffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, workingDiffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.ADD, workingDiffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual(path, workingDiffs[0].GetNewPath()); IList <DiffEntry> indexDiffs = DiffIndexAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, indexDiffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.ADD, indexDiffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual(path, indexDiffs[0].GetNewPath()); NUnit.Framework.Assert.AreEqual(workingDiffs[0].GetOldId(), indexDiffs[0].GetOldId ()); NUnit.Framework.Assert.IsTrue(workingDiffs[0].GetNewId().Equals(indexDiffs[0].GetNewId ())); }
public virtual void WorkingDirectoryCleanIndexModify() { WriteTrashFile("file.txt", "content2"); git.Add().AddFilepattern("file.txt").Call(); WriteTrashFile("file.txt", "content"); RevCommit stashed = Git.Wrap(db).StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.AreEqual("content", Read(committedFile)); ValidateStashedCommit(stashed); NUnit.Framework.Assert.AreEqual(stashed.GetParent(1).Tree, stashed.Tree); IList <DiffEntry> workingDiffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, workingDiffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, workingDiffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("file.txt", workingDiffs[0].GetNewPath()); IList <DiffEntry> indexDiffs = DiffIndexAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, indexDiffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, indexDiffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("file.txt", indexDiffs[0].GetNewPath()); NUnit.Framework.Assert.AreEqual(workingDiffs[0].GetOldId(), indexDiffs[0].GetOldId ()); NUnit.Framework.Assert.IsTrue(workingDiffs[0].GetNewId().Equals(indexDiffs[0].GetNewId ())); }
public const string BaseFileForDependency = "CatalogController.cs";// "defaultResources.nopres.xml"; public static string GetCommitDiff(Repository repository, Git git, RevCommit rev, String file) { string snapshotN = GetSnapshot(repository, git, rev.GetParent(0).Tree, file); string snapshotNPlusOne = GetSnapshot(repository, git, rev.Tree, file); //Fetch diffrence of commit OutputStream @out = new ByteArrayOutputStream(); DiffCommand diff = git.Diff().SetPathFilter(PathFilter.Create(file)).SetOldTree(GetTreeIterator(rev.GetParent(0).Tree.Name, repository)).SetNewTree(GetTreeIterator(rev.Tree.Name, repository)).SetOutputStream(@out); IList <DiffEntry> entries = diff.Call(); return(@out.ToString()); }
public virtual void TestStopOnConflictCommitAndContinue() { // create file1 on master RevCommit firstInMaster = WriteFileAndCommit(FILE1, "Add file1", "1", "2", "3"); // change in master WriteFileAndCommit(FILE1, "change file1 in master", "1master", "2", "3"); CheckFile(FILE1, "1master", "2", "3"); // create a topic branch based on the first commit CreateBranch(firstInMaster, "refs/heads/topic"); CheckoutBranch("refs/heads/topic"); // we have the old content again CheckFile(FILE1, "1", "2", "3"); // add a line (non-conflicting) WriteFileAndCommit(FILE1, "add a line to file1 in topic", "1", "2", "3", "4topic" ); // change first line (conflicting) WriteFileAndCommit(FILE1, "change file1 in topic\n\nThis is conflicting", "1topic" , "2", "3", "4topic"); // change second line (not conflicting) WriteFileAndCommit(FILE1, "change file1 in topic again", "1topic", "2", "3topic", "4topic"); RebaseResult res = git.Rebase().SetUpstream("refs/heads/master").Call(); NUnit.Framework.Assert.AreEqual(RebaseResult.Status.STOPPED, res.GetStatus()); // continue should throw a meaningful exception try { res = git.Rebase().SetOperation(RebaseCommand.Operation.CONTINUE).Call(); NUnit.Framework.Assert.Fail("Expected Exception not thrown"); } catch (UnmergedPathsException) { } // expected // merge the file; the second topic commit should go through WriteFileAndCommit(FILE1, "A different commit message", "1topic", "2", "3", "4topic" ); res = git.Rebase().SetOperation(RebaseCommand.Operation.CONTINUE).Call(); NUnit.Framework.Assert.IsNotNull(res); NUnit.Framework.Assert.AreEqual(RebaseResult.Status.OK, res.GetStatus()); NUnit.Framework.Assert.AreEqual(RepositoryState.SAFE, db.GetRepositoryState()); ObjectId headId = db.Resolve(Constants.HEAD); RevWalk rw = new RevWalk(db); RevCommit rc = rw.ParseCommit(headId); RevCommit parent = rw.ParseCommit(rc.GetParent(0)); NUnit.Framework.Assert.AreEqual("A different commit message", parent.GetFullMessage ()); }
public virtual void WorkingDirectoryDelete() { DeleteTrashFile("file.txt"); RevCommit stashed = git.StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.AreEqual("content", Read(committedFile)); ValidateStashedCommit(stashed); NUnit.Framework.Assert.AreEqual(head.Tree, stashed.GetParent(1).Tree); IList <DiffEntry> diffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, diffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.DELETE, diffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("file.txt", diffs[0].GetOldPath()); }
public virtual void IndexDelete() { git.Rm().AddFilepattern("file.txt").Call(); RevCommit stashed = Git.Wrap(db).StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.AreEqual("content", Read(committedFile)); ValidateStashedCommit(stashed); NUnit.Framework.Assert.AreEqual(stashed.Tree, stashed.GetParent(1).Tree); IList <DiffEntry> diffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, diffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.DELETE, diffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("file.txt", diffs[0].GetOldPath()); }
public virtual void WorkingDirectoryModify() { WriteTrashFile("file.txt", "content2"); RevCommit stashed = Git.Wrap(db).StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.AreEqual("content", Read(committedFile)); ValidateStashedCommit(stashed); NUnit.Framework.Assert.AreEqual(head.Tree, stashed.GetParent(1).Tree); IList <DiffEntry> diffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, diffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, diffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("file.txt", diffs[0].GetNewPath()); }
public void testStringOfPearls_FilePath1() { RevCommit a = Commit(tree(File("d/f", blob("a")))); RevCommit b = Commit(tree(File("d/f", blob("a"))), a); RevCommit c = Commit(tree(File("d/f", blob("b"))), b); filter("d/f"); MarkStart(c); AssertCommit(c, rw.next()); Assert.AreEqual(1, c.ParentCount); AssertCommit(a, c.GetParent(0)); // b was skipped AssertCommit(a, rw.next()); Assert.AreEqual(0, a.ParentCount); Assert.IsNull(rw.next()); }
public virtual void Branch_historyNotPruned() { RevCommit tip = CommitChain(10); tr.Branch("b").Update(tip); gc.SetExpireAgeMillis(0); gc.Prune(Collections.EmptySet <ObjectId>()); do { NUnit.Framework.Assert.IsTrue(repo.HasObject(tip)); tr.ParseBody(tip); RevTree t = tip.Tree; NUnit.Framework.Assert.IsTrue(repo.HasObject(t)); NUnit.Framework.Assert.IsTrue(repo.HasObject(tr.Get(t, "a"))); tip = tip.ParentCount > 0 ? tip.GetParent(0) : null; }while (tip != null); }
/// <exception cref="System.IO.IOException"></exception> private RebaseResult Stop(RevCommit commitToPick) { PersonIdent author = commitToPick.GetAuthorIdent(); string authorScript = ToAuthorScript(author); CreateFile(rebaseDir, AUTHOR_SCRIPT, authorScript); CreateFile(rebaseDir, MESSAGE, commitToPick.GetFullMessage()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DiffFormatter df = new DiffFormatter(bos); df.SetRepository(repo); df.Format(commitToPick.GetParent(0), commitToPick); CreateFile(rebaseDir, PATCH, Sharpen.Runtime.GetStringForBytes(bos.ToByteArray(), Constants.CHARACTER_ENCODING)); CreateFile(rebaseDir, STOPPED_SHA, repo.NewObjectReader().Abbreviate(commitToPick ).Name); return(new RebaseResult(commitToPick)); }
public virtual void IndexAdd() { FilePath addedFile = WriteTrashFile("file2.txt", "content2"); git.Add().AddFilepattern("file2.txt").Call(); RevCommit stashed = Git.Wrap(db).StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.IsFalse(addedFile.Exists()); ValidateStashedCommit(stashed); NUnit.Framework.Assert.AreEqual(stashed.Tree, stashed.GetParent(1).Tree); IList <DiffEntry> diffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, diffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.ADD, diffs[0].GetChangeType( )); NUnit.Framework.Assert.AreEqual("file2.txt", diffs[0].GetNewPath()); }
private static void BuildStopWordIndex(Iterable <RevCommit> log, Repository repository, Git git) { Console.WriteLine("Index build start -" + System.DateTime.Now); DateTime startTime = DateTime.Now; for (Iterator <RevCommit> iterator = log.Iterator(); iterator.HasNext();) { RevCommit rev = iterator.Next(); var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(rev.CommitTime).ToLocalTime(); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.SetRepository(repository); df.SetDiffComparator(RawTextComparator.DEFAULT); df.SetDetectRenames(true); List <String> files = new List <string>(); if (rev.ParentCount > 0) { List <DiffEntry> diffs = df.Scan(rev.GetParent(0).Tree, rev.Tree).ToList(); foreach (DiffEntry diff in diffs) { string filename = diff.GetNewPath(); if (Utils.AllowedFileExtentions(filename)) { string data = GitHelper.GetCommitDiff(repository, git, rev, filename); StopWords.StopWordIndexBuilder.BuildWordIndex(filename, data); } } } if (DateTime.Now.Subtract(startTime).TotalMinutes > 60) { break; } } Console.WriteLine("Index build end -" + System.DateTime.Now); StopWords.StopWordIndexBuilder.BuildStopWordsIndex(); StopWords.StopWordIndexBuilder.WriteToFile(); Console.WriteLine("Stop word keyword index build completed.."); }
public virtual void WorkingDirectoryModifyInSubfolder() { string path = "d1/d2/f.txt"; FilePath subfolderFile = WriteTrashFile(path, "content"); git.Add().AddFilepattern(path).Call(); head = git.Commit().SetMessage("add file").Call(); WriteTrashFile(path, "content2"); RevCommit stashed = Git.Wrap(db).StashCreate().Call(); NUnit.Framework.Assert.IsNotNull(stashed); NUnit.Framework.Assert.AreEqual("content", Read(subfolderFile)); ValidateStashedCommit(stashed); NUnit.Framework.Assert.AreEqual(head.Tree, stashed.GetParent(1).Tree); IList <DiffEntry> diffs = DiffWorkingAgainstHead(stashed); NUnit.Framework.Assert.AreEqual(1, diffs.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, diffs[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual(path, diffs[0].GetNewPath()); }
public virtual void Test026_CreateCommitMultipleparents() { ObjectId treeId; ObjectInserter oi = db.NewObjectInserter(); try { ObjectId blobId = oi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString ("and this is the data in me\n", Constants.CHARSET.Name())); TreeFormatter fmt = new TreeFormatter(); fmt.Append("i-am-a-file", FileMode.REGULAR_FILE, blobId); treeId = oi.Insert(fmt); oi.Flush(); } finally { oi.Release(); } NUnit.Framework.Assert.AreEqual(ObjectId.FromString("00b1f73724f493096d1ffa0b0f1f1482dbb8c936" ), treeId); NGit.CommitBuilder c1 = new NGit.CommitBuilder(); c1.Author = new PersonIdent(author, 1154236443000L, -4 * 60); c1.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60); c1.Message = "A Commit\n"; c1.TreeId = treeId; NUnit.Framework.Assert.AreEqual(treeId, c1.TreeId); ObjectId actid1 = InsertCommit(c1); ObjectId cmtid1 = ObjectId.FromString("803aec4aba175e8ab1d666873c984c0308179099"); NUnit.Framework.Assert.AreEqual(cmtid1, actid1); NGit.CommitBuilder c2 = new NGit.CommitBuilder(); c2.Author = new PersonIdent(author, 1154236443000L, -4 * 60); c2.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60); c2.Message = "A Commit 2\n"; c2.TreeId = treeId; NUnit.Framework.Assert.AreEqual(treeId, c2.TreeId); c2.SetParentIds(actid1); ObjectId actid2 = InsertCommit(c2); ObjectId cmtid2 = ObjectId.FromString("95d068687c91c5c044fb8c77c5154d5247901553"); NUnit.Framework.Assert.AreEqual(cmtid2, actid2); RevCommit rm2 = ParseCommit(cmtid2); NUnit.Framework.Assert.AreNotSame(c2, rm2); // assert the parsed objects is not from the // cache NUnit.Framework.Assert.AreEqual(c2.Author, rm2.GetAuthorIdent()); NUnit.Framework.Assert.AreEqual(actid2, rm2.Id); NUnit.Framework.Assert.AreEqual(c2.Message, rm2.GetFullMessage()); NUnit.Framework.Assert.AreEqual(c2.TreeId, rm2.Tree.Id); NUnit.Framework.Assert.AreEqual(1, rm2.ParentCount); NUnit.Framework.Assert.AreEqual(actid1, rm2.GetParent(0)); NGit.CommitBuilder c3 = new NGit.CommitBuilder(); c3.Author = new PersonIdent(author, 1154236443000L, -4 * 60); c3.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60); c3.Message = "A Commit 3\n"; c3.TreeId = treeId; NUnit.Framework.Assert.AreEqual(treeId, c3.TreeId); c3.SetParentIds(actid1, actid2); ObjectId actid3 = InsertCommit(c3); ObjectId cmtid3 = ObjectId.FromString("ce6e1ce48fbeeb15a83f628dc8dc2debefa066f4"); NUnit.Framework.Assert.AreEqual(cmtid3, actid3); RevCommit rm3 = ParseCommit(cmtid3); NUnit.Framework.Assert.AreNotSame(c3, rm3); // assert the parsed objects is not from the // cache NUnit.Framework.Assert.AreEqual(c3.Author, rm3.GetAuthorIdent()); NUnit.Framework.Assert.AreEqual(actid3, rm3.Id); NUnit.Framework.Assert.AreEqual(c3.Message, rm3.GetFullMessage()); NUnit.Framework.Assert.AreEqual(c3.TreeId, rm3.Tree.Id); NUnit.Framework.Assert.AreEqual(2, rm3.ParentCount); NUnit.Framework.Assert.AreEqual(actid1, rm3.GetParent(0)); NUnit.Framework.Assert.AreEqual(actid2, rm3.GetParent(1)); NGit.CommitBuilder c4 = new NGit.CommitBuilder(); c4.Author = new PersonIdent(author, 1154236443000L, -4 * 60); c4.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60); c4.Message = "A Commit 4\n"; c4.TreeId = treeId; NUnit.Framework.Assert.AreEqual(treeId, c3.TreeId); c4.SetParentIds(actid1, actid2, actid3); ObjectId actid4 = InsertCommit(c4); ObjectId cmtid4 = ObjectId.FromString("d1fca9fe3fef54e5212eb67902c8ed3e79736e27"); NUnit.Framework.Assert.AreEqual(cmtid4, actid4); RevCommit rm4 = ParseCommit(cmtid4); NUnit.Framework.Assert.AreNotSame(c4, rm3); // assert the parsed objects is not from the // cache NUnit.Framework.Assert.AreEqual(c4.Author, rm4.GetAuthorIdent()); NUnit.Framework.Assert.AreEqual(actid4, rm4.Id); NUnit.Framework.Assert.AreEqual(c4.Message, rm4.GetFullMessage()); NUnit.Framework.Assert.AreEqual(c4.TreeId, rm4.Tree.Id); NUnit.Framework.Assert.AreEqual(3, rm4.ParentCount); NUnit.Framework.Assert.AreEqual(actid1, rm4.GetParent(0)); NUnit.Framework.Assert.AreEqual(actid2, rm4.GetParent(1)); NUnit.Framework.Assert.AreEqual(actid3, rm4.GetParent(2)); }
/// <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"></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(JGitText.Get().canOnlyCherryPickCommitsWithOneParent ); } 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() ).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)); }
static void Main(string[] args) { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.SetGitDir(new FilePath(@"D:\Personal\E Books\Higher Education\Research\SampleProjects\NopCommerce\.git")) //Repository repository = builder.SetGitDir(new FilePath(@"C:\Users\neemathu\Documents\GitHub\angular.js\.git")) // Repository repository = builder.SetGitDir(new FilePath(@"D:\Personal\E Books\Higher Education\RefactoringActivity\ganttproject\.git")) .ReadEnvironment() // scan environment GIT_* variables .FindGitDir() // scan up the file system tree .Build(); HashSet <String> uniqueFile = new HashSet <string>(); Dictionary <String, int> logicalCoupling = new Dictionary <string, int>(); RevWalk rw = new RevWalk(repository); Git git = new Git(repository); Iterable <RevCommit> log = git.Log().Call(); for (Iterator <RevCommit> iterator = log.Iterator(); iterator.HasNext();) { RevCommit rev = iterator.Next(); //RevWalk revWalk = new RevWalk(git.GetRepository()); //RevTree revTree = revWalk.ParseTree(rev.Tree.Id); //TreeWalk treeWalk = new TreeWalk(git.GetRepository()); //treeWalk.AddTree(revTree); //while (treeWalk.Next()) //{ // //compare treeWalk.NameString yourself // byte[] bytes = treeWalk.ObjectReader.Open(treeWalk.GetObjectId(0)).GetBytes(); // string result1 = System.Text.Encoding.UTF8.GetString(bytes); //} // Sharpen.OutputStream os = new Sharpen.OutputStream(); //rev.CopyRawTo(os); //System.Console.WriteLine("Author: "+rev.GetAuthorIdent().GetName()); //System.Console.WriteLine("ID:" + rev.Id); var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(rev.CommitTime).ToLocalTime(); //var ts = new TimeSpan(DateTime.UtcNow.Ticks - rev.CommitTime); //System.Console.WriteLine("Date:" + dt.ToString()); //System.Console.WriteLine("Description:" + rev.GetFullMessage()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.SetRepository(repository); df.SetDiffComparator(RawTextComparator.DEFAULT); df.SetDetectRenames(true); List <String> files = new List <string>(); if (rev.ParentCount > 0) { List <DiffEntry> diffs = df.Scan(rev.GetParent(0).Tree, rev.Tree).ToList(); foreach (DiffEntry diff in diffs) { // Fetch data from the commited new file //ObjectLoader loader = repository.Open(diff.GetNewId().ToObjectId()); //OutputStream @out = new ByteArrayOutputStream(); ////loader.CopyTo(@out); ////Fetch diffrence of commit //DiffCommand diff1 = git.Diff().SetPathFilter(PathFilter.Create(diff.GetNewPath())).SetOldTree(GetTreeIterator(rev.GetParent(0).Tree.Name, repository)).SetNewTree(GetTreeIterator(rev.Tree.Name, repository)).SetOutputStream(@out); //IList<DiffEntry> entries = diff1.Call(); //string data = @out.ToString(); files.Add(diff.GetNewPath()); uniqueFile.Add(diff.GetNewPath()); //System.Console.WriteLine(String.Format("FilePath: {0} {1}", diff.GetNewMode().GetBits(), diff.GetNewPath())); } } if (isContainFile(rev, files)) { //System.Console.WriteLine(rev.Id); //System.Console.WriteLine(dt); //System.Console.WriteLine(rev.GetAuthorIdent().GetName()); //System.Console.WriteLine(rev.GetFullMessage()); tfIdfBeforeData.Add(rev.Id.Name, new Dictionary <string, Dictionary <string, double> >()); foreach (String file in files) { String fileName = file.Substring(file.LastIndexOf("/") + 1, file.Length - file.LastIndexOf("/") - 1); if (IsFileExtentionAllowed(fileName)) { string data = GetCommitDiff(repository, git, rev, file); Dictionary <string, double> tokensTF = GetTokensWithTF(data); tfIdfBeforeData[rev.Id.Name].Add(file, tokensTF); //System.Console.WriteLine("File path: " + file); //System.Console.WriteLine(data); //System.Console.WriteLine("------------------"); if (!logicalCoupling.ContainsKey(fileName)) { logicalCoupling.Add(fileName, 1); } else { logicalCoupling[fileName] += 1; } } } //System.Console.WriteLine("###################################"); } //foreach (var item in uniqueFile) //{ // System.Console.WriteLine(item); //} //System.Console.WriteLine("--------------------"); //http://stackoverflow.com/questions/11869412/jgit-using-revwalk-to-get-revcommit-returns-nothing ////ObjectId head = repository.Resolve("master"); //RevWalk walk = new RevWalk(repository); //foreach (var commit in walk) //{ // String email = commit.GetAuthorIdent().GetEmailAddress(); //} } CalculateTfIdfScore("defaultResources.nopres.xml"); CalculateLogicalDependency(logicalCoupling); System.Console.WriteLine("----------Done----------"); System.Console.ReadLine(); }
private static string GetCommitDiff(Repository repository, Git git, RevCommit rev, String file) { //Fetch diffrence of commit OutputStream @out = new ByteArrayOutputStream(); DiffCommand diff1 = git.Diff().SetPathFilter(PathFilter.Create(file)).SetOldTree(GetTreeIterator(rev.GetParent(0).Tree.Name, repository)).SetNewTree(GetTreeIterator(rev.Tree.Name, repository)).SetOutputStream(@out); IList <DiffEntry> entries = diff1.Call(); string data = @out.ToString(); data = System.Text.RegularExpressions.Regex.Replace(data, "[^a-zA-Z.]+", " ");//[^0-9a-zA-Z.] data = RemoveStopWords(data); return(data); }
static void Main(string[] args) { //string input = "group, and test but not testing. But yes to test"; //string val="Group"; //string pattern = @"\b" + val + @"\b"; //string replace = " "; //string result = System.Text.RegularExpressions.Regex.Replace(input, pattern, replace, System.Text.RegularExpressions.RegexOptions.IgnoreCase); //Console.WriteLine(result); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.SetGitDir(new FilePath(@"D:\Personal\E Books\Higher Education\Research\SampleProjects\NopCommerce\.git")) //Repository repository = builder.SetGitDir(new FilePath(@"C:\Users\neemathu\Documents\GitHub\angular.js\.git")) // Repository repository = builder.SetGitDir(new FilePath(@"D:\Personal\E Books\Higher Education\RefactoringActivity\ganttproject\.git")) .ReadEnvironment() // scan environment GIT_* variables .FindGitDir() // scan up the file system tree .Build(); RevWalk rw = new RevWalk(repository); Git git = new Git(repository); Iterable <RevCommit> log = git.Log().Call(); if (args.Length > 0) { switch (args[0]) { case "buildstopwordindex": BuildStopWordIndex(log, repository, git); return; break; default: break; } } // Iterat over revisions for (Iterator <RevCommit> iterator = log.Iterator(); iterator.HasNext();) { RevCommit rev = iterator.Next(); var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(rev.CommitTime).ToLocalTime(); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.SetRepository(repository); df.SetDiffComparator(RawTextComparator.DEFAULT); df.SetDetectRenames(true); List <String> files = new List <string>(); if (rev.ParentCount > 0) { List <DiffEntry> diffs = df.Scan(rev.GetParent(0).Tree, rev.Tree).ToList(); foreach (DiffEntry diff in diffs) { // Fetch data from the commited new file //ObjectLoader loader = repository.Open(diff.GetNewId().ToObjectId()); //OutputStream @out = new ByteArrayOutputStream(); ////loader.CopyTo(@out); ////Fetch diffrence of commit //DiffCommand diff1 = git.Diff().SetPathFilter(PathFilter.Create(diff.GetNewPath())).SetOldTree(GetTreeIterator(rev.GetParent(0).Tree.Name, repository)).SetNewTree(GetTreeIterator(rev.Tree.Name, repository)).SetOutputStream(@out); //IList<DiffEntry> entries = diff1.Call(); //string data = @out.ToString(); string filePath = diff.GetNewPath(); //if (fileCount.ContainsKey(filePath)) //{ // fileCount[filePath] = fileCount[filePath] + 1; //} //else //{ // fileCount.Add(filePath, 1); //} files.Add(filePath); //System.Console.WriteLine(String.Format("FilePath: {0} {1}", diff.GetNewMode().GetBits(), diff.GetNewPath())); } //continue; } if (GitHelper.HasFile(files)) { foreach (String file in files) { String FileName = file.Substring(file.LastIndexOf("/") + 1, file.Length - file.LastIndexOf("/") - 1); if (Utils.AllowedFileExtentions(FileName)) { string DiffContent = GitHelper.GetCommitDiff(repository, git, rev, file); //data = Common.Utils.RemoveStopWords(data); LogicalDependency.LogicalDependency.AddArtifact(rev.Id.Name, file, DiffContent); //StopWords.StopWordIndexBuilder.BuildWordIndex(file, data); } } } } //var sortedElements = fileCount.OrderByDescending(kvp => kvp.Value); //foreach (var item in sortedElements) //{ // Console.WriteLine(item.Key + ": " + item.Value); //} LogicalDependency.LogicalDependency.CalculateSimilarityIndex(); }
/// <summary>Apply the changes in a stashed commit to the working directory and index /// </summary> /// <returns>id of stashed commit that was applied</returns> /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException /// </exception> /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">NGit.Api.Errors.WrongRepositoryStateException /// </exception> public override ObjectId Call() { CheckCallable(); if (repo.GetRepositoryState() != RepositoryState.SAFE) { throw new WrongRepositoryStateException(MessageFormat.Format(JGitText.Get().stashApplyOnUnsafeRepository , repo.GetRepositoryState())); } ObjectId headTree = GetHeadTree(); ObjectId stashId = GetStashId(); ObjectReader reader = repo.NewObjectReader(); try { RevWalk revWalk = new RevWalk(reader); RevCommit stashCommit = revWalk.ParseCommit(stashId); if (stashCommit.ParentCount != 2) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().stashCommitMissingTwoParents , stashId.Name)); } RevTree stashWorkingTree = stashCommit.Tree; RevTree stashIndexTree = revWalk.ParseCommit(stashCommit.GetParent(1)).Tree; RevTree stashHeadTree = revWalk.ParseCommit(stashCommit.GetParent(0)).Tree; CanonicalTreeParser stashWorkingIter = new CanonicalTreeParser(); stashWorkingIter.Reset(reader, stashWorkingTree); CanonicalTreeParser stashIndexIter = new CanonicalTreeParser(); stashIndexIter.Reset(reader, stashIndexTree); CanonicalTreeParser stashHeadIter = new CanonicalTreeParser(); stashHeadIter.Reset(reader, stashHeadTree); CanonicalTreeParser headIter = new CanonicalTreeParser(); headIter.Reset(reader, headTree); DirCache cache = repo.LockDirCache(); DirCacheEditor editor = cache.Editor(); try { DirCacheIterator indexIter = new DirCacheIterator(cache); FileTreeIterator workingIter = new FileTreeIterator(repo); TreeWalk treeWalk = new TreeWalk(reader); treeWalk.Recursive = true; treeWalk.Filter = new StashApplyCommand.StashDiffFilter(); treeWalk.AddTree(stashHeadIter); treeWalk.AddTree(stashIndexIter); treeWalk.AddTree(stashWorkingIter); treeWalk.AddTree(headIter); treeWalk.AddTree(indexIter); treeWalk.AddTree(workingIter); ScanForConflicts(treeWalk); // Reset trees and walk treeWalk.Reset(); stashWorkingIter.Reset(reader, stashWorkingTree); stashIndexIter.Reset(reader, stashIndexTree); stashHeadIter.Reset(reader, stashHeadTree); treeWalk.AddTree(stashHeadIter); treeWalk.AddTree(stashIndexIter); treeWalk.AddTree(stashWorkingIter); ApplyChanges(treeWalk, cache, editor); } finally { editor.Commit(); cache.Unlock(); } } catch (JGitInternalException e) { throw; } catch (IOException e) { throw new JGitInternalException(JGitText.Get().stashApplyFailed, e); } finally { reader.Release(); } return(stashId); }