/// <exception cref="System.Exception"></exception>
 private void AssertPaths(TreeWalk treeWalk, params string[] paths)
 {
     for (int i = 0; i < paths.Length; i++)
     {
         NUnit.Framework.Assert.IsTrue(treeWalk.Next());
         AssertPath(treeWalk.PathString, paths);
     }
     NUnit.Framework.Assert.IsFalse(treeWalk.Next());
 }
        public virtual void TestPick()
        {
            // B---O
            // \----P---T
            //
            // Cherry-pick "T" onto "O". This shouldn't introduce "p-fail", which
            // was created by "P", nor should it modify "a", which was done by "P".
            //
            DirCache treeB = db.ReadDirCache();
            DirCache treeO = db.ReadDirCache();
            DirCache treeP = db.ReadDirCache();
            DirCache treeT = db.ReadDirCache();
            {
                DirCacheBuilder b = treeB.Builder();
                DirCacheBuilder o = treeO.Builder();
                DirCacheBuilder p = treeP.Builder();
                DirCacheBuilder t = treeT.Builder();
                b.Add(MakeEntry("a", FileMode.REGULAR_FILE));
                o.Add(MakeEntry("a", FileMode.REGULAR_FILE));
                o.Add(MakeEntry("o", FileMode.REGULAR_FILE));
                p.Add(MakeEntry("a", FileMode.REGULAR_FILE, "q"));
                p.Add(MakeEntry("p-fail", FileMode.REGULAR_FILE));
                t.Add(MakeEntry("a", FileMode.REGULAR_FILE));
                t.Add(MakeEntry("t", FileMode.REGULAR_FILE));
                b.Finish();
                o.Finish();
                p.Finish();
                t.Finish();
            }
            ObjectInserter ow  = db.NewObjectInserter();
            ObjectId       B   = Commit(ow, treeB, new ObjectId[] {  });
            ObjectId       O   = Commit(ow, treeO, new ObjectId[] { B });
            ObjectId       P   = Commit(ow, treeP, new ObjectId[] { B });
            ObjectId       T   = Commit(ow, treeT, new ObjectId[] { P });
            ThreeWayMerger twm = ((ThreeWayMerger)MergeStrategy.SIMPLE_TWO_WAY_IN_CORE.NewMerger
                                      (db));

            twm.SetBase(P);
            bool merge = twm.Merge(new ObjectId[] { O, T });

            NUnit.Framework.Assert.IsTrue(merge);
            TreeWalk tw = new TreeWalk(db);

            tw.Recursive = true;
            tw.Reset(twm.GetResultTreeId());
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("a", tw.PathString);
            AssertCorrectId(treeO, tw);
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("o", tw.PathString);
            AssertCorrectId(treeO, tw);
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("t", tw.PathString);
            AssertCorrectId(treeT, tw);
            NUnit.Framework.Assert.IsFalse(tw.Next());
        }
        public virtual void TestRevert()
        {
            // B---P---T
            //
            // Revert P, this should result in a tree with a
            // from B and t from T as the change to a in P
            // and addition of t in P is reverted.
            //
            // We use the standard merge, but change the order
            // of the sources.
            //
            DirCache treeB = db.ReadDirCache();
            DirCache treeP = db.ReadDirCache();
            DirCache treeT = db.ReadDirCache();
            {
                DirCacheBuilder b = treeB.Builder();
                DirCacheBuilder p = treeP.Builder();
                DirCacheBuilder t = treeT.Builder();
                b.Add(MakeEntry("a", FileMode.REGULAR_FILE));
                p.Add(MakeEntry("a", FileMode.REGULAR_FILE, "q"));
                p.Add(MakeEntry("p-fail", FileMode.REGULAR_FILE));
                t.Add(MakeEntry("a", FileMode.REGULAR_FILE, "q"));
                t.Add(MakeEntry("p-fail", FileMode.REGULAR_FILE));
                t.Add(MakeEntry("t", FileMode.REGULAR_FILE));
                b.Finish();
                p.Finish();
                t.Finish();
            }
            ObjectInserter ow  = db.NewObjectInserter();
            ObjectId       B   = Commit(ow, treeB, new ObjectId[] {  });
            ObjectId       P   = Commit(ow, treeP, new ObjectId[] { B });
            ObjectId       T   = Commit(ow, treeT, new ObjectId[] { P });
            ThreeWayMerger twm = ((ThreeWayMerger)MergeStrategy.SIMPLE_TWO_WAY_IN_CORE.NewMerger
                                      (db));

            twm.SetBase(P);
            bool merge = twm.Merge(new ObjectId[] { B, T });

            NUnit.Framework.Assert.IsTrue(merge);
            TreeWalk tw = new TreeWalk(db);

            tw.Recursive = true;
            tw.Reset(twm.GetResultTreeId());
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("a", tw.PathString);
            AssertCorrectId(treeB, tw);
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("t", tw.PathString);
            AssertCorrectId(treeT, tw);
            NUnit.Framework.Assert.IsFalse(tw.Next());
        }
        public virtual void TestRecursiveTreeWalk()
        {
            RevCommit commit = WriteFileInFolderAndCommit();

            DeleteAll();
            WriteFileWithFolderName();
            TreeWalk treeWalk = CreateTreeWalk(commit);

            NUnit.Framework.Assert.IsTrue(treeWalk.Next());
            NUnit.Framework.Assert.AreEqual("folder", treeWalk.PathString);
            NUnit.Framework.Assert.IsTrue(treeWalk.Next());
            NUnit.Framework.Assert.AreEqual("folder/file", treeWalk.PathString);
            NUnit.Framework.Assert.IsFalse(treeWalk.Next());
        }
        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 TestEmptyFolderCommitted()
        {
            RevCommit commit   = CreateEmptyFolderAndCommit();
            TreeWalk  treeWalk = CreateTreeWalk(commit);

            NUnit.Framework.Assert.IsFalse(treeWalk.Next());
        }
