public virtual void ShouldReportFileModeChange() { WriteTrashFile("a.txt", "content"); Git git = new Git(db); git.Add().AddFilepattern("a.txt").Call(); RevCommit c1 = git.Commit().SetMessage("initial commit").Call(); DirCache cache = db.LockDirCache(); DirCacheEditor editor = cache.Editor(); TreeWalk walk = new TreeWalk(db); walk.AddTree(c1.Tree); walk.Recursive = true; NUnit.Framework.Assert.IsTrue(walk.Next()); editor.Add(new _PathEdit_318(walk, "a.txt")); NUnit.Framework.Assert.IsTrue(editor.Commit()); RevCommit c2 = git.Commit().SetMessage("second commit").Call(); walk.Reset(); walk.AddTree(c1.Tree); walk.AddTree(c2.Tree); IList <DiffEntry> diffs = DiffEntry.Scan(walk, false); NUnit.Framework.Assert.AreEqual(1, diffs.Count); DiffEntry diff = diffs[0]; NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, diff.GetChangeType() ); NUnit.Framework.Assert.AreEqual(diff.GetOldId(), diff.GetNewId()); NUnit.Framework.Assert.AreEqual("a.txt", diff.GetOldPath()); NUnit.Framework.Assert.AreEqual(diff.GetOldPath(), diff.GetNewPath()); NUnit.Framework.Assert.AreEqual(FileMode.EXECUTABLE_FILE, diff.GetNewMode()); NUnit.Framework.Assert.AreEqual(FileMode.REGULAR_FILE, diff.GetOldMode()); }
public virtual void ShouldListAddedFileBetweenTwoCommits() { // given Git git = new Git(db); RevCommit c1 = git.Commit().SetMessage("initial commit").Call(); WriteTrashFile("a.txt", "content"); git.Add().AddFilepattern("a.txt").Call(); RevCommit c2 = git.Commit().SetMessage("second commit").Call(); // when TreeWalk walk = new TreeWalk(db); walk.AddTree(c1.Tree); walk.AddTree(c2.Tree); IList <DiffEntry> result = DiffEntry.Scan(walk); // then Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); DiffEntry entry = result[0]; Assert.AreEqual(entry.GetChangeType(), DiffEntry.ChangeType.ADD); Assert.AreEqual(entry.GetNewPath(), "a.txt"); Assert.AreEqual(entry.GetOldPath(), DiffEntry.DEV_NULL); }
public virtual void ShouldListChangesInWorkingTree() { // given WriteTrashFile("a.txt", "content"); Git git = new Git(db); git.Add().AddFilepattern("a.txt").Call(); RevCommit c = git.Commit().SetMessage("initial commit").Call(); WriteTrashFile("b.txt", "new line"); // when TreeWalk walk = new TreeWalk(db); walk.AddTree(c.Tree); walk.AddTree(new FileTreeIterator(db)); IList <DiffEntry> result = DiffEntry.Scan(walk, true); // then Assert.AreEqual(1, result.Count); DiffEntry entry = result[0]; Assert.AreEqual(entry.GetChangeType(), DiffEntry.ChangeType.ADD); Assert.AreEqual(entry.GetNewPath(), "b.txt"); }
public virtual void ShouldListModificationInDirWithoutModifiedTrees() { // given Git git = new Git(db); FilePath tree = new FilePath(new FilePath(db.WorkTree, "a"), "b"); FileUtils.Mkdirs(tree); FilePath file = new FilePath(tree, "c.txt"); FileUtils.CreateNewFile(file); Write(file, "content"); git.Add().AddFilepattern("a").Call(); RevCommit c1 = git.Commit().SetMessage("initial commit").Call(); Write(file, "new line"); RevCommit c2 = git.Commit().SetAll(true).SetMessage("second commit").Call(); // when TreeWalk walk = new TreeWalk(db); walk.AddTree(c1.Tree); walk.AddTree(c2.Tree); walk.Recursive = true; IList <DiffEntry> result = DiffEntry.Scan(walk); // then Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); DiffEntry entry = result[0]; Assert.AreEqual(entry.GetChangeType(), DiffEntry.ChangeType.MODIFY); Assert.AreEqual(entry.GetNewPath(), "a/b/c.txt"); }
private static IEnumerable <DiffEntry> GetDiffEntries(this RevCommit commit, Repository repository) { var tw = new TreeWalk(repository) { Recursive = true }; if (commit.ParentCount > 0) { if (commit.Parents.First().Tree != null) { tw.AddTree(commit.Parents.First().Tree); } else { tw.AddTree(new EmptyTreeIterator()); } } else { tw.AddTree(new EmptyTreeIterator()); } tw.Filter = TreeFilter.ANY_DIFF; tw.AddTree(commit.Tree); return(DiffEntry.Scan(tw)); }
public virtual void TestNoDF_NoGap() { DirCache tree0 = db.ReadDirCache(); DirCache tree1 = db.ReadDirCache(); { DirCacheBuilder b0 = tree0.Builder(); DirCacheBuilder b1 = tree1.Builder(); b0.Add(MakeEntry("a", REGULAR_FILE)); b0.Add(MakeEntry("a.b", EXECUTABLE_FILE)); b1.Add(MakeEntry("a/b", REGULAR_FILE)); b0.Add(MakeEntry("a0b", SYMLINK)); b0.Finish(); b1.Finish(); NUnit.Framework.Assert.AreEqual(3, tree0.GetEntryCount()); NUnit.Framework.Assert.AreEqual(1, tree1.GetEntryCount()); } TreeWalk tw = new TreeWalk(db); tw.AddTree(new DirCacheIterator(tree0)); tw.AddTree(new DirCacheIterator(tree1)); AssertModes("a", REGULAR_FILE, MISSING, tw); AssertModes("a.b", EXECUTABLE_FILE, MISSING, tw); AssertModes("a", MISSING, TREE, tw); tw.EnterSubtree(); AssertModes("a/b", MISSING, REGULAR_FILE, tw); AssertModes("a0b", SYMLINK, MISSING, tw); }
internal IList <GitFile> GetChangedFiles() { if (!HasGitRepository) { return(new List <GitFile>()); } if (GitBash.Exists) { var output = GitBash.Run("status --porcelain -z --untracked-files", this.GitWorkingDirectory); return(ParseGitStatus(output)); } else { var list = new List <GitFile>(); var treeWalk = new TreeWalk(this.repository); treeWalk.Recursive = true; treeWalk.Filter = TreeFilter.ANY_DIFF; var id = repository.Resolve(Constants.HEAD); if (id != null) { treeWalk.AddTree(new RevWalk(repository).ParseTree(id)); } else { treeWalk.AddTree(new EmptyTreeIterator()); } treeWalk.AddTree(new DirCacheIterator(this.repository.ReadDirCache())); treeWalk.AddTree(new FileTreeIterator(this.repository)); var filters = new TreeFilter[] { new SkipWorkTreeFilter(INDEX), new IndexDiffFilter(INDEX, WORKDIR) }; treeWalk.Filter = AndTreeFilter.Create(filters); while (treeWalk.Next()) { WorkingTreeIterator workingTreeIterator = treeWalk.GetTree <WorkingTreeIterator>(WORKDIR); if (workingTreeIterator != null && workingTreeIterator.IsEntryIgnored()) { continue; } var fileName = GetFullPath(treeWalk.PathString); if (Directory.Exists(fileName)) { continue; // this excludes sub modules } var status = GetFileStatus(treeWalk); list.Add(new GitFile { FileName = GetRelativeFileName(fileName), Status = status }); this.cache[GetCacheKey(fileName)] = status; } return(list); } }
ObjectId WriteWorkingDirectoryTree(RevTree headTree, DirCache index) { DirCache dc = DirCache.NewInCore(); DirCacheBuilder cb = dc.Builder(); ObjectInserter oi = _repo.NewObjectInserter(); try { TreeWalk tw = new TreeWalk(_repo); tw.Reset(); tw.AddTree(new FileTreeIterator(_repo)); tw.AddTree(headTree); tw.AddTree(new DirCacheIterator(index)); while (tw.Next()) { // Ignore untracked files if (tw.IsSubtree) { tw.EnterSubtree(); } else if (tw.GetFileMode(0) != NGit.FileMode.MISSING && (tw.GetFileMode(1) != NGit.FileMode.MISSING || tw.GetFileMode(2) != NGit.FileMode.MISSING)) { WorkingTreeIterator f = tw.GetTree <WorkingTreeIterator>(0); DirCacheIterator dcIter = tw.GetTree <DirCacheIterator>(2); DirCacheEntry currentEntry = dcIter.GetDirCacheEntry(); DirCacheEntry ce = new DirCacheEntry(tw.PathString); if (!f.IsModified(currentEntry, true)) { ce.SetLength(currentEntry.Length); ce.LastModified = currentEntry.LastModified; ce.FileMode = currentEntry.FileMode; ce.SetObjectId(currentEntry.GetObjectId()); } else { long sz = f.GetEntryLength(); ce.SetLength(sz); ce.LastModified = f.GetEntryLastModified(); ce.FileMode = f.EntryFileMode; var data = f.OpenEntryStream(); try { ce.SetObjectId(oi.Insert(Constants.OBJ_BLOB, sz, data)); } finally { data.Close(); } } cb.Add(ce); } } cb.Finish(); return(dc.WriteTree(oi)); } finally { oi.Release(); } }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> private void AddTree(TreeWalk tw, ObjectId id) { if (id == null) { tw.AddTree(new EmptyTreeIterator()); } else { tw.AddTree(id); } }
/// <exception cref="System.Exception"></exception> public virtual void ShouldThrowIAEWhenScanShouldIncludeTreesAndWalkIsRecursive() { // given - we don't need anything here // when TreeWalk walk = new TreeWalk(db); walk.AddTree(new EmptyTreeIterator()); walk.AddTree(new EmptyTreeIterator()); walk.Recursive = true; DiffEntry.Scan(walk, true); }
public GitFileStatus GetFileStatusNoCache(string fileName) { if (Directory.Exists(fileName)) { return(GitFileStatus.Ignored); } var fileNameRel = GetRelativeFileNameForGit(fileName); TreeWalk treeWalk = new TreeWalk(this.repository) { Recursive = true }; RevTree revTree = head == null ? null : new RevWalk(repository).ParseTree(head); if (revTree != null) { treeWalk.AddTree(revTree); } else { treeWalk.AddTree(new EmptyTreeIterator()); } treeWalk.AddTree(new DirCacheIterator(dirCache)); treeWalk.AddTree(new FileTreeIterator(this.repository)); var filters = new TreeFilter[] { PathFilter.Create(fileNameRel), new SkipWorkTreeFilter(INDEX), new IndexDiffFilter(INDEX, WORKDIR) }; treeWalk.Filter = AndTreeFilter.Create(filters); var status = GitFileStatus.NotControlled; if (treeWalk.Next()) { status = GetFileStatus(treeWalk); } if (status == GitFileStatus.NotControlled) { var dirCacheEntry2 = dirCache.GetEntry(fileNameRel); if (dirCacheEntry2 != null) { var treeEntry2 = TreeWalk.ForPath(repository, fileNameRel, revTree); if (treeEntry2 != null && treeEntry2.GetObjectId(0).Equals(dirCacheEntry2.GetObjectId())) { return(GitFileStatus.Tracked); } } } return(GitFileStatus.NotControlled); }
/// <exception cref="System.Exception"></exception> public virtual void ShouldThrowIAEWhenTreeWalkHasMoreThanTwoTrees() { // given - we don't need anything here // when TreeWalk walk = new TreeWalk(db); walk.AddTree(new EmptyTreeIterator()); walk.AddTree(new EmptyTreeIterator()); walk.AddTree(new EmptyTreeIterator()); DiffEntry.Scan(walk); }
public virtual void CommitNewSubmodule() { Git git = new Git(db); WriteTrashFile("file.txt", "content"); git.Add().AddFilepattern("file.txt").Call(); RevCommit commit = git.Commit().SetMessage("create 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(commit, 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(commit, repo.Resolve(Constants.HEAD)); RevCommit submoduleCommit = git.Commit().SetMessage("submodule add").SetOnly(path ).Call(); NUnit.Framework.Assert.IsNotNull(submoduleCommit); TreeWalk walk = new TreeWalk(db); walk.AddTree(commit.Tree); walk.AddTree(submoduleCommit.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.MISSING, subDiff.GetOldMode()); NUnit.Framework.Assert.AreEqual(FileMode.GITLINK, subDiff.GetNewMode()); NUnit.Framework.Assert.AreEqual(ObjectId.ZeroId, subDiff.GetOldId().ToObjectId()); NUnit.Framework.Assert.AreEqual(commit, subDiff.GetNewId().ToObjectId()); NUnit.Framework.Assert.AreEqual(path, subDiff.GetNewPath()); }
/// <summary>Determine the differences between two trees.</summary> /// <remarks> /// Determine the differences between two trees. /// No output is created, instead only the file paths that are different are /// returned. Callers may choose to format these paths themselves, or convert /// them into /// <see cref="NGit.Patch.FileHeader">NGit.Patch.FileHeader</see> /// instances with a complete edit list by /// calling /// <see cref="ToFileHeader(DiffEntry)">ToFileHeader(DiffEntry)</see> /// . /// </remarks> /// <param name="a">the old (or previous) side.</param> /// <param name="b">the new (or updated) side.</param> /// <returns>the paths that are different.</returns> /// <exception cref="System.IO.IOException">trees cannot be read or file contents cannot be read. /// </exception> public virtual IList <DiffEntry> Scan(AbstractTreeIterator a, AbstractTreeIterator b) { AssertHaveRepository(); TreeWalk walk = new TreeWalk(reader); walk.AddTree(a); walk.AddTree(b); walk.Recursive = true; TreeFilter filter = GetDiffTreeFilterFor(a, b); if (pathFilter is FollowFilter) { walk.Filter = AndTreeFilter.Create(PathFilter.Create(((FollowFilter)pathFilter).GetPath ()), filter); } else { walk.Filter = AndTreeFilter.Create(pathFilter, filter); } source = new ContentSource.Pair(Source(a), Source(b)); IList <DiffEntry> files = DiffEntry.Scan(walk); if (pathFilter is FollowFilter && IsAdd(files)) { // The file we are following was added here, find where it // came from so we can properly show the rename or copy, // then continue digging backwards. // a.Reset(); b.Reset(); walk.Reset(); walk.AddTree(a); walk.AddTree(b); walk.Filter = filter; if (renameDetector == null) { SetDetectRenames(true); } files = UpdateFollowFilter(DetectRenames(DiffEntry.Scan(walk))); } else { if (renameDetector != null) { files = DetectRenames(files); } } return(files); }
private void ResetIndexForPaths(RevCommit commit) { DirCache dc = null; DirCacheEditor edit; try { dc = repo.LockDirCache(); edit = dc.Editor(); TreeWalk tw = new TreeWalk(repo); tw.AddTree(new DirCacheIterator(dc)); tw.AddTree(commit.Tree); tw.Filter = PathFilterGroup.CreateFromStrings(filepaths); tw.Recursive = true; while (tw.Next()) { string path = tw.PathString; // DirCacheIterator dci = tw.getTree(0, DirCacheIterator.class); CanonicalTreeParser tree = tw.GetTree <CanonicalTreeParser>(1); if (tree == null) { // file is not in the commit, remove from index edit.Add(new DirCacheEditor.DeletePath(path)); } else { // revert index to commit // it seams that there is concurrent access to tree // variable, therefore we need to keep references to // entryFileMode and entryObjectId in local // variables FileMode entryFileMode = tree.EntryFileMode; ObjectId entryObjectId = tree.EntryObjectId; edit.Add(new _PathEdit_305(entryFileMode, entryObjectId, path)); } } edit.Commit(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (dc != null) { dc.Unlock(); } } }
/// <summary>Checkout paths into index and working directory</summary> /// <returns>this instance</returns> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException /// </exception> protected internal virtual NGit.Api.CheckoutCommand CheckoutPaths() { RevWalk revWalk = new RevWalk(repo); DirCache dc = repo.LockDirCache(); try { DirCacheEditor editor = dc.Editor(); TreeWalk startWalk = new TreeWalk(revWalk.GetObjectReader()); startWalk.Recursive = true; if (!checkoutAllPaths) { startWalk.Filter = PathFilterGroup.CreateFromStrings(paths); } bool checkoutIndex = startCommit == null && startPoint == null; if (!checkoutIndex) { startWalk.AddTree(revWalk.ParseCommit(GetStartPoint()).Tree); } else { startWalk.AddTree(new DirCacheIterator(dc)); } FilePath workTree = repo.WorkTree; ObjectReader r = repo.ObjectDatabase.NewReader(); try { while (startWalk.Next()) { ObjectId blobId = startWalk.GetObjectId(0); FileMode mode = startWalk.GetFileMode(0); editor.Add(new _PathEdit_349(this, checkoutIndex, blobId, mode, workTree, r, startWalk .PathString)); } editor.Commit(); } finally { startWalk.Release(); r.Release(); } } finally { dc.Unlock(); revWalk.Release(); } return(this); }
/// <summary>Update any smudged entries with information from the working tree.</summary> /// <remarks>Update any smudged entries with information from the working tree.</remarks> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> private void UpdateSmudgedEntries() { TreeWalk walk = new TreeWalk(repository); IList <string> paths = new AList <string>(128); try { for (int i = 0; i < entryCnt; i++) { if (sortedEntries[i].IsSmudged) { paths.AddItem(sortedEntries[i].PathString); } } if (paths.IsEmpty()) { return; } walk.Filter = PathFilterGroup.CreateFromStrings(paths); DirCacheIterator iIter = new DirCacheIterator(this); FileTreeIterator fIter = new FileTreeIterator(repository); walk.AddTree(iIter); walk.AddTree(fIter); walk.Recursive = true; while (walk.Next()) { iIter = walk.GetTree <DirCacheIterator>(0); if (iIter == null) { continue; } fIter = walk.GetTree <FileTreeIterator>(1); if (fIter == null) { continue; } DirCacheEntry entry = iIter.GetDirCacheEntry(); if (entry.IsSmudged && iIter.IdEqual(fIter)) { entry.SetLength(fIter.GetEntryLength()); entry.LastModified = fIter.GetEntryLastModified(); } } } finally { walk.Release(); } }
/// <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 static API_NGit files(this API_NGit nGit, string commitId, Action <TreeWalk> onTreeWalk) { try { var headCommit = nGit.Repository.Resolve(commitId); if (commitId.notNull()) { var revWalk = new RevWalk(nGit.Repository); var commit = revWalk.ParseCommit(headCommit); var treeWalk = new TreeWalk(nGit.Repository); var tree = commit.Tree; treeWalk.AddTree(tree); treeWalk.Recursive = true; while (treeWalk.Next()) { onTreeWalk(treeWalk); } } } catch (Exception ex) { ex.log("[API_NGit][getRepoFiles]"); } return(nGit); }
public virtual void TestNonRecursiveFiltering() { ObjectInserter odi = db.NewObjectInserter(); ObjectId aSth = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString( "a.sth")); ObjectId aTxt = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString( "a.txt")); DirCache dc = db.ReadDirCache(); DirCacheBuilder builder = dc.Builder(); DirCacheEntry aSthEntry = new DirCacheEntry("a.sth"); aSthEntry.FileMode = FileMode.REGULAR_FILE; aSthEntry.SetObjectId(aSth); DirCacheEntry aTxtEntry = new DirCacheEntry("a.txt"); aTxtEntry.FileMode = FileMode.REGULAR_FILE; aTxtEntry.SetObjectId(aTxt); builder.Add(aSthEntry); builder.Add(aTxtEntry); builder.Finish(); ObjectId treeId = dc.WriteTree(odi); odi.Flush(); TreeWalk tw = new TreeWalk(db); tw.Filter = PathSuffixFilter.Create(".txt"); tw.AddTree(treeId); IList<string> paths = new List<string>(); while (tw.Next()) { paths.AddItem(tw.PathString); } IList<string> expected = new List<string>(); expected.AddItem("a.txt"); NUnit.Framework.Assert.AreEqual(expected, paths); }
public virtual void TestALL_IncludesAnything() { TreeWalk tw = new TreeWalk(db); tw.AddTree(new EmptyTreeIterator()); NUnit.Framework.Assert.IsTrue(TreeFilter.ALL.Include(tw)); }
public virtual void TestNotALL_IncludesNothing() { TreeWalk tw = new TreeWalk(db); tw.AddTree(new EmptyTreeIterator()); NUnit.Framework.Assert.IsFalse(TreeFilter.ALL.Negate().Include(tw)); }
public virtual void TestANY_DIFF_IncludesSingleTreeCase() { TreeWalk tw = new TreeWalk(db); tw.AddTree(new EmptyTreeIterator()); NUnit.Framework.Assert.IsTrue(TreeFilter.ANY_DIFF.Include(tw)); }
public static List <GitData_File> gitData_Files(this API_NGit nGit, int max_FilesToShow, string commitSha1) { var gitData_Files = new List <GitData_File>(); try { var headCommit = nGit.Repository.Resolve(commitSha1); if (commitSha1.notNull()) { var revWalk = new RevWalk(nGit.Repository); var commit = revWalk.ParseCommit(headCommit); var treeWalk = new TreeWalk(nGit.Repository); var tree = commit.Tree; treeWalk.AddTree(tree); treeWalk.Recursive = true; while (treeWalk.Next() && (max_FilesToShow == -1) || gitData_Files.size() < max_FilesToShow) { gitData_Files.add_File(treeWalk); } //repoFiles.Add(treeWalk.PathString); } } catch (Exception ex) { ex.log("[API_NGit][gitData_Files]"); } return(gitData_Files); }
public virtual void TestTreeWalk_LsFiles() { Repository db = CreateBareRepository(); IDictionary <string, DirCacheCGitCompatabilityTest.CGitIndexRecord> ls = ReadLsFiles (); DirCache dc = new DirCache(index, db.FileSystem); NUnit.Framework.Assert.AreEqual(0, dc.GetEntryCount()); dc.Read(); NUnit.Framework.Assert.AreEqual(ls.Count, dc.GetEntryCount()); { Iterator <DirCacheCGitCompatabilityTest.CGitIndexRecord> rItr = ls.Values.Iterator (); TreeWalk tw = new TreeWalk(db); tw.Recursive = true; tw.AddTree(new DirCacheIterator(dc)); while (rItr.HasNext()) { DirCacheIterator dcItr; NUnit.Framework.Assert.IsTrue(tw.Next()); dcItr = tw.GetTree <DirCacheIterator>(0); NUnit.Framework.Assert.IsNotNull(dcItr); AssertEqual(rItr.Next(), dcItr.GetDirCacheEntry()); } } }
public static string GetFileContent(this RevCommit commit, string path, Repository repository) { var treeWalk = new TreeWalk(repository) { Recursive = true, Filter = PathFilter.Create(path) }; treeWalk.AddTree(commit.Tree); if (!treeWalk.Next()) { return(string.Empty); } var objectId = treeWalk.GetObjectId(0); var loader = repository.Open(objectId); using (var stream = loader.OpenStream()) { using (var reader = new StreamReader(stream)) { return(reader.ReadToEnd()); } } }
public virtual void TestEmptyTree_WithTreeWalk() { DirCache dc = DirCache.NewInCore(); NUnit.Framework.Assert.AreEqual(0, dc.GetEntryCount()); TreeWalk tw = new TreeWalk(db); tw.AddTree(new DirCacheIterator(dc)); NUnit.Framework.Assert.IsFalse(tw.Next()); }
/// <exception cref="System.Exception"></exception> private TreeWalk CreateTreeWalk(RevCommit commit, bool isRecursive, bool honorIgnores ) { TreeWalk treeWalk = new TreeWalk(db); treeWalk.Recursive = isRecursive; treeWalk.AddTree(commit.Tree); treeWalk.AddTree(new DirCacheIterator(db.ReadDirCache())); treeWalk.AddTree(new FileTreeIterator(db)); if (!honorIgnores) { treeWalk.Filter = new IndexDiffFilter(1, 2, honorIgnores); } else { treeWalk.Filter = new IndexDiffFilter(1, 2); } return(treeWalk); }
/// <exception cref="System.IO.IOException"></exception> private void ResetIndex(RevCommit commit) { DirCache dc = repo.LockDirCache(); TreeWalk walk = null; try { DirCacheEditor editor = dc.Editor(); walk = new TreeWalk(repo); walk.AddTree(commit.Tree); walk.AddTree(new DirCacheIterator(dc)); walk.Recursive = true; while (walk.Next()) { AbstractTreeIterator cIter = walk.GetTree <AbstractTreeIterator>(0); if (cIter == null) { editor.Add(new DirCacheEditor.DeletePath(walk.PathString)); continue; } DirCacheEntry entry = new DirCacheEntry(walk.RawPath); entry.FileMode = cIter.EntryFileMode; entry.SetObjectIdFromRaw(cIter.IdBuffer, cIter.IdOffset); DirCacheIterator dcIter = walk.GetTree <DirCacheIterator>(1); if (dcIter != null && dcIter.IdEqual(cIter)) { DirCacheEntry indexEntry = dcIter.GetDirCacheEntry(); entry.LastModified = indexEntry.LastModified; entry.SetLength(indexEntry.Length); } editor.Add(new _PathEdit_356(entry, entry)); } editor.Commit(); } finally { dc.Unlock(); if (walk != null) { walk.Release(); } } }
private void ResetIndexForPaths(RevCommit commit) { DirCache dc = null; DirCacheEditor edit; try { dc = repo.LockDirCache(); edit = dc.Editor(); TreeWalk tw = new TreeWalk(repo); tw.AddTree(new DirCacheIterator(dc)); tw.AddTree(commit.Tree); tw.Filter = PathFilterGroup.CreateFromStrings(filepaths); while (tw.Next()) { string path = tw.PathString; // DirCacheIterator dci = tw.getTree(0, DirCacheIterator.class); CanonicalTreeParser tree = tw.GetTree <CanonicalTreeParser>(1); if (tree == null) { // file is not in the commit, remove from index edit.Add(new DirCacheEditor.DeletePath(path)); } else { // revert index to commit edit.Add(new _PathEdit_281(tree, path)); } } edit.Commit(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (dc != null) { dc.Unlock(); } } }
public virtual void TestRecursiveFiltering() { ObjectInserter odi = db.NewObjectInserter(); ObjectId aSth = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString( "a.sth")); ObjectId aTxt = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString( "a.txt")); ObjectId bSth = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString( "b.sth")); ObjectId bTxt = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString( "b.txt")); DirCache dc = db.ReadDirCache(); DirCacheBuilder builder = dc.Builder(); DirCacheEntry aSthEntry = new DirCacheEntry("a.sth"); aSthEntry.FileMode = FileMode.REGULAR_FILE; aSthEntry.SetObjectId(aSth); DirCacheEntry aTxtEntry = new DirCacheEntry("a.txt"); aTxtEntry.FileMode = FileMode.REGULAR_FILE; aTxtEntry.SetObjectId(aTxt); builder.Add(aSthEntry); builder.Add(aTxtEntry); DirCacheEntry bSthEntry = new DirCacheEntry("sub/b.sth"); bSthEntry.FileMode = FileMode.REGULAR_FILE; bSthEntry.SetObjectId(bSth); DirCacheEntry bTxtEntry = new DirCacheEntry("sub/b.txt"); bTxtEntry.FileMode = FileMode.REGULAR_FILE; bTxtEntry.SetObjectId(bTxt); builder.Add(bSthEntry); builder.Add(bTxtEntry); builder.Finish(); ObjectId treeId = dc.WriteTree(odi); odi.Flush(); TreeWalk tw = new TreeWalk(db); tw.Recursive = true; tw.Filter = PathSuffixFilter.Create(".txt"); tw.AddTree(treeId); IList <string> paths = new List <string>(); while (tw.Next()) { paths.AddItem(tw.PathString); } IList <string> expected = new List <string>(); expected.AddItem("a.txt"); expected.AddItem("sub/b.txt"); NUnit.Framework.Assert.AreEqual(expected, paths); }
public virtual void ShouldListAddedFileInInitialCommit() { // given WriteTrashFile("a.txt", "content"); Git git = new Git(db); git.Add().AddFilepattern("a.txt").Call(); RevCommit c = git.Commit().SetMessage("initial commit").Call(); // when TreeWalk walk = new TreeWalk(db); walk.AddTree(new EmptyTreeIterator()); walk.AddTree(c.Tree); IList<DiffEntry> result = DiffEntry.Scan(walk); // then Assert.IsNotNull (result); Assert.AreEqual(1, result.Count); DiffEntry entry = result[0]; Assert.AreEqual(entry.GetChangeType(), DiffEntry.ChangeType.ADD); Assert.AreEqual(entry.GetNewPath(), "a.txt"); Assert.AreEqual(entry.GetOldPath(), DiffEntry.DEV_NULL); }
public IEnumerable<FileDiff> GetFileDiffs(string newHash, string oldHash) { NGit.Repository repo = this.git.GetRepository(); ObjectId newCommit = repo.Resolve(newHash + "^{tree}"); ObjectId oldCommit = repo.Resolve(oldHash + "^{tree}"); var walk = new TreeWalk(repo) { Recursive = true }; walk.AddTree(oldCommit); walk.AddTree(newCommit); IEnumerable<DiffEntry> entries = DiffEntry.Scan(walk); var diffs = entries.Where(diff => diff.GetNewId().Name != diff.GetOldId().Name); return from diffEntry in diffs let diffType = ToDiffType(diffEntry.GetChangeType()) let path = diffType == DiffType.Delete ? diffEntry.GetOldPath() : diffEntry.GetNewPath() select new FileDiff(path, diffType); }
/// <summary> /// Load the config for this walk from /// <code>.gitmodules</code> /// . /// <p> /// Uses the root tree if /// <see cref="SetRootTree(NGit.Treewalk.AbstractTreeIterator)">SetRootTree(NGit.Treewalk.AbstractTreeIterator) /// </see> /// was /// previously called, otherwise uses the working tree. /// <p> /// If no submodule config is found, loads an empty config. /// </summary> /// <returns>this generator</returns> /// <exception cref="System.IO.IOException">if an error occurred, or if the repository is bare /// </exception> /// <exception cref="NGit.Errors.ConfigInvalidException">NGit.Errors.ConfigInvalidException /// </exception> public virtual NGit.Submodule.SubmoduleWalk LoadModulesConfig() { if (rootTree == null) { FilePath modulesFile = new FilePath(repository.WorkTree, Constants.DOT_GIT_MODULES ); FileBasedConfig config = new FileBasedConfig(modulesFile, repository.FileSystem); config.Load(); modulesConfig = config; } else { TreeWalk configWalk = new TreeWalk(repository); try { configWalk.AddTree(rootTree); // The root tree may be part of the submodule walk, so we need to revert // it after this walk. int idx; for (idx = 0; !rootTree.First; idx++) { rootTree.Back(1); } try { configWalk.Recursive = false; PathFilter filter = PathFilter.Create(Constants.DOT_GIT_MODULES); configWalk.Filter = filter; while (configWalk.Next()) { if (filter.IsDone(configWalk)) { modulesConfig = new BlobBasedConfig(null, repository, configWalk.GetObjectId(0)); return(this); } } modulesConfig = new Config(); } finally { if (idx > 0) { rootTree.Next(idx); } } } finally { configWalk.Release(); } } return(this); }
public static List<string> GetConflictedFiles (NGit.Repository repo) { List<string> list = new List<string> (); TreeWalk treeWalk = new TreeWalk (repo); treeWalk.Reset (); treeWalk.Recursive = true; DirCache dc = repo.ReadDirCache (); treeWalk.AddTree (new DirCacheIterator (dc)); while (treeWalk.Next()) { DirCacheIterator dirCacheIterator = treeWalk.GetTree<DirCacheIterator>(0); var ce = dirCacheIterator.GetDirCacheEntry (); if (ce != null && ce.Stage == 1) list.Add (ce.PathString); } return list; }
public virtual void TestPathFilterGroup_DoesNotSkipTail() { DirCache dc = db.ReadDirCache(); FileMode mode = FileMode.REGULAR_FILE; string[] paths = new string[] { "a.", "a/b", "a/c", "a/d", "a0b" }; DirCacheEntry[] ents = new DirCacheEntry[paths.Length]; for (int i = 0; i < paths.Length; i++) { ents[i] = new DirCacheEntry(paths[i]); ents[i].FileMode = mode; } { DirCacheBuilder b = dc.Builder(); for (int i_1 = 0; i_1 < ents.Length; i_1++) { b.Add(ents[i_1]); } b.Finish(); } int expIdx = 2; DirCacheBuilder b_1 = dc.Builder(); TreeWalk tw = new TreeWalk(db); tw.AddTree(new DirCacheBuildIterator(b_1)); tw.Recursive = true; tw.Filter = PathFilterGroup.CreateFromStrings(Collections.Singleton(paths[expIdx] )); NUnit.Framework.Assert.IsTrue(tw.Next(), "found " + paths[expIdx]); DirCacheIterator c = tw.GetTree<DirCacheIterator>(0); NUnit.Framework.Assert.IsNotNull(c); NUnit.Framework.Assert.AreEqual(expIdx, c.ptr); NUnit.Framework.Assert.AreSame(ents[expIdx], c.GetDirCacheEntry()); NUnit.Framework.Assert.AreEqual(paths[expIdx], tw.PathString); NUnit.Framework.Assert.AreEqual(mode.GetBits(), tw.GetRawMode(0)); NUnit.Framework.Assert.AreSame(mode, tw.GetFileMode(0)); b_1.Add(c.GetDirCacheEntry()); NUnit.Framework.Assert.IsFalse(tw.Next(), "no more entries"); b_1.Finish(); NUnit.Framework.Assert.AreEqual(ents.Length, dc.GetEntryCount()); for (int i_2 = 0; i_2 < ents.Length; i_2++) { NUnit.Framework.Assert.AreSame(ents[i_2], dc.GetEntry(i_2)); } }
public static string GetFileContent(this RevCommit commit, string path, Repository repository) { var treeWalk = new TreeWalk(repository) {Recursive = true, Filter = PathFilter.Create(path)}; treeWalk.AddTree(commit.Tree); if (!treeWalk.Next()) { return string.Empty; } var objectId = treeWalk.GetObjectId(0); var loader = repository.Open(objectId); using (var stream = loader.OpenStream()) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } }
/// <exception cref="NGit.Errors.CorruptObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void AssertWorkDir(Dictionary<string, string> i) { TreeWalk walk = new TreeWalk(db); walk.Recursive = true; walk.AddTree(new FileTreeIterator(db)); string expectedValue; string path; int nrFiles = 0; FileTreeIterator ft; while (walk.Next()) { ft = walk.GetTree<FileTreeIterator>(0); path = ft.EntryPathString; expectedValue = i.Get(path); NUnit.Framework.Assert.IsNotNull(expectedValue, "found unexpected file for path " + path + " in workdir"); FilePath file = new FilePath(db.WorkTree, path); NUnit.Framework.Assert.IsTrue(file.Exists()); if (file.IsFile()) { FileInputStream @is = new FileInputStream(file); byte[] buffer = new byte[(int)file.Length()]; int offset = 0; int numRead = 0; while (offset < buffer.Length && (numRead = @is.Read(buffer, offset, buffer.Length - offset)) >= 0) { offset += numRead; } @is.Close(); CollectionAssert.AreEqual (buffer, Sharpen.Runtime.GetBytesForString(i.Get(path)), "unexpected content for path " + path + " in workDir. "); nrFiles++; } } NUnit.Framework.Assert.AreEqual(i.Count, nrFiles, "WorkDir has not the right size." ); }
public static API_NGit files(this API_NGit nGit,string commitId, Action<TreeWalk> onTreeWalk) { try { var headCommit = nGit.Repository.Resolve(commitId); if (commitId.notNull()) { var revWalk = new RevWalk(nGit.Repository); var commit = revWalk.ParseCommit(headCommit); var treeWalk = new TreeWalk(nGit.Repository); var tree = commit.Tree; treeWalk.AddTree(tree); treeWalk.Recursive = true; while (treeWalk.Next()) onTreeWalk(treeWalk); } } catch (Exception ex) { ex.log("[API_NGit][getRepoFiles]"); } return nGit ; }
public GitFileStatus GetFileStatusNoCache(string fileName) { if (Directory.Exists(fileName)) return GitFileStatus.Ignored; var fileNameRel = GetRelativeFileNameForGit(fileName); TreeWalk treeWalk = new TreeWalk(this.repository) { Recursive = true }; RevTree revTree = head == null ? null : new RevWalk(repository).ParseTree(head); if (revTree != null) { treeWalk.AddTree(revTree); } else { treeWalk.AddTree(new EmptyTreeIterator()); } treeWalk.AddTree(new DirCacheIterator(dirCache)); treeWalk.AddTree(new FileTreeIterator(this.repository)); var filters = new TreeFilter[] { PathFilter.Create(fileNameRel), new SkipWorkTreeFilter(INDEX), new IndexDiffFilter(INDEX, WORKDIR) }; treeWalk.Filter = AndTreeFilter.Create(filters); var status = GitFileStatus.NotControlled; if (treeWalk.Next()) { status = GetFileStatus(treeWalk); } if (status == GitFileStatus.NotControlled) { var dirCacheEntry2 = dirCache.GetEntry(fileNameRel); if (dirCacheEntry2 != null) { var treeEntry2 = TreeWalk.ForPath(repository, fileNameRel, revTree); if (treeEntry2 != null && treeEntry2.GetObjectId(0).Equals(dirCacheEntry2.GetObjectId())) return GitFileStatus.Tracked; } } return GitFileStatus.NotControlled; }
private static IEnumerable<DiffEntry> GetDiffEntries(this RevCommit commit, Repository repository) { var tw = new TreeWalk(repository) { Recursive = true }; if (commit.ParentCount > 0) { if (commit.Parents.First().Tree != null) { tw.AddTree(commit.Parents.First().Tree); } else { tw.AddTree(new EmptyTreeIterator()); } } else { tw.AddTree(new EmptyTreeIterator()); } tw.Filter = TreeFilter.ANY_DIFF; tw.AddTree(commit.Tree); return DiffEntry.Scan(tw); }
/// <summary> /// Run the diff operation. Until this is called, all lists will be empty /// </summary> /// <returns>true if anything is different between index, tree, and workdir</returns> private void UpdateDirectory (IEnumerable<string> paths, bool recursive) { RevWalk rw = new RevWalk (Repository); ObjectId id = Repository.Resolve (Constants.HEAD); var commit = id != null ? rw.ParseCommit (id) : null; TreeWalk treeWalk = new TreeWalk (Repository); treeWalk.Reset (); treeWalk.Recursive = false; if (commit != null) treeWalk.AddTree (commit.Tree); else treeWalk.AddTree (new EmptyTreeIterator()); DirCache dc = Repository.ReadDirCache (); treeWalk.AddTree (new DirCacheIterator (dc)); FileTreeIterator workTree = new FileTreeIterator (Repository.WorkTree, Repository.FileSystem, WorkingTreeOptions.KEY.Parse(Repository.GetConfig())); treeWalk.AddTree (workTree); List<TreeFilter> filters = new List<TreeFilter> (); filters.Add (new SkipWorkTreeFilter(1)); var pathFilters = paths.Where (p => p != ".").Select (p => PathFilter.Create (p)).ToArray (); if (pathFilters.Length > 1) { filters.Add (OrTreeFilter.Create (pathFilters)); // Use an OR to join all path filters } else if (pathFilters.Length == 1) filters.Add (pathFilters[0]); if (filters.Count > 1) treeWalk.Filter = AndTreeFilter.Create(filters); else treeWalk.Filter = filters[0]; while (treeWalk.Next()) { AbstractTreeIterator treeIterator = treeWalk.GetTree<AbstractTreeIterator>(0); DirCacheIterator dirCacheIterator = treeWalk.GetTree<DirCacheIterator>(1); WorkingTreeIterator workingTreeIterator = treeWalk.GetTree<WorkingTreeIterator>(2); NGit.FileMode fileModeTree = treeWalk.GetFileMode(0); if (treeWalk.IsSubtree) { treeWalk.EnterSubtree (); continue; } int stage = dirCacheIterator != null ? dirCacheIterator.GetDirCacheEntry ().Stage : 0; if (stage > 1) continue; else if (stage == 1) { MergeConflict.Add(dirCacheIterator.EntryPathString); changesExist = true; continue; } if (treeIterator != null) { if (dirCacheIterator != null) { if (!treeIterator.EntryObjectId.Equals(dirCacheIterator.EntryObjectId)) { // in repo, in index, content diff => changed Modified.Add(dirCacheIterator.EntryPathString); changesExist = true; } } else { // in repo, not in index => removed if (!fileModeTree.Equals(NGit.FileMode.TYPE_TREE)) { Removed.Add(treeIterator.EntryPathString); changesExist = true; } } } else { if (dirCacheIterator != null) { // not in repo, in index => added Added.Add(dirCacheIterator.EntryPathString); changesExist = true; } else { // not in repo, not in index => untracked if (workingTreeIterator != null && !workingTreeIterator.IsEntryIgnored()) { Untracked.Add(workingTreeIterator.EntryPathString); changesExist = true; } } } if (dirCacheIterator != null) { if (workingTreeIterator == null) { // in index, not in workdir => missing Missing.Add(dirCacheIterator.EntryPathString); changesExist = true; } else { // Workaround to file time resolution issues long itime = dirCacheIterator.GetDirCacheEntry ().LastModified; long ftime = workingTreeIterator.GetEntryLastModified (); if (itime / 1000 != ftime / 1000) { if (!dirCacheIterator.IdEqual(workingTreeIterator)) { // in index, in workdir, content differs => modified Modified.Add(dirCacheIterator.EntryPathString); changesExist = true; } } } } } }
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()); }
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 TestTwoLevelSubtree_Recursive() { DirCache dc = DirCache.NewInCore(); FileMode mode = FileMode.REGULAR_FILE; string[] paths = new string[] { "a.", "a/b", "a/c/e", "a/c/f", "a/d", "a0b" }; DirCacheEntry[] ents = new DirCacheEntry[paths.Length]; for (int i = 0; i < paths.Length; i++) { ents[i] = new DirCacheEntry(paths[i]); ents[i].FileMode = mode; } DirCacheBuilder b = dc.Builder(); for (int i_1 = 0; i_1 < ents.Length; i_1++) { b.Add(ents[i_1]); } b.Finish(); TreeWalk tw = new TreeWalk(db); tw.AddTree(new DirCacheIterator(dc)); tw.Recursive = true; int pathIdx = 0; while (tw.Next()) { DirCacheIterator c = tw.GetTree<DirCacheIterator>(0); NUnit.Framework.Assert.IsNotNull(c); NUnit.Framework.Assert.AreEqual(pathIdx, c.ptr); NUnit.Framework.Assert.AreSame(ents[pathIdx], c.GetDirCacheEntry()); NUnit.Framework.Assert.AreEqual(paths[pathIdx], tw.PathString); NUnit.Framework.Assert.AreEqual(mode.GetBits(), tw.GetRawMode(0)); NUnit.Framework.Assert.AreSame(mode, tw.GetFileMode(0)); pathIdx++; } NUnit.Framework.Assert.AreEqual(paths.Length, pathIdx); }
public static List<GitData_File> gitData_Files(this API_NGit nGit, int max_FilesToShow, string commitSha1) { var gitData_Files = new List<GitData_File>(); try { var headCommit = nGit.Repository.Resolve(commitSha1); if (commitSha1.notNull()) { var revWalk = new RevWalk(nGit.Repository); var commit = revWalk.ParseCommit(headCommit); var treeWalk = new TreeWalk(nGit.Repository); var tree = commit.Tree; treeWalk.AddTree(tree); treeWalk.Recursive = true; while (treeWalk.Next() && (max_FilesToShow == -1) || gitData_Files.size() < max_FilesToShow) gitData_Files.add_File(treeWalk); //repoFiles.Add(treeWalk.PathString); } } catch(Exception ex) { ex.log("[API_NGit][gitData_Files]"); } return gitData_Files; }
public string ReadCommit(string commitId, string fileName) { var repo = m_git.GetRepository(); var id = ObjectId.FromString(commitId); RevCommit commit = null; try { commit = ParseCommit(repo, id); if (commit == null) return null; } catch (Exception ex) { Trace.WriteLine(ex.Message); return null; } //var commits = m_git.Log().AddRange(id, id).Call(); //var commit = commits.SingleOrDefault(); //if (commit == null) // return null; TreeWalk walk = new TreeWalk(repo); //RevWalk r = new RevWalk(m_git.GetRepository()); //var tree = r.ParseTree(commit.Tree.Id); //r.LookupTree( //walk.AddTree(new FileTreeIterator(repo)); //var tree = ParseTree(repo, commit.Tree.Id); walk.AddTree(commit.Tree); var filter = GetGitFriendlyName(fileName); walk.Filter = PathFilterGroup.CreateFromStrings(new string[]{filter}); //walk.EnterSubtree(); while (walk.Next()) { var path = walk.PathString; if (walk.IsSubtree) { walk.EnterSubtree(); continue; } if (path == filter) { var cur = walk.GetObjectId(0); ObjectLoader ol = repo.Open(cur); // //Console.WriteLine(string.Format("Path: {0}{1}", walk.PathString, walk.IsSubtree ? "/" : "")); // //var loader = reader.Open(commit.Tree.Id); var text = ""; using (var stream = ol.OpenStream()) using (var sr = new System.IO.StreamReader(stream)) { text = sr.ReadToEnd(); } return text; } } //walk.Reset(); //reader.Open(); return ""; }
public virtual void TestSingleSubtree_NoRecursion() { DirCache dc = DirCache.NewInCore(); string[] paths = new string[] { "a.", "a/b", "a/c", "a/d", "a0b" }; DirCacheEntry[] ents = new DirCacheEntry[paths.Length]; for (int i = 0; i < paths.Length; i++) { ents[i] = new DirCacheEntry(paths[i]); ents[i].FileMode = FileMode.REGULAR_FILE; } DirCacheBuilder b = dc.Builder(); for (int i_1 = 0; i_1 < ents.Length; i_1++) { b.Add(ents[i_1]); } b.Finish(); string[] expPaths = new string[] { "a.", "a", "a0b" }; FileMode[] expModes = new FileMode[] { FileMode.REGULAR_FILE, FileMode.TREE, FileMode .REGULAR_FILE }; int[] expPos = new int[] { 0, -1, 4 }; DirCacheIterator i_2 = new DirCacheIterator(dc); TreeWalk tw = new TreeWalk(db); tw.AddTree(i_2); tw.Recursive = false; int pathIdx = 0; while (tw.Next()) { NUnit.Framework.Assert.AreSame(i_2, tw.GetTree<DirCacheIterator>(0)); NUnit.Framework.Assert.AreEqual(expModes[pathIdx].GetBits(), tw.GetRawMode(0)); NUnit.Framework.Assert.AreSame(expModes[pathIdx], tw.GetFileMode(0)); NUnit.Framework.Assert.AreEqual(expPaths[pathIdx], tw.PathString); if (expPos[pathIdx] >= 0) { NUnit.Framework.Assert.AreEqual(expPos[pathIdx], i_2.ptr); NUnit.Framework.Assert.AreSame(ents[expPos[pathIdx]], i_2.GetDirCacheEntry()); } else { NUnit.Framework.Assert.AreSame(FileMode.TREE, tw.GetFileMode(0)); } pathIdx++; } NUnit.Framework.Assert.AreEqual(expPaths.Length, pathIdx); }
/// <summary>Recursively add an entire tree into this builder.</summary> /// <remarks> /// Recursively add an entire tree into this builder. /// <p> /// If pathPrefix is "a/b" and the tree contains file "c" then the resulting /// DirCacheEntry will have the path "a/b/c". /// <p> /// All entries are inserted at stage 0, therefore assuming that the /// application will not insert any other paths with the same pathPrefix. /// </remarks> /// <param name="pathPrefix"> /// UTF-8 encoded prefix to mount the tree's entries at. If the /// path does not end with '/' one will be automatically inserted /// as necessary. /// </param> /// <param name="stage">stage of the entries when adding them.</param> /// <param name="reader"> /// reader the tree(s) will be read from during recursive /// traversal. This must be the same repository that the resulting /// DirCache would be written out to (or used in) otherwise the /// caller is simply asking for deferred MissingObjectExceptions. /// Caller is responsible for releasing this reader when done. /// </param> /// <param name="tree"> /// the tree to recursively add. This tree's contents will appear /// under <code>pathPrefix</code>. The ObjectId must be that of a /// tree; the caller is responsible for dereferencing a tag or /// commit (if necessary). /// </param> /// <exception cref="System.IO.IOException">a tree cannot be read to iterate through its entries. /// </exception> public virtual void AddTree(byte[] pathPrefix, int stage, ObjectReader reader, AnyObjectId tree) { TreeWalk tw = new TreeWalk(reader); tw.AddTree(new CanonicalTreeParser(pathPrefix, reader, tree.ToObjectId())); tw.Recursive = true; if (tw.Next()) { DirCacheEntry newEntry = ToEntry(stage, tw); BeforeAdd(newEntry); FastAdd(newEntry); while (tw.Next()) { FastAdd(ToEntry(stage, tw)); } } }
public virtual void SubmoduleWithNoHead() { Git git = new Git(db); WriteTrashFile("file.txt", "content"); git.Add().AddFilepattern("file.txt").Call(); RevCommit id = git.Commit().SetMessage("create file").Call(); string path = "sub"; DirCache cache = db.LockDirCache(); DirCacheEditor editor = cache.Editor(); editor.Add(new _PathEdit_345(id, path)); editor.Commit(); NUnit.Framework.Assert.IsNotNull(Git.Init().SetDirectory(new FilePath(db.WorkTree , path)).Call().GetRepository()); TreeWalk walk = new TreeWalk(db); DirCacheIterator indexIter = new DirCacheIterator(db.ReadDirCache()); FileTreeIterator workTreeIter = new FileTreeIterator(db); walk.AddTree(indexIter); walk.AddTree(workTreeIter); walk.Filter = PathFilter.Create(path); NUnit.Framework.Assert.IsTrue(walk.Next()); NUnit.Framework.Assert.IsFalse(indexIter.IdEqual(workTreeIter)); NUnit.Framework.Assert.AreEqual(ObjectId.ZeroId, workTreeIter.EntryObjectId); }
public virtual void SubmoduleNestedWithHeadMatchingIndex() { Git git = new Git(db); WriteTrashFile("file.txt", "content"); git.Add().AddFilepattern("file.txt").Call(); RevCommit id = git.Commit().SetMessage("create file").Call(); string path = "sub/dir1/dir2"; DirCache cache = db.LockDirCache(); DirCacheEditor editor = cache.Editor(); editor.Add(new _PathEdit_412(id, path)); editor.Commit(); Git.CloneRepository().SetURI(db.Directory.ToURI().ToString()).SetDirectory(new FilePath (db.WorkTree, path)).Call().GetRepository().Close(); TreeWalk walk = new TreeWalk(db); DirCacheIterator indexIter = new DirCacheIterator(db.ReadDirCache()); FileTreeIterator workTreeIter = new FileTreeIterator(db); walk.AddTree(indexIter); walk.AddTree(workTreeIter); walk.Filter = PathFilter.Create(path); NUnit.Framework.Assert.IsTrue(walk.Next()); NUnit.Framework.Assert.IsTrue(indexIter.IdEqual(workTreeIter)); }
private IList<GitFile> GetChangedFilesImpl(bool initializeCache) { if (!HasGitRepository) return new List<GitFile>(); var list = new List<GitFile>(); // initialize the cache if (initializeCache) { var treeWalk = new TreeWalk(this.repository); treeWalk.Recursive = true; treeWalk.Filter = TreeFilter.ALL; var id = repository.Resolve(Constants.HEAD); if (id != null) treeWalk.AddTree(new RevWalk(repository).ParseTree(id)); else treeWalk.AddTree(new EmptyTreeIterator()); while (treeWalk.Next()) { string pathString = treeWalk.PathString; var fileName = GetFullPath(pathString); if (Directory.Exists(fileName)) continue; // this excludes sub modules cache[pathString] = GitFileStatus.Tracked; } } if (GitBash.Exists) { var result = GitBash.Run("status --porcelain -z --untracked-files", this.GitWorkingDirectory); if (!result.HasError) return ParseGitStatus(result.Output); return list; } else { var treeWalk = new TreeWalk(this.repository); treeWalk.Recursive = true; treeWalk.Filter = TreeFilter.ANY_DIFF; var id = repository.Resolve(Constants.HEAD); if (id != null) { treeWalk.AddTree(new RevWalk(repository).ParseTree(id)); } else { treeWalk.AddTree(new EmptyTreeIterator()); } treeWalk.AddTree(new DirCacheIterator(this.repository.ReadDirCache())); treeWalk.AddTree(new FileTreeIterator(this.repository)); var filters = new TreeFilter[] { new SkipWorkTreeFilter(INDEX), new IndexDiffFilter(INDEX, WORKDIR) }; treeWalk.Filter = AndTreeFilter.Create(filters); while (treeWalk.Next()) { WorkingTreeIterator workingTreeIterator = treeWalk.GetTree<WorkingTreeIterator>(WORKDIR); if (workingTreeIterator != null && workingTreeIterator.IsEntryIgnored()) continue; var fileName = GetFullPath(treeWalk.PathString); if (Directory.Exists(fileName)) continue; // this excludes sub modules var status = GetFileStatus(treeWalk); list.Add(new GitFile { FileName = GetRelativeFileName(fileName), Status = status }); this.cache[GetCacheKey(fileName)] = status; } return list; } }
public virtual void TestTwoLevelSubtree_FilterPath() { DirCache dc = DirCache.NewInCore(); FileMode mode = FileMode.REGULAR_FILE; string[] paths = new string[] { "a.", "a/b", "a/c/e", "a/c/f", "a/d", "a0b" }; DirCacheEntry[] ents = new DirCacheEntry[paths.Length]; for (int i = 0; i < paths.Length; i++) { ents[i] = new DirCacheEntry(paths[i]); ents[i].FileMode = mode; } DirCacheBuilder b = dc.Builder(); for (int i_1 = 0; i_1 < ents.Length; i_1++) { b.Add(ents[i_1]); } b.Finish(); TreeWalk tw = new TreeWalk(db); for (int victimIdx = 0; victimIdx < paths.Length; victimIdx++) { tw.Reset(); tw.AddTree(new DirCacheIterator(dc)); tw.Filter = PathFilterGroup.CreateFromStrings(Collections.Singleton(paths[victimIdx ])); tw.Recursive = tw.Filter.ShouldBeRecursive(); NUnit.Framework.Assert.IsTrue(tw.Next()); DirCacheIterator c = tw.GetTree<DirCacheIterator>(0); NUnit.Framework.Assert.IsNotNull(c); NUnit.Framework.Assert.AreEqual(victimIdx, c.ptr); NUnit.Framework.Assert.AreSame(ents[victimIdx], c.GetDirCacheEntry()); NUnit.Framework.Assert.AreEqual(paths[victimIdx], tw.PathString); NUnit.Framework.Assert.AreEqual(mode.GetBits(), tw.GetRawMode(0)); NUnit.Framework.Assert.AreSame(mode, tw.GetFileMode(0)); NUnit.Framework.Assert.IsFalse(tw.Next()); } }
/// <summary>Run the diff operation.</summary> /// <remarks> /// Run the diff operation. Until this is called, all lists will be empty. /// <p> /// The operation may be aborted by the progress monitor. In that event it /// will report what was found before the cancel operation was detected. /// Callers should ignore the result if monitor.isCancelled() is true. If a /// progress monitor is not needed, callers should use /// <see cref="Diff()">Diff()</see> /// instead. Progress reporting is crude and approximate and only intended /// for informing the user. /// </remarks> /// <param name="monitor">for reporting progress, may be null</param> /// <param name="estWorkTreeSize">number or estimated files in the working tree</param> /// <param name="estIndexSize">number of estimated entries in the cache</param> /// <param name="title"></param> /// <returns>if anything is different between index, tree, and workdir</returns> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> public virtual bool Diff(ProgressMonitor monitor, int estWorkTreeSize, int estIndexSize , string title) { dirCache = repository.ReadDirCache(); TreeWalk treeWalk = new TreeWalk(repository); treeWalk.Recursive = true; // add the trees (tree, dirchache, workdir) if (tree != null) { treeWalk.AddTree(tree); } else { treeWalk.AddTree(new EmptyTreeIterator()); } treeWalk.AddTree(new DirCacheIterator(dirCache)); treeWalk.AddTree(initialWorkingTreeIterator); ICollection<TreeFilter> filters = new AList<TreeFilter>(4); if (monitor != null) { // Get the maximum size of the work tree and index // and add some (quite arbitrary) if (estIndexSize == 0) { estIndexSize = dirCache.GetEntryCount(); } int total = Math.Max(estIndexSize * 10 / 9, estWorkTreeSize * 10 / 9); monitor.BeginTask(title, total); filters.AddItem(new IndexDiff.ProgressReportingFilter(monitor, total)); } if (filter != null) { filters.AddItem(filter); } filters.AddItem(new SkipWorkTreeFilter(INDEX)); filters.AddItem(new IndexDiffFilter(INDEX, WORKDIR)); treeWalk.Filter = AndTreeFilter.Create(filters); while (treeWalk.Next()) { AbstractTreeIterator treeIterator = treeWalk.GetTree<AbstractTreeIterator>(TREE); DirCacheIterator dirCacheIterator = treeWalk.GetTree<DirCacheIterator>(INDEX); WorkingTreeIterator workingTreeIterator = treeWalk.GetTree<WorkingTreeIterator>(WORKDIR ); if (treeIterator != null) { if (dirCacheIterator != null) { if (!treeIterator.IdEqual(dirCacheIterator) || treeIterator.EntryRawMode != dirCacheIterator .EntryRawMode) { // in repo, in index, content diff => changed changed.AddItem(treeWalk.PathString); } } else { // in repo, not in index => removed removed.AddItem(treeWalk.PathString); if (workingTreeIterator != null) { untracked.AddItem(treeWalk.PathString); } } } else { if (dirCacheIterator != null) { // not in repo, in index => added added.AddItem(treeWalk.PathString); } else { // not in repo, not in index => untracked if (workingTreeIterator != null && !workingTreeIterator.IsEntryIgnored()) { untracked.AddItem(treeWalk.PathString); } } } if (dirCacheIterator != null) { if (workingTreeIterator == null) { // in index, not in workdir => missing missing.AddItem(treeWalk.PathString); } else { if (workingTreeIterator.IsModified(dirCacheIterator.GetDirCacheEntry(), true)) { // in index, in workdir, content differs => modified modified.AddItem(treeWalk.PathString); } } } } // consume the remaining work if (monitor != null) { monitor.EndTask(); } if (added.IsEmpty() && changed.IsEmpty() && removed.IsEmpty() && missing.IsEmpty( ) && modified.IsEmpty() && untracked.IsEmpty()) { return false; } else { return true; } }
public virtual void TestRemovedSubtree() { FilePath path = JGitTestUtil.GetTestResourceFile("dircache.testRemovedSubtree"); DirCache dc = DirCache.Read(path, FS.DETECTED); NUnit.Framework.Assert.AreEqual(2, dc.GetEntryCount()); TreeWalk tw = new TreeWalk(db); tw.Recursive = true; tw.AddTree(new DirCacheIterator(dc)); NUnit.Framework.Assert.IsTrue(tw.Next()); NUnit.Framework.Assert.AreEqual("a/a", tw.PathString); NUnit.Framework.Assert.AreSame(FileMode.REGULAR_FILE, tw.GetFileMode(0)); NUnit.Framework.Assert.IsTrue(tw.Next()); NUnit.Framework.Assert.AreEqual("q", tw.PathString); NUnit.Framework.Assert.AreSame(FileMode.REGULAR_FILE, tw.GetFileMode(0)); NUnit.Framework.Assert.IsFalse(tw.Next()); }
public virtual void TestNoSubtree_WithTreeWalk() { DirCache dc = DirCache.NewInCore(); string[] paths = new string[] { "a.", "a0b" }; FileMode[] modes = new FileMode[] { FileMode.EXECUTABLE_FILE, FileMode.GITLINK }; DirCacheEntry[] ents = new DirCacheEntry[paths.Length]; for (int i = 0; i < paths.Length; i++) { ents[i] = new DirCacheEntry(paths[i]); ents[i].FileMode = modes[i]; } DirCacheBuilder b = dc.Builder(); for (int i_1 = 0; i_1 < ents.Length; i_1++) { b.Add(ents[i_1]); } b.Finish(); DirCacheIterator i_2 = new DirCacheIterator(dc); TreeWalk tw = new TreeWalk(db); tw.AddTree(i_2); int pathIdx = 0; while (tw.Next()) { NUnit.Framework.Assert.AreSame(i_2, tw.GetTree<DirCacheIterator>(0)); NUnit.Framework.Assert.AreEqual(pathIdx, i_2.ptr); NUnit.Framework.Assert.AreSame(ents[pathIdx], i_2.GetDirCacheEntry()); NUnit.Framework.Assert.AreEqual(paths[pathIdx], tw.PathString); NUnit.Framework.Assert.AreEqual(modes[pathIdx].GetBits(), tw.GetRawMode(0)); NUnit.Framework.Assert.AreSame(modes[pathIdx], tw.GetFileMode(0)); pathIdx++; } NUnit.Framework.Assert.AreEqual(paths.Length, pathIdx); }
public virtual void TestFindObjects() { DirCache tree0 = DirCache.NewInCore(); DirCacheBuilder b0 = tree0.Builder(); ObjectReader or = db.NewObjectReader(); ObjectInserter oi = db.NewObjectInserter(); DirCacheEntry aDotB = CreateEntry("a.b", EXECUTABLE_FILE); b0.Add(aDotB); DirCacheEntry aSlashB = CreateEntry("a/b", REGULAR_FILE); b0.Add(aSlashB); DirCacheEntry aSlashCSlashD = CreateEntry("a/c/d", REGULAR_FILE); b0.Add(aSlashCSlashD); DirCacheEntry aZeroB = CreateEntry("a0b", SYMLINK); b0.Add(aZeroB); b0.Finish(); NUnit.Framework.Assert.AreEqual(4, tree0.GetEntryCount()); ObjectId tree = tree0.WriteTree(oi); // Find the directories that were implicitly created above. TreeWalk tw = new TreeWalk(or); tw.AddTree(tree); ObjectId a = null; ObjectId aSlashC = null; while (tw.Next()) { if (tw.PathString.Equals("a")) { a = tw.GetObjectId(0); tw.EnterSubtree(); while (tw.Next()) { if (tw.PathString.Equals("a/c")) { aSlashC = tw.GetObjectId(0); break; } } break; } } NUnit.Framework.Assert.AreEqual(a, TreeWalk.ForPath(or, "a", tree).GetObjectId(0) ); NUnit.Framework.Assert.AreEqual(a, TreeWalk.ForPath(or, "a/", tree).GetObjectId(0 )); NUnit.Framework.Assert.AreEqual(null, TreeWalk.ForPath(or, "/a", tree)); NUnit.Framework.Assert.AreEqual(null, TreeWalk.ForPath(or, "/a/", tree)); NUnit.Framework.Assert.AreEqual(aDotB.GetObjectId(), TreeWalk.ForPath(or, "a.b", tree).GetObjectId(0)); NUnit.Framework.Assert.AreEqual(null, TreeWalk.ForPath(or, "/a.b", tree)); NUnit.Framework.Assert.AreEqual(null, TreeWalk.ForPath(or, "/a.b/", tree)); NUnit.Framework.Assert.AreEqual(aDotB.GetObjectId(), TreeWalk.ForPath(or, "a.b/", tree).GetObjectId(0)); NUnit.Framework.Assert.AreEqual(aZeroB.GetObjectId(), TreeWalk.ForPath(or, "a0b", tree).GetObjectId(0)); NUnit.Framework.Assert.AreEqual(aSlashB.GetObjectId(), TreeWalk.ForPath(or, "a/b" , tree).GetObjectId(0)); NUnit.Framework.Assert.AreEqual(aSlashB.GetObjectId(), TreeWalk.ForPath(or, "b", a).GetObjectId(0)); NUnit.Framework.Assert.AreEqual(aSlashC, TreeWalk.ForPath(or, "a/c", tree).GetObjectId (0)); NUnit.Framework.Assert.AreEqual(aSlashC, TreeWalk.ForPath(or, "c", a).GetObjectId (0)); NUnit.Framework.Assert.AreEqual(aSlashCSlashD.GetObjectId(), TreeWalk.ForPath(or, "a/c/d", tree).GetObjectId(0)); NUnit.Framework.Assert.AreEqual(aSlashCSlashD.GetObjectId(), TreeWalk.ForPath(or, "c/d", a).GetObjectId(0)); or.Release(); oi.Release(); }
/// <exception cref="NGit.Errors.CorruptObjectException"></exception> private void BeginWalk() { walk = new TreeWalk(db); walk.AddTree(new FileTreeIterator(db)); }