コード例 #1
0
        public virtual void TestTreeIteratorWithGitmodules()
        {
            ObjectId subId      = ObjectId.FromString("abcd1234abcd1234abcd1234abcd1234abcd1234");
            string   path       = "sub";
            Config   gitmodules = new Config();

            gitmodules.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants
                                 .CONFIG_KEY_PATH, "sub");
            gitmodules.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants
                                 .CONFIG_KEY_URL, "git://example.com/sub");
            RevCommit commit = testDb.GetRevWalk().ParseCommit(testDb.Commit().NoParents().Add
                                                                   (Constants.DOT_GIT_MODULES, gitmodules.ToText()).Edit(new _PathEdit_397(subId, path
                                                                                                                                           )).Create());
            CanonicalTreeParser p = new CanonicalTreeParser();

            p.Reset(testDb.GetRevWalk().GetObjectReader(), commit.Tree);
            SubmoduleWalk gen = SubmoduleWalk.ForPath(db, p, "sub");

            NUnit.Framework.Assert.AreEqual(path, gen.GetPath());
            NUnit.Framework.Assert.AreEqual(subId, gen.GetObjectId());
            NUnit.Framework.Assert.AreEqual(new FilePath(db.WorkTree, path), gen.GetDirectory
                                                ());
            NUnit.Framework.Assert.IsNull(gen.GetConfigUpdate());
            NUnit.Framework.Assert.IsNull(gen.GetConfigUrl());
            NUnit.Framework.Assert.AreEqual("sub", gen.GetModulesPath());
            NUnit.Framework.Assert.IsNull(gen.GetModulesUpdate());
            NUnit.Framework.Assert.AreEqual("git://example.com/sub", gen.GetModulesUrl());
            NUnit.Framework.Assert.IsNull(gen.GetRepository());
            NUnit.Framework.Assert.IsFalse(gen.Next());
        }
コード例 #2
0
        /// <summary>
        /// Set the tree used by this walk for finding
        /// <code>.gitmodules</code>
        /// .
        /// <p>
        /// The root tree is not read until the first submodule is encountered by the
        /// walk.
        /// <p>
        /// This method need only be called if constructing a walk manually instead of
        /// with one of the static factory methods above.
        /// </summary>
        /// <param name="id">ID of a tree containing .gitmodules</param>
        /// <returns>this generator</returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public virtual NGit.Submodule.SubmoduleWalk SetRootTree(AnyObjectId id)
        {
            CanonicalTreeParser p = new CanonicalTreeParser();

            p.Reset(walk.ObjectReader, id);
            rootTree      = p;
            modulesConfig = null;
            return(this);
        }
コード例 #3
0
        /// <summary>Determine the differences between two trees.</summary>
        /// <remarks>
        /// Determine the differences between two trees.
        /// No output is created, instead only the file paths that are different are
        /// returned. Callers may choose to format these paths themselves, or convert
        /// them into
        /// <see cref="NGit.Patch.FileHeader">NGit.Patch.FileHeader</see>
        /// instances with a complete edit list by
        /// calling
        /// <see cref="ToFileHeader(DiffEntry)">ToFileHeader(DiffEntry)</see>
        /// .
        /// </remarks>
        /// <param name="a">the old (or previous) side.</param>
        /// <param name="b">the new (or updated) side.</param>
        /// <returns>the paths that are different.</returns>
        /// <exception cref="System.IO.IOException">trees cannot be read or file contents cannot be read.
        ///     </exception>
        public virtual IList <DiffEntry> Scan(RevTree a, RevTree b)
        {
            AssertHaveRepository();
            CanonicalTreeParser aParser = new CanonicalTreeParser();
            CanonicalTreeParser bParser = new CanonicalTreeParser();

            aParser.Reset(reader, a);
            bParser.Reset(reader, b);
            return(Scan(aParser, bParser));
        }
コード例 #4
0
        public static IEnumerable <DiffEntry> CompareCommits(NGit.Repository repo, AnyObjectId reference, ObjectId compared)
        {
            var diff = new MyersDiff(repo);

            if (reference != ObjectId.ZeroId)
            {
                var firstTree = new CanonicalTreeParser();
                firstTree.Reset(repo.NewObjectReader(), new RevWalk(repo).ParseTree(reference));
                diff.SetOldTree(firstTree);
            }

            var secondTree = new CanonicalTreeParser();

            secondTree.Reset(repo.NewObjectReader(), new RevWalk(repo).ParseTree(compared));
            diff.SetNewTree(secondTree);

            return(diff.Call());
        }
コード例 #5
0
        /// <exception cref="System.IO.IOException"></exception>
        private AbstractTreeIterator GetTreeIterator(string name)
        {
            ObjectId id = db.Resolve(name);

            if (id == null)
            {
                throw new ArgumentException(name);
            }
            CanonicalTreeParser p  = new CanonicalTreeParser();
            ObjectReader        or = db.NewObjectReader();

            try
            {
                p.Reset(or, new RevWalk(db).ParseTree(id));
                return(p);
            }
            finally
            {
                or.Release();
            }
        }