Example #7
0
        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 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 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());
                }
            }
        }
Example #10
0
        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());
                }
            }
        }
Example #11
0
        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 TestFileCommitted()
        {
            RevCommit commit   = WriteFileAndCommit();
            TreeWalk  treeWalk = CreateTreeWalk(commit);

            NUnit.Framework.Assert.IsFalse(treeWalk.Next());
        }
        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);
            }
        }
Example #14
0
		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());
		}
Example #15
0
        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));
            }
        }
Example #16
0
        /// <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));
                }
            }
        }
Example #17
0
        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();
            }
        }
Example #18
0
        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 TestFileInFolderCommittedChangedNotModified()
        {
            RevCommit commit = WriteFileInFolderAndCommit();

            WriteFileInFolder();
            TreeWalk treeWalk = CreateTreeWalk(commit);

            NUnit.Framework.Assert.IsFalse(treeWalk.Next());
        }
Example #20
0
        public virtual void TestTrivialTwoWay_validSubtreeSort()
        {
            DirCache treeB = db.ReadDirCache();
            DirCache treeO = db.ReadDirCache();
            DirCache treeT = db.ReadDirCache();
            {
                DirCacheBuilder b = treeB.Builder();
                DirCacheBuilder o = treeO.Builder();
                DirCacheBuilder t = treeT.Builder();
                b.Add(CreateEntry("libelf-po/a", FileMode.REGULAR_FILE));
                b.Add(CreateEntry("libelf/c", FileMode.REGULAR_FILE));
                o.Add(CreateEntry("Makefile", FileMode.REGULAR_FILE));
                o.Add(CreateEntry("libelf-po/a", FileMode.REGULAR_FILE));
                o.Add(CreateEntry("libelf/c", FileMode.REGULAR_FILE));
                t.Add(CreateEntry("libelf-po/a", FileMode.REGULAR_FILE));
                t.Add(CreateEntry("libelf/c", FileMode.REGULAR_FILE, "blah"));
                b.Finish();
                o.Finish();
                t.Finish();
            }
            ObjectInserter ow        = db.NewObjectInserter();
            ObjectId       b_1       = Commit(ow, treeB, new ObjectId[] {  });
            ObjectId       o_1       = Commit(ow, treeO, new ObjectId[] { b_1 });
            ObjectId       t_1       = Commit(ow, treeT, new ObjectId[] { b_1 });
            Merger         ourMerger = ((ThreeWayMerger)MergeStrategy.SIMPLE_TWO_WAY_IN_CORE.NewMerger
                                            (db));
            bool merge = ourMerger.Merge(new ObjectId[] { o_1, t_1 });

            NUnit.Framework.Assert.IsTrue(merge);
            TreeWalk tw = new TreeWalk(db);

            tw.Recursive = true;
            tw.Reset(ourMerger.GetResultTreeId());
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("Makefile", tw.PathString);
            AssertCorrectId(treeO, tw);
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("libelf-po/a", tw.PathString);
            AssertCorrectId(treeO, tw);
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("libelf/c", tw.PathString);
            AssertCorrectId(treeT, tw);
            NUnit.Framework.Assert.IsFalse(tw.Next());
        }
