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()); } } }
static int GetFileLineCount(NGit.Repository repo, TreeWalk tw) { ObjectId id = tw.GetObjectId(0); byte[] data = repo.ObjectDatabase.Open(id).GetBytes(); return(new RawText(data).Size()); }
// reduce the visibility of the default constructor /// <summary>Convert the TreeWalk into DiffEntry headers.</summary> /// <remarks>Convert the TreeWalk into DiffEntry headers.</remarks> /// <param name="walk">the TreeWalk to walk through. Must have exactly two trees.</param> /// <returns>headers describing the changed files.</returns> /// <exception cref="System.IO.IOException">the repository cannot be accessed.</exception> public static IList <NGit.Diff.DiffEntry> Scan(TreeWalk walk) { IList <NGit.Diff.DiffEntry> r = new AList <NGit.Diff.DiffEntry>(); MutableObjectId idBuf = new MutableObjectId(); while (walk.Next()) { NGit.Diff.DiffEntry entry = new NGit.Diff.DiffEntry(); walk.GetObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.FromObjectId(idBuf); walk.GetObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.FromObjectId(idBuf); entry.oldMode = walk.GetFileMode(0); entry.newMode = walk.GetFileMode(1); entry.newPath = entry.oldPath = walk.PathString; if (entry.oldMode == FileMode.MISSING) { entry.oldPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.ADD; r.AddItem(entry); } else { if (entry.newMode == FileMode.MISSING) { entry.newPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.DELETE; r.AddItem(entry); } else { entry.changeType = DiffEntry.ChangeType.MODIFY; if (RenameDetector.SameType(entry.oldMode, entry.newMode)) { r.AddItem(entry); } else { Sharpen.Collections.AddAll(r, BreakModify(entry)); } } } } return(r); }
public virtual void TestRules1thru3_NoIndexEntry() { ObjectId head = BuildTree(Mk("foo")); TreeWalk tw = TreeWalk.ForPath(db, "foo", head); ObjectId objectId = tw.GetObjectId(0); ObjectId merge = db.NewObjectInserter().Insert(Constants.OBJ_TREE, new byte[0]); PrescanTwoTrees(head, merge); NUnit.Framework.Assert.IsTrue(GetRemoved().Contains("foo")); PrescanTwoTrees(merge, head); NUnit.Framework.Assert.AreEqual(objectId, GetUpdated().Get("foo")); merge = BuildTree(Mkmap("foo", "a")); tw = TreeWalk.ForPath(db, "foo", merge); ObjectId anotherId = tw.GetObjectId(0); PrescanTwoTrees(head, merge); NUnit.Framework.Assert.AreEqual(anotherId, GetUpdated().Get("foo")); }
public static GitData_File add_File(this List <GitData_File> gitData_Files, TreeWalk treeWalk) { var gitData_File = new GitData_File { FilePath = treeWalk.PathString, Sha1 = treeWalk.GetObjectId(0).sha1() }; gitData_Files.add(gitData_File); return(gitData_File); }
static RawText GetRawText(NGit.Repository repo, string file, RevCommit commit) { TreeWalk tw = TreeWalk.ForPath(repo, file, commit.Tree); if (tw == null) { return(new RawText(new byte[0])); } ObjectId objectID = tw.GetObjectId(0); byte[] data = repo.ObjectDatabase.Open(objectID).GetBytes(); return(new RawText(data)); }
/// <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>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 { TreeWalk treeWalk = new TreeWalk(revWalk.GetObjectReader()); treeWalk.Recursive = true; treeWalk.AddTree(new DirCacheIterator(dc)); treeWalk.Filter = PathFilterGroup.CreateFromStrings(paths); IList <string> files = new List <string>(); while (treeWalk.Next()) { files.AddItem(treeWalk.PathString); } if (startCommit != null || startPoint != null) { DirCacheEditor editor = dc.Editor(); TreeWalk startWalk = new TreeWalk(revWalk.GetObjectReader()); startWalk.Recursive = true; startWalk.Filter = treeWalk.Filter; startWalk.AddTree(revWalk.ParseCommit(GetStartPoint()).Tree); while (startWalk.Next()) { ObjectId blobId = startWalk.GetObjectId(0); editor.Add(new _PathEdit_258(blobId, startWalk.PathString)); } editor.Commit(); } FilePath workTree = repo.WorkTree; foreach (string file in files) { DirCacheCheckout.CheckoutEntry(repo, new FilePath(workTree, file), dc.GetEntry(file )); } } finally { dc.Unlock(); revWalk.Release(); } return(this); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> private static byte[] Read(Repository db, AnyObjectId treeish, string path) { ObjectReader or = db.NewObjectReader(); try { TreeWalk tree = TreeWalk.ForPath(or, path, AsTree(or, treeish)); if (tree == null) { throw new FileNotFoundException(MessageFormat.Format(JGitText.Get().entryNotFoundByPath , path)); } return(Read(or, tree.GetObjectId(0))); } finally { or.Release(); } }
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="System.IO.IOException"></exception> private bool Find(RevCommit commit, PathFilter path) { treeWalk.Filter = path; treeWalk.Reset(commit.Tree); while (treeWalk.Next()) { if (path.IsDone(treeWalk)) { if (treeWalk.GetFileMode(0).GetObjectType() != Constants.OBJ_BLOB) { return(false); } treeWalk.GetObjectId(idBuf, 0); return(true); } if (treeWalk.IsSubtree) { treeWalk.EnterSubtree(); } } return(false); }
private static string GetSnapshot(Repository repository, Git git, RevTree revTree, String file) { //Get snapshot , Retrive older version of an object TreeWalk treeWalk = TreeWalk.ForPath(git.GetRepository(), file, revTree); byte[] data = repository.Open(treeWalk.GetObjectId(0)).GetBytes(); return(System.Text.Encoding.UTF8.GetString(data)); //ObjectLoader loader = repository.Open(rev.ToObjectId()); //InputStream ttt = loader.OpenStream(); //string result = ttt.ToString(); //Retrive older version of an object //RevTree revTree = rev.Tree; //TreeWalk treeWalk = new TreeWalk(git.GetRepository()); //treeWalk.AddTree(revTree); //while (treeWalk.Next()) //{ // //compare treeWalk.NameString yourself // byte[] bytes = treeWalk.ObjectReader.Open(rev.ToObjectId()).GetCachedBytes(); // string result = System.Text.Encoding.UTF8.GetString(rev.RawBuffer); //} }
static int GetFileLineCount (NGit.Repository repo, TreeWalk tw) { ObjectId id = tw.GetObjectId (0); byte[] data = repo.ObjectDatabase.Open (id).GetBytes (); return new RawText (data).Size(); }
static IEnumerable<Change> CalculateCommitDiff (NGit.Repository repo, TreeWalk walk, RevCommit[] commits) { while (walk.Next ()) { int m0 = walk.GetRawMode (0); if (walk.TreeCount == 2) { int m1 = walk.GetRawMode (1); var change = new Change { ReferenceCommit = commits[0], ComparedCommit = commits[1], ReferencePermissions = walk.GetFileMode (0).GetBits (), ComparedPermissions = walk.GetFileMode (1).GetBits (), Name = walk.NameString, Path = walk.PathString }; if (m0 != 0 && m1 == 0) { change.ChangeType = ChangeType.Added; change.ComparedObject = walk.GetObjectId (0); } else if (m0 == 0 && m1 != 0) { change.ChangeType = ChangeType.Deleted; change.ReferenceObject = walk.GetObjectId (0); } else if (m0 != m1 && walk.IdEqual (0, 1)) { change.ChangeType = ChangeType.TypeChanged; change.ReferenceObject = walk.GetObjectId (0); change.ComparedObject = walk.GetObjectId (1); } else { change.ChangeType = ChangeType.Modified; change.ReferenceObject = walk.GetObjectId (0); change.ComparedObject = walk.GetObjectId (1); } yield return change; } else { var raw_modes = new int[walk.TreeCount - 1]; for (int i = 0; i < walk.TreeCount - 1; i++) raw_modes[i] = walk.GetRawMode (i + 1); //ComparedCommit = compared, var change = new Change { ReferenceCommit = commits[0], Name = walk.NameString, Path = walk.PathString }; if (m0 != 0 && raw_modes.All (m1 => m1 == 0)) { change.ChangeType = ChangeType.Added; change.ComparedObject = walk.GetObjectId (0); yield return change; } else if (m0 == 0 && raw_modes.Any (m1 => m1 != 0)) { change.ChangeType = ChangeType.Deleted; yield return change; // TODO: not sure if this condition suffices in some special cases. } else if (raw_modes.Select ((m1, i) => new { Mode = m1, Index = i + 1 }).All (x => !walk.IdEqual (0, x.Index))) { change.ChangeType = ChangeType.Modified; change.ReferenceObject = walk.GetObjectId (0); yield return change; } else if (raw_modes.Select ((m1, i) => new { Mode = m1, Index = i + 1 }).Any (x => m0 != x.Mode && walk.IdEqual (0, x.Index))) { change.ChangeType = ChangeType.TypeChanged; change.ReferenceObject = walk.GetObjectId (0); yield return change; } } } }
/// <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); }
/// <summary>Get object id of current submodule entry</summary> /// <returns>object id</returns> public virtual ObjectId GetObjectId() { return(walk.GetObjectId(0)); }
static IEnumerable <Change> CalculateCommitDiff(NGit.Repository repo, TreeWalk walk, RevCommit[] commits) { while (walk.Next()) { int m0 = walk.GetRawMode(0); if (walk.TreeCount == 2) { int m1 = walk.GetRawMode(1); var change = new Change { ReferenceCommit = commits[0], ComparedCommit = commits[1], ReferencePermissions = walk.GetFileMode(0).GetBits(), ComparedPermissions = walk.GetFileMode(1).GetBits(), Name = walk.NameString, Path = walk.PathString }; if (m0 != 0 && m1 == 0) { change.ChangeType = ChangeType.Added; change.ComparedObject = walk.GetObjectId(0); } else if (m0 == 0 && m1 != 0) { change.ChangeType = ChangeType.Deleted; change.ReferenceObject = walk.GetObjectId(0); } else if (m0 != m1 && walk.IdEqual(0, 1)) { change.ChangeType = ChangeType.TypeChanged; change.ReferenceObject = walk.GetObjectId(0); change.ComparedObject = walk.GetObjectId(1); } else { change.ChangeType = ChangeType.Modified; change.ReferenceObject = walk.GetObjectId(0); change.ComparedObject = walk.GetObjectId(1); } yield return(change); } else { var raw_modes = new int[walk.TreeCount - 1]; for (int i = 0; i < walk.TreeCount - 1; i++) { raw_modes[i] = walk.GetRawMode(i + 1); } //ComparedCommit = compared, var change = new Change { ReferenceCommit = commits[0], Name = walk.NameString, Path = walk.PathString }; if (m0 != 0 && raw_modes.All(m1 => m1 == 0)) { change.ChangeType = ChangeType.Added; change.ComparedObject = walk.GetObjectId(0); yield return(change); } else if (m0 == 0 && raw_modes.Any(m1 => m1 != 0)) { change.ChangeType = ChangeType.Deleted; yield return(change); // TODO: not sure if this condition suffices in some special cases. } else if (raw_modes.Select((m1, i) => new { Mode = m1, Index = i + 1 }).All(x => !walk.IdEqual(0, x.Index))) { change.ChangeType = ChangeType.Modified; change.ReferenceObject = walk.GetObjectId(0); yield return(change); } else if (raw_modes.Select((m1, i) => new { Mode = m1, Index = i + 1 }).Any(x => m0 != x.Mode && walk.IdEqual(0, x.Index))) { change.ChangeType = ChangeType.TypeChanged; change.ReferenceObject = walk.GetObjectId(0); yield return(change); } } } }
/// <summary> /// Stash the contents on the working directory and index in separate commits /// and reset to the current HEAD commit. /// </summary> /// <remarks> /// Stash the contents on the working directory and index in separate commits /// and reset to the current HEAD commit. /// </remarks> /// <returns>stashed commit or null if no changes to stash</returns> /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException /// </exception> public override RevCommit Call() { CheckCallable(); Ref head = GetHead(); ObjectReader reader = repo.NewObjectReader(); try { RevCommit headCommit = ParseCommit(reader, head.GetObjectId()); DirCache cache = repo.LockDirCache(); ObjectInserter inserter = repo.NewObjectInserter(); ObjectId commitId; try { TreeWalk treeWalk = new TreeWalk(reader); treeWalk.Recursive = true; treeWalk.AddTree(headCommit.Tree); treeWalk.AddTree(new DirCacheIterator(cache)); treeWalk.AddTree(new FileTreeIterator(repo)); treeWalk.Filter = AndTreeFilter.Create(new SkipWorkTreeFilter(1), new IndexDiffFilter (1, 2)); // Return null if no local changes to stash if (!treeWalk.Next()) { return(null); } MutableObjectId id = new MutableObjectId(); IList <DirCacheEditor.PathEdit> wtEdits = new AList <DirCacheEditor.PathEdit>(); IList <string> wtDeletes = new AList <string>(); do { AbstractTreeIterator headIter = treeWalk.GetTree <AbstractTreeIterator>(0); DirCacheIterator indexIter = treeWalk.GetTree <DirCacheIterator>(1); WorkingTreeIterator wtIter = treeWalk.GetTree <WorkingTreeIterator>(2); if (headIter != null && indexIter != null && wtIter != null) { if (!indexIter.GetDirCacheEntry().IsMerged()) { throw new UnmergedPathsException(new UnmergedPathException(indexIter.GetDirCacheEntry ())); } if (wtIter.IdEqual(indexIter) || wtIter.IdEqual(headIter)) { continue; } treeWalk.GetObjectId(id, 0); DirCacheEntry entry = new DirCacheEntry(treeWalk.RawPath); entry.SetLength(wtIter.GetEntryLength()); entry.LastModified = wtIter.GetEntryLastModified(); entry.FileMode = wtIter.EntryFileMode; long contentLength = wtIter.GetEntryContentLength(); InputStream @in = wtIter.OpenEntryStream(); try { entry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, contentLength, @in)); } finally { @in.Close(); } wtEdits.AddItem(new _PathEdit_273(entry, entry)); } else { if (indexIter == null) { wtDeletes.AddItem(treeWalk.PathString); } else { if (wtIter == null && headIter != null) { wtDeletes.AddItem(treeWalk.PathString); } } } }while (treeWalk.Next()); string branch = Repository.ShortenRefName(head.GetTarget().GetName()); // Commit index changes NGit.CommitBuilder builder = CreateBuilder(headCommit); builder.TreeId = cache.WriteTree(inserter); builder.Message = MessageFormat.Format(indexMessage, branch, headCommit.Abbreviate (7).Name, headCommit.GetShortMessage()); ObjectId indexCommit = inserter.Insert(builder); // Commit working tree changes if (!wtEdits.IsEmpty() || !wtDeletes.IsEmpty()) { DirCacheEditor editor = cache.Editor(); foreach (DirCacheEditor.PathEdit edit in wtEdits) { editor.Add(edit); } foreach (string path in wtDeletes) { editor.Add(new DirCacheEditor.DeletePath(path)); } editor.Finish(); } builder.AddParentId(indexCommit); builder.Message = MessageFormat.Format(workingDirectoryMessage, branch, headCommit .Abbreviate(7).Name, headCommit.GetShortMessage()); builder.TreeId = cache.WriteTree(inserter); commitId = inserter.Insert(builder); inserter.Flush(); UpdateStashRef(commitId, builder.Author, builder.Message); } finally { inserter.Release(); cache.Unlock(); } // Hard reset to HEAD new ResetCommand(repo).SetMode(ResetCommand.ResetType.HARD).Call(); // Return stashed commit return(ParseCommit(reader, commitId)); } catch (IOException e) { throw new JGitInternalException(JGitText.Get().stashFailed, e); } finally { reader.Release(); } }
public static GitData_File add_File(this List<GitData_File> gitData_Files, TreeWalk treeWalk) { var gitData_File = new GitData_File { FilePath = treeWalk.PathString, Sha1 = treeWalk.GetObjectId(0).sha1() }; gitData_Files.add(gitData_File); return gitData_File; }
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 ""; }
/// <summary> /// Convert the TreeWalk into DiffEntry headers, depending on /// <code>includeTrees</code> /// it will add tree objects into result or not. /// </summary> /// <param name="walk"> /// the TreeWalk to walk through. Must have exactly two trees and /// when /// <code>includeTrees</code> /// parameter is /// <code>true</code> /// it can't /// be recursive. /// </param> /// <param name="includeTrees">include tree object's.</param> /// <returns>headers describing the changed files.</returns> /// <exception cref="System.IO.IOException">the repository cannot be accessed.</exception> /// <exception cref="System.ArgumentException"> /// when /// <code>includeTrees</code> /// is true and given TreeWalk is /// recursive. Or when given TreeWalk doesn't have exactly two /// trees /// </exception> public static IList<NGit.Diff.DiffEntry> Scan(TreeWalk walk, bool includeTrees) { if (walk.TreeCount != 2) { throw new ArgumentException(JGitText.Get().treeWalkMustHaveExactlyTwoTrees); } if (includeTrees && walk.Recursive) { throw new ArgumentException(JGitText.Get().cannotBeRecursiveWhenTreesAreIncluded); } IList<NGit.Diff.DiffEntry> r = new AList<NGit.Diff.DiffEntry>(); MutableObjectId idBuf = new MutableObjectId(); while (walk.Next()) { NGit.Diff.DiffEntry entry = new NGit.Diff.DiffEntry(); walk.GetObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.FromObjectId(idBuf); walk.GetObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.FromObjectId(idBuf); entry.oldMode = walk.GetFileMode(0); entry.newMode = walk.GetFileMode(1); entry.newPath = entry.oldPath = walk.PathString; if (entry.oldMode == FileMode.MISSING) { entry.oldPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.ADD; r.AddItem(entry); } else { if (entry.newMode == FileMode.MISSING) { entry.newPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.DELETE; r.AddItem(entry); } else { if (!entry.oldId.Equals(entry.newId)) { entry.changeType = DiffEntry.ChangeType.MODIFY; if (RenameDetector.SameType(entry.oldMode, entry.newMode)) { r.AddItem(entry); } else { Sharpen.Collections.AddAll(r, BreakModify(entry)); } } else { if (entry.oldMode != entry.newMode) { entry.changeType = DiffEntry.ChangeType.MODIFY; r.AddItem(entry); } } } } if (includeTrees && walk.IsSubtree) { walk.EnterSubtree(); } } return r; }
private void AssertCorrectId(DirCache treeT, TreeWalk tw) { NUnit.Framework.Assert.AreEqual(treeT.GetEntry(tw.PathString).GetObjectId(), tw.GetObjectId (0)); }
/// <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; }
/// <summary> /// Convert the TreeWalk into DiffEntry headers, depending on /// <code>includeTrees</code> /// it will add tree objects into result or not. /// </summary> /// <param name="walk"> /// the TreeWalk to walk through. Must have exactly two trees and /// when /// <code>includeTrees</code> /// parameter is /// <code>true</code> /// it can't /// be recursive. /// </param> /// <param name="includeTrees">include tree object's.</param> /// <returns>headers describing the changed files.</returns> /// <exception cref="System.IO.IOException">the repository cannot be accessed.</exception> /// <exception cref="System.ArgumentException"> /// when /// <code>includeTrees</code> /// is true and given TreeWalk is /// recursive. Or when given TreeWalk doesn't have exactly two /// trees /// </exception> public static IList <NGit.Diff.DiffEntry> Scan(TreeWalk walk, bool includeTrees) { if (walk.TreeCount != 2) { throw new ArgumentException(JGitText.Get().treeWalkMustHaveExactlyTwoTrees); } if (includeTrees && walk.Recursive) { throw new ArgumentException(JGitText.Get().cannotBeRecursiveWhenTreesAreIncluded); } IList <NGit.Diff.DiffEntry> r = new AList <NGit.Diff.DiffEntry>(); MutableObjectId idBuf = new MutableObjectId(); while (walk.Next()) { NGit.Diff.DiffEntry entry = new NGit.Diff.DiffEntry(); walk.GetObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.FromObjectId(idBuf); walk.GetObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.FromObjectId(idBuf); entry.oldMode = walk.GetFileMode(0); entry.newMode = walk.GetFileMode(1); entry.newPath = entry.oldPath = walk.PathString; if (entry.oldMode == FileMode.MISSING) { entry.oldPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.ADD; r.AddItem(entry); } else { if (entry.newMode == FileMode.MISSING) { entry.newPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.DELETE; r.AddItem(entry); } else { if (!entry.oldId.Equals(entry.newId)) { entry.changeType = DiffEntry.ChangeType.MODIFY; if (RenameDetector.SameType(entry.oldMode, entry.newMode)) { r.AddItem(entry); } else { Sharpen.Collections.AddAll(r, BreakModify(entry)); } } else { if (entry.oldMode != entry.newMode) { entry.changeType = DiffEntry.ChangeType.MODIFY; r.AddItem(entry); } } } } if (includeTrees && walk.IsSubtree) { walk.EnterSubtree(); } } return(r); }
} // End Function GetDiff // https://stackoverflow.com/questions/13537734/how-to-use-jgit-to-get-list-of-changed-files // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowChangedFilesBetweenCommits.java public static void GetChanges(Git git, Repository repo, RevCommit oldCommit, RevCommit newCommit) { System.Console.WriteLine("Printing diff between commit: " + oldCommit.ToString() + " and " + newCommit.ToString()); ObjectReader reader = repo.NewObjectReader(); // prepare the two iterators to compute the diff between CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.Reset(reader, oldCommit.Tree.Id); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.Reset(reader, newCommit.Tree.Id); // DiffStatFormatter df = new DiffStatFormatter(newCommit.Name, repo); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { DiffFormatter diffFormatter = new DiffFormatter(ms); diffFormatter.SetRepository(repo); int entryCount = 0; foreach (DiffEntry entry in diffFormatter.Scan(oldCommit, newCommit)) { string pathToUse = null; TreeWalk treeWalk = new TreeWalk(repo); treeWalk.Recursive = true; if (entry.GetChangeType() == DiffEntry.ChangeType.DELETE) { treeWalk.AddTree(oldCommit.Tree); pathToUse = entry.GetOldPath(); } else { treeWalk.AddTree(newCommit.Tree); pathToUse = entry.GetNewPath(); } treeWalk.Filter = PathFilter.Create(pathToUse); if (!treeWalk.Next()) { throw new System.Exception("Did not find expected file '" + pathToUse + "'"); } ObjectId objectId = treeWalk.GetObjectId(0); ObjectLoader loader = repo.Open(objectId); string strModifiedFile = ReadFile(loader); System.Console.WriteLine(strModifiedFile); ////////////// // https://stackoverflow.com/questions/27361538/how-to-show-changes-between-commits-with-jgit diffFormatter.Format(diffFormatter.ToFileHeader(entry)); string diff = GetDiff(repo, entry); System.Console.WriteLine(diff); entryCount++; } // Next entry System.Console.WriteLine(entryCount); ms.Position = 0; using (System.IO.StreamReader sr = new System.IO.StreamReader(ms)) { string strAllDiffs = sr.ReadToEnd(); System.Console.WriteLine(strAllDiffs); } // End Using sr } // End Using ms System.Collections.Generic.IList<DiffEntry> diffs = git.Diff() .SetNewTree(newTreeIter) .SetOldTree(oldTreeIter) .Call(); foreach (DiffEntry entry in diffs) { System.Console.WriteLine("Entry: " + entry); System.Console.WriteLine("Entry: " + entry.GetChangeType()); } // Next entry System.Console.WriteLine("Done"); } // End Sub GetChanges
public virtual void TestMissingSubtree_DetectFileAdded_FileModified() { ObjectInserter inserter = db.NewObjectInserter(); ObjectId aFileId = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("a")); ObjectId bFileId = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("b")); ObjectId cFileId1 = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("c-1")); ObjectId cFileId2 = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("c-2")); // Create sub-a/empty, sub-c/empty = hello. ObjectId oldTree; { Tree root = new Tree(db); { Tree subA = root.AddTree("sub-a"); subA.AddFile("empty").SetId(aFileId); subA.SetId(inserter.Insert(Constants.OBJ_TREE, subA.Format())); } { Tree subC = root.AddTree("sub-c"); subC.AddFile("empty").SetId(cFileId1); subC.SetId(inserter.Insert(Constants.OBJ_TREE, subC.Format())); } oldTree = inserter.Insert(Constants.OBJ_TREE, root.Format()); } // Create sub-a/empty, sub-b/empty, sub-c/empty. ObjectId newTree; { Tree root = new Tree(db); { Tree subA = root.AddTree("sub-a"); subA.AddFile("empty").SetId(aFileId); subA.SetId(inserter.Insert(Constants.OBJ_TREE, subA.Format())); } { Tree subB = root.AddTree("sub-b"); subB.AddFile("empty").SetId(bFileId); subB.SetId(inserter.Insert(Constants.OBJ_TREE, subB.Format())); } { Tree subC = root.AddTree("sub-c"); subC.AddFile("empty").SetId(cFileId2); subC.SetId(inserter.Insert(Constants.OBJ_TREE, subC.Format())); } newTree = inserter.Insert(Constants.OBJ_TREE, root.Format()); } inserter.Flush(); inserter.Release(); TreeWalk tw = new TreeWalk(db); tw.Reset(oldTree, newTree); tw.Recursive = true; tw.Filter = TreeFilter.ANY_DIFF; NUnit.Framework.Assert.IsTrue(tw.Next()); NUnit.Framework.Assert.AreEqual("sub-b/empty", tw.PathString); NUnit.Framework.Assert.AreEqual(FileMode.MISSING, tw.GetFileMode(0)); NUnit.Framework.Assert.AreEqual(FileMode.REGULAR_FILE, tw.GetFileMode(1)); NUnit.Framework.Assert.AreEqual(ObjectId.ZeroId, tw.GetObjectId(0)); NUnit.Framework.Assert.AreEqual(bFileId, tw.GetObjectId(1)); NUnit.Framework.Assert.IsTrue(tw.Next()); NUnit.Framework.Assert.AreEqual("sub-c/empty", tw.PathString); NUnit.Framework.Assert.AreEqual(FileMode.REGULAR_FILE, tw.GetFileMode(0)); NUnit.Framework.Assert.AreEqual(FileMode.REGULAR_FILE, tw.GetFileMode(1)); NUnit.Framework.Assert.AreEqual(cFileId1, tw.GetObjectId(0)); NUnit.Framework.Assert.AreEqual(cFileId2, tw.GetObjectId(1)); NUnit.Framework.Assert.IsFalse(tw.Next()); }
// reduce the visibility of the default constructor /// <summary>Convert the TreeWalk into DiffEntry headers.</summary> /// <remarks>Convert the TreeWalk into DiffEntry headers.</remarks> /// <param name="walk">the TreeWalk to walk through. Must have exactly two trees.</param> /// <returns>headers describing the changed files.</returns> /// <exception cref="System.IO.IOException">the repository cannot be accessed.</exception> public static IList<NGit.Diff.DiffEntry> Scan(TreeWalk walk) { IList<NGit.Diff.DiffEntry> r = new AList<NGit.Diff.DiffEntry>(); MutableObjectId idBuf = new MutableObjectId(); while (walk.Next()) { NGit.Diff.DiffEntry entry = new NGit.Diff.DiffEntry(); walk.GetObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.FromObjectId(idBuf); walk.GetObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.FromObjectId(idBuf); entry.oldMode = walk.GetFileMode(0); entry.newMode = walk.GetFileMode(1); entry.newPath = entry.oldPath = walk.PathString; if (entry.oldMode == FileMode.MISSING) { entry.oldPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.ADD; r.AddItem(entry); } else { if (entry.newMode == FileMode.MISSING) { entry.newPath = NGit.Diff.DiffEntry.DEV_NULL; entry.changeType = DiffEntry.ChangeType.DELETE; r.AddItem(entry); } else { entry.changeType = DiffEntry.ChangeType.MODIFY; if (RenameDetector.SameType(entry.oldMode, entry.newMode)) { r.AddItem(entry); } else { Sharpen.Collections.AddAll(r, BreakModify(entry)); } } } } return r; }
public virtual void TestAddUnstagedChanges() { FilePath file = new FilePath(db.WorkTree, "a.txt"); FileUtils.CreateNewFile(file); PrintWriter writer = new PrintWriter(file); writer.Write("content"); writer.Close(); Git git = new Git(db); git.Add().AddFilepattern("a.txt").Call(); RevCommit commit = git.Commit().SetMessage("initial commit").Call(); TreeWalk tw = TreeWalk.ForPath(db, "a.txt", commit.Tree); NUnit.Framework.Assert.AreEqual("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.GetObjectId (0).GetName()); writer = new PrintWriter(file); writer.Write("content2"); writer.Close(); commit = git.Commit().SetMessage("second commit").Call(); tw = TreeWalk.ForPath(db, "a.txt", commit.Tree); NUnit.Framework.Assert.AreEqual("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.GetObjectId (0).GetName()); commit = git.Commit().SetAll(true).SetMessage("third commit").SetAll(true).Call(); tw = TreeWalk.ForPath(db, "a.txt", commit.Tree); NUnit.Framework.Assert.AreEqual("db00fd65b218578127ea51f3dffac701f12f486a", tw.GetObjectId (0).GetName()); }
public 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(""); }
/// <summary> /// Return a list of those objects in the index which differ from whats in /// HEAD /// </summary> /// <returns>a set of ObjectIds of changed objects in the index</returns> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> /// <exception cref="NGit.Errors.CorruptObjectException">NGit.Errors.CorruptObjectException /// </exception> /// <exception cref="NGit.Errors.NoWorkTreeException">NGit.Errors.NoWorkTreeException /// </exception> private ICollection <ObjectId> ListNonHEADIndexObjects() { RevWalk revWalk = null; try { if (repo.GetIndexFile() == null) { return(Sharpen.Collections.EmptySet <ObjectId>()); } } catch (NoWorkTreeException) { return(Sharpen.Collections.EmptySet <ObjectId>()); } TreeWalk treeWalk = new TreeWalk(repo); try { treeWalk.AddTree(new DirCacheIterator(repo.ReadDirCache())); ObjectId headID = repo.Resolve(Constants.HEAD); if (headID != null) { revWalk = new RevWalk(repo); treeWalk.AddTree(revWalk.ParseTree(headID)); revWalk.Dispose(); revWalk = null; } treeWalk.Filter = TreeFilter.ANY_DIFF; treeWalk.Recursive = true; ICollection <ObjectId> ret = new HashSet <ObjectId>(); while (treeWalk.Next()) { ObjectId objectId = treeWalk.GetObjectId(0); switch (treeWalk.GetRawMode(0) & FileMode.TYPE_MASK) { case FileMode.TYPE_MISSING: case FileMode.TYPE_GITLINK: { continue; goto case FileMode.TYPE_TREE; } case FileMode.TYPE_TREE: case FileMode.TYPE_FILE: case FileMode.TYPE_SYMLINK: { ret.AddItem(objectId); continue; goto default; } default: { throw new IOException(MessageFormat.Format(JGitText.Get().corruptObjectInvalidMode3 , string.Format("%o", Sharpen.Extensions.ValueOf(treeWalk.GetRawMode(0)), (objectId == null) ? "null" : objectId.Name, treeWalk.PathString, repo.GetIndexFile()))); } } } return(ret); } finally { if (revWalk != null) { revWalk.Dispose(); } treeWalk.Release(); } }
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.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="NGit.Errors.CorruptObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> private void AssertEntry(string sha1string, string path, TreeWalk tw) { NUnit.Framework.Assert.IsTrue(tw.Next()); NUnit.Framework.Assert.AreEqual(path, tw.PathString); NUnit.Framework.Assert.AreEqual(sha1string, tw.GetObjectId(1).GetName()); }