コード例 #6
0
        public override string ToString()
        {
            byte[] raw            = ToByteArray();
            CanonicalTreeParser p = new CanonicalTreeParser();

            p.Reset(raw);
            StringBuilder r = new StringBuilder();

            r.Append("Tree={");
            if (!p.Eof)
            {
                r.Append('\n');
                try
                {
                    new ObjectChecker().CheckTree(raw);
                }
                catch (CorruptObjectException error)
                {
                    r.Append("*** ERROR: ").Append(error.Message).Append("\n");
                    r.Append('\n');
                }
            }
            while (!p.Eof)
            {
                FileMode mode = p.EntryFileMode;
                r.Append(mode);
                r.Append(' ');
                r.Append(Constants.TypeString(mode.GetObjectType()));
                r.Append(' ');
                r.Append(p.EntryObjectId.Name);
                r.Append(' ');
                r.Append(p.EntryPathString);
                r.Append('\n');
                p.Next();
            }
            r.Append("}");
            return(r.ToString());
        }
コード例 #7
0
        /// <summary>
        /// Executes the
        /// <code>Diff</code>
        /// command with all the options and parameters
        /// collected by the setter methods (e.g.
        /// <see cref="SetCached(bool)">SetCached(bool)</see>
        /// of this
        /// class. Each instance of this class should only be used for one invocation
        /// of the command. Don't call this method twice on an instance.
        /// </summary>
        /// <returns>a DiffEntry for each path which is different</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        public override IList <DiffEntry> Call()
        {
            DiffFormatter diffFmt;

            if (@out != null && !showNameAndStatusOnly)
            {
                diffFmt = new DiffFormatter(new BufferedOutputStream(@out));
            }
            else
            {
                diffFmt = new DiffFormatter(NullOutputStream.INSTANCE);
            }
            diffFmt.SetRepository(repo);
            diffFmt.SetProgressMonitor(monitor);
            try
            {
                if (cached)
                {
                    if (oldTree == null)
                    {
                        ObjectId head = repo.Resolve(Constants.HEAD + "^{tree}");
                        if (head == null)
                        {
                            throw new NoHeadException(JGitText.Get().cannotReadTree);
                        }
                        CanonicalTreeParser p      = new CanonicalTreeParser();
                        ObjectReader        reader = repo.NewObjectReader();
                        try
                        {
                            p.Reset(reader, head);
                        }
                        finally
                        {
                            reader.Release();
                        }
                        oldTree = p;
                    }
                    newTree = new DirCacheIterator(repo.ReadDirCache());
                }
                else
                {
                    if (oldTree == null)
                    {
                        oldTree = new DirCacheIterator(repo.ReadDirCache());
                    }
                    if (newTree == null)
                    {
                        newTree = new FileTreeIterator(repo);
                    }
                }
                diffFmt.SetPathFilter(pathFilter);
                IList <DiffEntry> result = diffFmt.Scan(oldTree, newTree);
                if (showNameAndStatusOnly)
                {
                    return(result);
                }
                else
                {
                    if (contextLines >= 0)
                    {
                        diffFmt.SetContext(contextLines);
                    }
                    if (destinationPrefix != null)
                    {
                        diffFmt.SetNewPrefix(destinationPrefix);
                    }
                    if (sourcePrefix != null)
                    {
                        diffFmt.SetOldPrefix(sourcePrefix);
                    }
                    diffFmt.Format(result);
                    diffFmt.Flush();
                    return(result);
                }
            }
            catch (IOException e)
            {
                throw new JGitInternalException(e.Message, e);
            }
            finally
            {
                diffFmt.Release();
            }
        }