Example #21
0
        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());
        }
        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);
        }
        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 TestEmptyFolderCommittedDeletedCommittedIgnoredComparedWithInitialCommit
            ()
        {
            RevCommit commit = CreateEmptyFolderAndCommit();

            DeleteFolderAndCommit();
            RecreateEmptyFolderIgnored();
            TreeWalk treeWalk = CreateTreeWalk(commit);

            NUnit.Framework.Assert.IsFalse(treeWalk.Next());
        }
Example #25
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);
 }
Example #26
0
        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());
            }
        }
Example #27
0
 /// <summary>Advance to next submodule in the index tree.</summary>
 /// <remarks>
 /// Advance to next submodule in the index tree.
 /// The object id and path of the next entry can be obtained by calling
 /// <see cref="GetObjectId()">GetObjectId()</see>
 /// and
 /// <see cref="GetPath()">GetPath()</see>
 /// .
 /// </remarks>
 /// <returns>true if entry found, false otherwise</returns>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public virtual bool Next()
 {
     while (walk.Next())
     {
         if (FileMode.GITLINK != walk.GetFileMode(0))
         {
             continue;
         }
         path = walk.PathString;
         return(true);
     }
     path = null;
     return(false);
 }
Example #28
0
        public static RevCommit       commit_TreeWalk(this RevCommit revCommit, API_NGit nGit, Action <TreeWalk> onNext)
        {
            var treeWalk = new TreeWalk(nGit.Repository);
            var tree     = revCommit.Tree;

            treeWalk.AddTree(tree);
            treeWalk.Recursive = true;

            while (treeWalk.Next())
            {
                onNext(treeWalk);
            }
            return(revCommit);
        }
Example #29
0
        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();
                }
            }
        }
Example #30
0
        /// <exception cref="System.IO.IOException"></exception>
        private void AssertEntry(FileMode type, bool entryIgnored, string pathName)
        {
            NUnit.Framework.Assert.IsTrue(walk.Next(), "walk has entry");
            NUnit.Framework.Assert.AreEqual(pathName, walk.PathString);
            NUnit.Framework.Assert.AreEqual(type, walk.GetFileMode(0));
            WorkingTreeIterator itr = walk.GetTree <WorkingTreeIterator>(0);

            NUnit.Framework.Assert.IsNotNull(itr, "has tree");
            NUnit.Framework.Assert.AreEqual(entryIgnored, itr.IsEntryIgnored(), "is ignored");
            if (D.Equals(type))
            {
                walk.EnterSubtree();
            }
        }
Example #31
0
        /// <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();
            }
        }
Example #32
0
        /// <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);
        }
Example #33
0
		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();
                }
            }
        }
        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 ;
        }
Example #37
0
		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());
		}
Example #38
0
		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());
		}
Example #39
0
		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());
			}
		}
Example #40
0
		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);
		}
Example #41
0
		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);
		}
Example #42
0
		/// <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 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 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;
            }
        }
Example #45
0
		/// <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;
			}
		}
Example #46
0
		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));
		}
Example #47
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;
					}
				}
			}
		}
Example #48
0
 /// <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;
 }
Example #49
0
		/// <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;
							}
						}
					}
				}
			}
		}
Example #50
0
        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 "";
        }
Example #51
0
		// 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;
		}
Example #52
0
		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);
		}