コード例 #8
0
        } // End Function GetDiff


        // https://stackoverflow.com/questions/13537734/how-to-use-jgit-to-get-list-of-changed-files
        // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowChangedFilesBetweenCommits.java
        public static void GetChanges(Git git, Repository repo, RevCommit oldCommit, RevCommit newCommit)
        {
            System.Console.WriteLine("Printing diff between commit: " + oldCommit.ToString() + " and " + newCommit.ToString());
            ObjectReader reader = repo.NewObjectReader();

            // prepare the two iterators to compute the diff between
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.Reset(reader, oldCommit.Tree.Id);
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.Reset(reader, newCommit.Tree.Id);

            // DiffStatFormatter df = new DiffStatFormatter(newCommit.Name, repo);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                DiffFormatter diffFormatter = new DiffFormatter(ms);
                diffFormatter.SetRepository(repo);

                int entryCount = 0;
                foreach (DiffEntry entry in diffFormatter.Scan(oldCommit, newCommit))
                {
                    string pathToUse = null;

                    TreeWalk treeWalk = new TreeWalk(repo);
                    treeWalk.Recursive = true;

                    if (entry.GetChangeType() == DiffEntry.ChangeType.DELETE)
                    {
                        treeWalk.AddTree(oldCommit.Tree);
                        pathToUse = entry.GetOldPath();
                    }
                    else
                    {
                        treeWalk.AddTree(newCommit.Tree);
                        pathToUse = entry.GetNewPath();   
                    }

                    treeWalk.Filter = PathFilter.Create(pathToUse); 
                        
                    if (!treeWalk.Next())
                    {
                        throw new System.Exception("Did not find expected file '" + pathToUse + "'");
                    }

                    ObjectId objectId = treeWalk.GetObjectId(0);
                    ObjectLoader loader = repo.Open(objectId);

                    string strModifiedFile = ReadFile(loader);
                    System.Console.WriteLine(strModifiedFile);

                    //////////////
                    // https://stackoverflow.com/questions/27361538/how-to-show-changes-between-commits-with-jgit
                    diffFormatter.Format(diffFormatter.ToFileHeader(entry));

                    string diff = GetDiff(repo, entry);
                    System.Console.WriteLine(diff);

                    entryCount++;
                } // Next entry 

                System.Console.WriteLine(entryCount);

                ms.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ms))
                {
                    string strAllDiffs = sr.ReadToEnd();
                    System.Console.WriteLine(strAllDiffs);
                } // End Using sr 
                
            } // End Using ms 


            System.Collections.Generic.IList<DiffEntry> diffs = git.Diff()
                             .SetNewTree(newTreeIter)
                             .SetOldTree(oldTreeIter)
                             .Call();

            foreach (DiffEntry entry in diffs)
            {
                System.Console.WriteLine("Entry: " + entry);
                System.Console.WriteLine("Entry: " + entry.GetChangeType());
            } // Next entry 

            System.Console.WriteLine("Done");
        } // End Sub GetChanges 
コード例 #9
0
        /// <summary>Apply the changes in a stashed commit to the working directory and index
        ///     </summary>
        /// <returns>id of stashed commit that was applied</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">NGit.Api.Errors.WrongRepositoryStateException
        ///     </exception>
        public override ObjectId Call()
        {
            CheckCallable();
            if (repo.GetRepositoryState() != RepositoryState.SAFE)
            {
                throw new WrongRepositoryStateException(MessageFormat.Format(JGitText.Get().stashApplyOnUnsafeRepository
                                                                             , repo.GetRepositoryState()));
            }
            ObjectId     headTree = GetHeadTree();
            ObjectId     stashId  = GetStashId();
            ObjectReader reader   = repo.NewObjectReader();

            try
            {
                RevWalk   revWalk     = new RevWalk(reader);
                RevCommit stashCommit = revWalk.ParseCommit(stashId);
                if (stashCommit.ParentCount != 2)
                {
                    throw new JGitInternalException(MessageFormat.Format(JGitText.Get().stashCommitMissingTwoParents
                                                                         , stashId.Name));
                }
                RevTree             stashWorkingTree = stashCommit.Tree;
                RevTree             stashIndexTree   = revWalk.ParseCommit(stashCommit.GetParent(1)).Tree;
                RevTree             stashHeadTree    = revWalk.ParseCommit(stashCommit.GetParent(0)).Tree;
                CanonicalTreeParser stashWorkingIter = new CanonicalTreeParser();
                stashWorkingIter.Reset(reader, stashWorkingTree);
                CanonicalTreeParser stashIndexIter = new CanonicalTreeParser();
                stashIndexIter.Reset(reader, stashIndexTree);
                CanonicalTreeParser stashHeadIter = new CanonicalTreeParser();
                stashHeadIter.Reset(reader, stashHeadTree);
                CanonicalTreeParser headIter = new CanonicalTreeParser();
                headIter.Reset(reader, headTree);
                DirCache       cache  = repo.LockDirCache();
                DirCacheEditor editor = cache.Editor();
                try
                {
                    DirCacheIterator indexIter   = new DirCacheIterator(cache);
                    FileTreeIterator workingIter = new FileTreeIterator(repo);
                    TreeWalk         treeWalk    = new TreeWalk(reader);
                    treeWalk.Recursive = true;
                    treeWalk.Filter    = new StashApplyCommand.StashDiffFilter();
                    treeWalk.AddTree(stashHeadIter);
                    treeWalk.AddTree(stashIndexIter);
                    treeWalk.AddTree(stashWorkingIter);
                    treeWalk.AddTree(headIter);
                    treeWalk.AddTree(indexIter);
                    treeWalk.AddTree(workingIter);
                    ScanForConflicts(treeWalk);
                    // Reset trees and walk
                    treeWalk.Reset();
                    stashWorkingIter.Reset(reader, stashWorkingTree);
                    stashIndexIter.Reset(reader, stashIndexTree);
                    stashHeadIter.Reset(reader, stashHeadTree);
                    treeWalk.AddTree(stashHeadIter);
                    treeWalk.AddTree(stashIndexIter);
                    treeWalk.AddTree(stashWorkingIter);
                    ApplyChanges(treeWalk, cache, editor);
                }
                finally
                {
                    editor.Commit();
                    cache.Unlock();
                }
            }
            catch (JGitInternalException e)
            {
                throw;
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().stashApplyFailed, e);
            }
            finally
            {
                reader.Release();
            }
            return(stashId);
        }