Example #53
0
		protected override void OnRevert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
		{
			// Replace with NGit.Api.Git.Reset ()
			// FIXME: we lack info about what happened to files
			foreach (var group in GroupByRepository (localPaths)) {
				var repository = group.Key;
				var files = group.ToArray ();

			var c = GetHeadCommit (repository);
			RevTree tree = c != null ? c.Tree : null;
			
			List<FilePath> changedFiles = new List<FilePath> ();
			List<FilePath> removedFiles = new List<FilePath> ();
			
			monitor.BeginTask (GettextCatalog.GetString ("Reverting files"), 3);
			monitor.BeginStepTask (GettextCatalog.GetString ("Reverting files"), files.Length, 2);
			
			DirCache dc = repository.LockDirCache ();
			DirCacheBuilder builder = dc.Builder ();
			
			try {
				HashSet<string> entriesToRemove = new HashSet<string> ();
				HashSet<string> foldersToRemove = new HashSet<string> ();
				
				// Add the new entries
				foreach (FilePath fp in files) {
					string p = repository.ToGitPath (fp);
					
					// Register entries to be removed from the index
					if (Directory.Exists (fp))
						foldersToRemove.Add (p);
					else
						entriesToRemove.Add (p);
					
					TreeWalk tw = tree != null ? TreeWalk.ForPath (repository, p, tree) : null;
					if (tw == null) {
						// Removed from the index
					}
					else {
						// Add new entries
						
						TreeWalk r;
						if (tw.IsSubtree) {
							// It's a directory. Make sure we remove existing index entries of this directory
							foldersToRemove.Add (p);
							
							// We have to iterate through all folder files. We need a new iterator since the
							// existing rw is not recursive
							r = new TreeWalk(repository);
							r.Reset (tree);
							r.Filter = PathFilterGroup.CreateFromStrings(new string[]{p});
							r.Recursive = true;
							r.Next ();
						} else {
							r = tw;
						}
						
						do {
							// There can be more than one entry if reverting a whole directory
							string rpath = repository.FromGitPath (r.PathString);
							DirCacheEntry e = new DirCacheEntry (r.PathString);
							e.SetObjectId (r.GetObjectId (0));
							e.FileMode = r.GetFileMode (0);
							if (!Directory.Exists (Path.GetDirectoryName (rpath)))
								Directory.CreateDirectory (rpath);
							DirCacheCheckout.CheckoutEntry (repository, rpath, e);
							builder.Add (e);
							changedFiles.Add (rpath);
						} while (r.Next ());
					}
					monitor.Step (1);
				}
				
				// Add entries we want to keep
				int count = dc.GetEntryCount ();
				for (int n=0; n<count; n++) {
					DirCacheEntry e = dc.GetEntry (n);
					string path = e.PathString;
					if (!entriesToRemove.Contains (path) && !foldersToRemove.Any (f => IsSubpath (f,path)))
						builder.Add (e);
				}
				
				builder.Commit ();
			}
			catch {
				dc.Unlock ();
				throw;
			}
			
			monitor.EndTask ();
			monitor.BeginTask (null, files.Length);

			foreach (FilePath p in changedFiles) {
				FileService.NotifyFileChanged (p, true);
				monitor.Step (1);
			}
			foreach (FilePath p in removedFiles) {
				FileService.NotifyFileRemoved (p);
				monitor.Step (1);
			}
			monitor.EndTask ();
			}
		}
Example #54
0
        /// <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."
                );
        }
Example #55
0
		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);
		}
Example #56
0
		/// <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());
		}
        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;
        }
Example #58
0
		public virtual void TestRevert()
		{
			// B---P---T
			//
			// Revert P, this should result in a tree with a
			// from B and t from T as the change to a in P
			// and addition of t in P is reverted.
			//
			// We use the standard merge, but change the order
			// of the sources.
			//
			DirCache treeB = db.ReadDirCache();
			DirCache treeP = db.ReadDirCache();
			DirCache treeT = db.ReadDirCache();
			{
				DirCacheBuilder b = treeB.Builder();
				DirCacheBuilder p = treeP.Builder();
				DirCacheBuilder t = treeT.Builder();
				b.Add(CreateEntry("a", FileMode.REGULAR_FILE));
				p.Add(CreateEntry("a", FileMode.REGULAR_FILE, "q"));
				p.Add(CreateEntry("p-fail", FileMode.REGULAR_FILE));
				t.Add(CreateEntry("a", FileMode.REGULAR_FILE, "q"));
				t.Add(CreateEntry("p-fail", FileMode.REGULAR_FILE));
				t.Add(CreateEntry("t", FileMode.REGULAR_FILE));
				b.Finish();
				p.Finish();
				t.Finish();
			}
			ObjectInserter ow = db.NewObjectInserter();
			ObjectId B = Commit(ow, treeB, new ObjectId[] {  });
			ObjectId P = Commit(ow, treeP, new ObjectId[] { B });
			ObjectId T = Commit(ow, treeT, new ObjectId[] { P });
			ThreeWayMerger twm = ((ThreeWayMerger)MergeStrategy.SIMPLE_TWO_WAY_IN_CORE.NewMerger
				(db));
			twm.SetBase(P);
			bool merge = twm.Merge(new ObjectId[] { B, T });
			NUnit.Framework.Assert.IsTrue(merge);
			TreeWalk tw = new TreeWalk(db);
			tw.Recursive = true;
			tw.Reset(twm.GetResultTreeId());
			NUnit.Framework.Assert.IsTrue(tw.Next());
			NUnit.Framework.Assert.AreEqual("a", tw.PathString);
			AssertCorrectId(treeB, tw);
			NUnit.Framework.Assert.IsTrue(tw.Next());
			NUnit.Framework.Assert.AreEqual("t", tw.PathString);
			AssertCorrectId(treeT, tw);
			NUnit.Framework.Assert.IsFalse(tw.Next());
		}
Example #59
0
		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();
		}
Example #60
0
		public virtual void TestPick()
		{
			// B---O
			// \----P---T
			//
			// Cherry-pick "T" onto "O". This shouldn't introduce "p-fail", which
			// was created by "P", nor should it modify "a", which was done by "P".
			//
			DirCache treeB = db.ReadDirCache();
			DirCache treeO = db.ReadDirCache();
			DirCache treeP = db.ReadDirCache();
			DirCache treeT = db.ReadDirCache();
			{
				DirCacheBuilder b = treeB.Builder();
				DirCacheBuilder o = treeO.Builder();
				DirCacheBuilder p = treeP.Builder();
				DirCacheBuilder t = treeT.Builder();
				b.Add(CreateEntry("a", FileMode.REGULAR_FILE));
				o.Add(CreateEntry("a", FileMode.REGULAR_FILE));
				o.Add(CreateEntry("o", FileMode.REGULAR_FILE));
				p.Add(CreateEntry("a", FileMode.REGULAR_FILE, "q"));
				p.Add(CreateEntry("p-fail", FileMode.REGULAR_FILE));
				t.Add(CreateEntry("a", FileMode.REGULAR_FILE));
				t.Add(CreateEntry("t", FileMode.REGULAR_FILE));
				b.Finish();
				o.Finish();
				p.Finish();
				t.Finish();
			}
			ObjectInserter ow = db.NewObjectInserter();
			ObjectId B = Commit(ow, treeB, new ObjectId[] {  });
			ObjectId O = Commit(ow, treeO, new ObjectId[] { B });
			ObjectId P = Commit(ow, treeP, new ObjectId[] { B });
			ObjectId T = Commit(ow, treeT, new ObjectId[] { P });
			ThreeWayMerger twm = ((ThreeWayMerger)MergeStrategy.SIMPLE_TWO_WAY_IN_CORE.NewMerger
				(db));
			twm.SetBase(P);
			bool merge = twm.Merge(new ObjectId[] { O, T });
			NUnit.Framework.Assert.IsTrue(merge);
			TreeWalk tw = new TreeWalk(db);
			tw.Recursive = true;
			tw.Reset(twm.GetResultTreeId());
			NUnit.Framework.Assert.IsTrue(tw.Next());
			NUnit.Framework.Assert.AreEqual("a", tw.PathString);
			AssertCorrectId(treeO, tw);
			NUnit.Framework.Assert.IsTrue(tw.Next());
			NUnit.Framework.Assert.AreEqual("o", tw.PathString);
			AssertCorrectId(treeO, tw);
			NUnit.Framework.Assert.IsTrue(tw.Next());
			NUnit.Framework.Assert.AreEqual("t", tw.PathString);
			AssertCorrectId(treeT, tw);
			NUnit.Framework.Assert.IsFalse(tw.Next());
		}