Esempio n. 1
0
        public void testCull()
        {
            RevBlob f1 = blob("1");
            RevBlob f2 = blob("2");
            RevBlob f3 = blob("3");
            RevBlob f4 = blob("4");

            RevTree   ta = tree(File("a/1", f1), File("c/3", f3));
            RevCommit a  = Commit(ta);

            RevTree   tb = tree(File("a/1", f2), File("c/3", f3));
            RevCommit b1 = Commit(tb, a);
            RevCommit b2 = Commit(tb, b1);

            RevTree   tc = tree(File("a/1", f4));
            RevCommit c1 = Commit(tc, a);
            RevCommit c2 = Commit(tc, c1);

            MarkStart(b2);
            MarkUninteresting(c2);

            AssertCommit(b2, objw.next());
            AssertCommit(b1, objw.next());
            Assert.IsNull(objw.next());

            Assert.IsTrue(a.has(RevFlag.UNINTERESTING));
            Assert.IsTrue(ta.has(RevFlag.UNINTERESTING));
            Assert.IsTrue(f1.has(RevFlag.UNINTERESTING));
            Assert.IsTrue(f3.has(RevFlag.UNINTERESTING));

            Assert.AreSame(tb, objw.nextObject());
            Assert.AreSame(get(tb, "a"), objw.nextObject());
            Assert.AreSame(f2, objw.nextObject());
            Assert.IsNull(objw.nextObject());
        }
Esempio n. 2
0
        public void testTwoCommitTwoTreeTwoBlob()
        {
            RevBlob   f0 = blob("0");
            RevBlob   f1 = blob("1");
            RevBlob   f2 = blob("0v2");
            RevTree   ta = tree(File("0", f0), File("1", f1), File("2", f1));
            RevTree   tb = tree(File("0", f2), File("1", f1), File("2", f1));
            RevCommit a  = Commit(ta);
            RevCommit b  = Commit(tb, a);

            MarkStart(b);

            AssertCommit(b, objw.next());
            AssertCommit(a, objw.next());
            Assert.IsNull(objw.next());

            Assert.AreSame(tb, objw.nextObject());
            Assert.AreSame(f2, objw.nextObject());
            Assert.AreSame(f1, objw.nextObject());

            Assert.AreSame(ta, objw.nextObject());
            Assert.AreSame(f0, objw.nextObject());

            Assert.IsNull(objw.nextObject());
        }
Esempio n. 3
0
        public byte[] GetFileContent(string fileName)
        {
            if (!HasGitRepository || string.IsNullOrEmpty(fileName))
            {
                return(null);
            }

            fileName = GetRelativeFileNameForGit(fileName);

            try
            {
                var     head    = repository.Resolve(Constants.HEAD);
                RevTree revTree = head == null ? null : new RevWalk(repository).ParseTree(head);
                if (revTree != null)
                {
                    var entry = TreeWalk.ForPath(repository, fileName, revTree);
                    if (entry != null && !entry.IsSubtree)
                    {
                        var blob = repository.Open(entry.GetObjectId(0));
                        if (blob != null)
                        {
                            return(blob.GetCachedBytes());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine("Get File Content: {0}\r\n{1}", fileName, ex.ToString());
            }

            return(null);
        }
Esempio n. 4
0
        public byte[] GetFileContent(string commitId, string fileName)
        {
            if (repository == null)
            {
                return(null);
            }
            RevWalk walk = null;

            try
            {
                var     head    = repository.Resolve(commitId);
                RevTree revTree = head == null ? null : new RevWalk(repository).ParseTree(head);

                var entry = TreeWalk.ForPath(repository, fileName, revTree);
                if (entry != null && !entry.IsSubtree)
                {
                    var blob = repository.Open(entry.GetObjectId(0));
                    if (blob != null)
                    {
                        return(blob.GetCachedBytes());
                    }
                }
            }
            catch { }
            finally
            {
                if (walk != null)
                {
                    walk.Dispose();
                }
            }
            return(null);
        }
Esempio n. 5
0
        public void testTwoCommitDeepTree2()
        {
            RevBlob   f1 = blob("1");
            RevTree   ta = tree(File("a/b/0", f1), File("a/c/q", f1));
            RevTree   tb = tree(File("a/b/1", f1), File("a/c/q", f1));
            RevCommit a  = Commit(ta);
            RevCommit b  = Commit(tb, a);

            MarkStart(b);

            AssertCommit(b, objw.next());
            AssertCommit(a, objw.next());
            Assert.IsNull(objw.next());

            Assert.AreSame(tb, objw.nextObject());
            Assert.AreSame(get(tb, "a"), objw.nextObject());
            Assert.AreSame(get(tb, "a/b"), objw.nextObject());
            Assert.AreSame(f1, objw.nextObject());
            Assert.AreSame(get(tb, "a/c"), objw.nextObject());

            Assert.AreSame(ta, objw.nextObject());
            Assert.AreSame(get(ta, "a"), objw.nextObject());
            Assert.AreSame(get(ta, "a/b"), objw.nextObject());

            Assert.IsNull(objw.nextObject());
        }
Esempio n. 6
0
 public override void setUp()
 {
     base.setUp();
     _ow       = new ObjectWriter(db);
     rw        = createRevWalk();
     emptyTree = rw.parseTree(_ow.WriteTree(new Core.Tree(db)));
     nowTick   = 1236977987000L;
 }
Esempio n. 7
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();
            }
        }
Esempio n. 8
0
        public virtual void NonReferencedExpiredObjectTree_pruned()
        {
            RevBlob a = tr.Blob("a");
            RevTree t = tr.Tree(tr.File("a", a));

            gc.SetExpireAgeMillis(0);
            gc.Prune(Collections.EmptySet <ObjectId>());
            NUnit.Framework.Assert.IsFalse(repo.HasObject(t));
            NUnit.Framework.Assert.IsFalse(repo.HasObject(a));
        }
Esempio n. 9
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));
        }
Esempio n. 10
0
        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);
        }
Esempio n. 11
0
 /// <summary>Set the common ancestor tree.</summary>
 /// <remarks>Set the common ancestor tree.</remarks>
 /// <param name="id">
 /// common base treeish; null to automatically compute the common
 /// base from the input commits during
 /// <see cref="Merge(NGit.AnyObjectId, NGit.AnyObjectId)">Merge(NGit.AnyObjectId, NGit.AnyObjectId)
 ///     </see>
 /// .
 /// </param>
 /// <exception cref="NGit.Errors.IncorrectObjectTypeException">the object is not a treeish.
 ///     </exception>
 /// <exception cref="NGit.Errors.MissingObjectException">the object does not exist.</exception>
 /// <exception cref="System.IO.IOException">the object could not be read.</exception>
 public virtual void SetBase(AnyObjectId id)
 {
     if (id != null)
     {
         baseTree = walk.ParseTree(id);
     }
     else
     {
         baseTree = null;
     }
 }
Esempio n. 12
0
        /*
         * Create a new commit.
         * <p>
         * The author and committer identities are stored using the current
         * timestamp, after being incremented by {@code secDelta}. The message body
         * is empty.
         *
         * @param secDelta
         *            number of seconds to advance {@link #tick(int)} by.
         * @param tree
         *            the root tree for the commit.
         * @param parents
         *            zero or more parents of the commit.
         * @return the new commit.
         * @throws Exception
         */
        public RevCommit commit(int secDelta, RevTree tree,
                                params RevCommit[] parents)
        {
            tick(secDelta);

            global::GitSharp.Core.Commit c = new global::GitSharp.Core.Commit(db);
            c.TreeId    = (tree);
            c.ParentIds = (parents);
            c.Author    = (new PersonIdent(author, now.MillisToUtcDateTime()));
            c.Committer = (new PersonIdent(committer, now.MillisToUtcDateTime()));
            c.Message   = ("");
            return(pool.lookupCommit(writer.WriteCommit(c)));
        }
        public virtual void TestUsingUnknownTreeFails()
        {
            TestRepository <Repository> s = new TestRepository <Repository>(src);
            RevCommit N = s.Commit().Parent(B).Add("q", s.Blob("a")).Create();
            RevTree   t = s.ParseBody(N).Tree;

            // Don't include the tree in the pack.
            //
            TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024);
            PackHeader(pack, 1);
            Copy(pack, src.Open(N));
            Digest(pack);
            TemporaryBuffer.Heap inBuf     = new TemporaryBuffer.Heap(1024);
            PacketLineOut        inPckLine = new PacketLineOut(inBuf);

            inPckLine.WriteString(ObjectId.ZeroId.Name + ' ' + N.Name + ' ' + "refs/heads/s"
                                  + '\0' + BasePackPushConnection.CAPABILITY_REPORT_STATUS);
            inPckLine.End();
            pack.WriteTo(inBuf, PM);
            TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024);
            ReceivePack          rp     = new ReceivePack(dst);

            rp.SetCheckReceivedObjects(true);
            rp.SetCheckReferencedObjectsAreReachable(true);
            rp.SetAdvertiseRefsHook(new ReceivePackAdvertiseRefsHookTest.HidePrivateHook());
            try
            {
                Receive(rp, inBuf, outBuf);
                NUnit.Framework.Assert.Fail("Expected UnpackException");
            }
            catch (UnpackException failed)
            {
                Exception err = failed.InnerException;
                NUnit.Framework.Assert.IsTrue(err is MissingObjectException);
                MissingObjectException moe = (MissingObjectException)err;
                NUnit.Framework.Assert.AreEqual(t, moe.GetObjectId());
            }
            PacketLineIn r      = AsPacketLineIn(outBuf);
            string       master = r.ReadString();
            int          nul    = master.IndexOf('\0');

            NUnit.Framework.Assert.IsTrue(nul > 0, "has capability list");
            NUnit.Framework.Assert.AreEqual(B.Name + ' ' + R_MASTER, Sharpen.Runtime.Substring
                                                (master, 0, nul));
            NUnit.Framework.Assert.AreSame(PacketLineIn.END, r.ReadString());
            NUnit.Framework.Assert.AreEqual("unpack error Missing tree " + t.Name, r.ReadString
                                                ());
            NUnit.Framework.Assert.AreEqual("ng refs/heads/s n/a (unpacker error)", r.ReadString
                                                ());
            NUnit.Framework.Assert.AreSame(PacketLineIn.END, r.ReadString());
        }
Esempio n. 14
0
 /// <summary>Construct an Indexdiff</summary>
 /// <param name="repository"></param>
 /// <param name="objectId">tree id. If null, an EmptyTreeIterator is used.</param>
 /// <param name="workingTreeIterator">iterator for working directory</param>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public IndexDiff(Repository repository, ObjectId objectId, WorkingTreeIterator workingTreeIterator
                  )
 {
     this.repository = repository;
     if (objectId != null)
     {
         tree = new RevWalk(repository).ParseTree(objectId);
     }
     else
     {
         tree = null;
     }
     this.initialWorkingTreeIterator = workingTreeIterator;
 }
Esempio n. 15
0
        /// <exception cref="System.IO.IOException"></exception>
        private void MarkTreeComplete(RevTree tree)
        {
            if (tree.Has(COMPLETE))
            {
                return;
            }
            tree.Add(COMPLETE);
            treeWalk.Reset(tree);
            while (treeWalk.Next())
            {
                FileMode mode  = treeWalk.GetFileMode(0);
                int      sType = mode.GetObjectType();
                switch (sType)
                {
                case Constants.OBJ_BLOB:
                {
                    treeWalk.GetObjectId(idBuffer, 0);
                    revWalk.LookupAny(idBuffer, sType).Add(COMPLETE);
                    continue;
                    goto case Constants.OBJ_TREE;
                }

                case Constants.OBJ_TREE:
                {
                    treeWalk.GetObjectId(idBuffer, 0);
                    RevObject o = revWalk.LookupAny(idBuffer, sType);
                    if (!o.Has(COMPLETE))
                    {
                        o.Add(COMPLETE);
                        treeWalk.EnterSubtree();
                    }
                    continue;
                    goto default;
                }

                default:
                {
                    if (FileMode.GITLINK.Equals(mode))
                    {
                        continue;
                    }
                    treeWalk.GetObjectId(idBuffer, 0);
                    throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().corruptObjectInvalidMode3
                                                                          , mode, idBuffer.Name, treeWalk.PathString, tree.Name));
                }
                }
            }
        }
Esempio n. 16
0
        public void testOneCommitOneTreeTwoBlob()
        {
            RevBlob   f0 = blob("0");
            RevBlob   f1 = blob("1");
            RevTree   t  = tree(File("0", f0), File("1", f1), File("2", f1));
            RevCommit a  = Commit(t);

            MarkStart(a);

            AssertCommit(a, objw.next());
            Assert.IsNull(objw.next());

            Assert.AreSame(t, objw.nextObject());
            Assert.AreSame(f0, objw.nextObject());
            Assert.AreSame(f1, objw.nextObject());
            Assert.IsNull(objw.nextObject());
        }
Esempio n. 17
0
        public virtual void Branch_historyNotPruned()
        {
            RevCommit tip = CommitChain(10);

            tr.Branch("b").Update(tip);
            gc.SetExpireAgeMillis(0);
            gc.Prune(Collections.EmptySet <ObjectId>());
            do
            {
                NUnit.Framework.Assert.IsTrue(repo.HasObject(tip));
                tr.ParseBody(tip);
                RevTree t = tip.Tree;
                NUnit.Framework.Assert.IsTrue(repo.HasObject(t));
                NUnit.Framework.Assert.IsTrue(repo.HasObject(tr.Get(t, "a")));
                tip = tip.ParentCount > 0 ? tip.GetParent(0) : null;
            }while (tip != null);
        }
        public virtual void TestRemoveDeletesTreeFanout2_38()
        {
            RevBlob   a     = tr.Blob("a");
            RevBlob   data1 = tr.Blob("data1");
            RevTree   empty = tr.Tree();
            RevCommit r     = tr.Commit().Add(Fanout(2, a.Name), data1).Create();

            //
            //
            tr.ParseBody(r);
            NoteMap map = NoteMap.Read(reader, r);

            map.Set(a, null);
            RevCommit n = CommitNoteMap(map);

            NUnit.Framework.Assert.AreEqual(empty, n.Tree, "empty tree");
        }
        private void MarkTreeComplete(RevTree tree)
        {
            if (tree.has(COMPLETE))
            {
                return;
            }

            tree.add(COMPLETE);
            _treeWalk.reset(tree);
            while (_treeWalk.next())
            {
                FileMode mode  = _treeWalk.getFileMode(0);
                int      sType = (int)mode.ObjectType;

                switch (sType)
                {
                case Constants.OBJ_BLOB:
                    _treeWalk.getObjectId(_idBuffer, 0);
                    _revWalk.lookupAny(_idBuffer, sType).add(COMPLETE);
                    continue;

                case Constants.OBJ_TREE:
                {
                    _treeWalk.getObjectId(_idBuffer, 0);
                    RevObject o = _revWalk.lookupAny(_idBuffer, sType);
                    if (!o.has(COMPLETE))
                    {
                        o.add(COMPLETE);
                        _treeWalk.enterSubtree();
                    }
                    continue;
                }

                default:
                    if (FileMode.GitLink.Equals(sType))
                    {
                        continue;
                    }
                    _treeWalk.getObjectId(_idBuffer, 0);
                    throw new CorruptObjectException("Invalid mode " + mode.ObjectType + " for " + _idBuffer.Name + " " +
                                                     _treeWalk.getPathString() + " in " + tree.Name);
                }
            }
        }
Esempio n. 20
0
        /**
         * Lookup an entry stored in a tree, failing if not present.
         *
         * @param tree
         *            the tree to search.
         * @param path
         *            the path to find the entry of.
         * @return the parsed object entry at this path, never null.
         * @throws AssertionFailedError
         *             if the path does not exist in the given tree.
         * @throws Exception
         */
        public RevObject get(RevTree tree, String path)
        {
            TreeWalk tw = new TreeWalk(db);

            tw.setFilter(PathFilterGroup.createFromStrings(new[] { path }));
            tw.reset(tree);
            while (tw.next())
            {
                if (tw.isSubtree() && !path.Equals(tw.getPathString()))
                {
                    tw.enterSubtree();
                    continue;
                }
                ObjectId entid   = tw.getObjectId(0);
                FileMode entmode = tw.getFileMode(0);
                return(pool.lookupAny(entid, (int)entmode.ObjectType));
            }
            Assert.Fail("Can't find " + path + " in tree " + tree.Name);
            return(null); // never reached.
        }
Esempio n. 21
0
        private static string GetSnapshot(Repository repository, Git git, RevTree revTree, String file)
        {
            //Get snapshot , Retrive older version of an object
            TreeWalk treeWalk = TreeWalk.ForPath(git.GetRepository(), file, revTree);

            byte[] data = repository.Open(treeWalk.GetObjectId(0)).GetBytes();
            return(System.Text.Encoding.UTF8.GetString(data));


            //ObjectLoader loader = repository.Open(rev.ToObjectId());
            //InputStream ttt = loader.OpenStream();
            //string result = ttt.ToString();
            //Retrive older version of an object
            //RevTree revTree = rev.Tree;
            //TreeWalk treeWalk = new TreeWalk(git.GetRepository());
            //treeWalk.AddTree(revTree);
            //while (treeWalk.Next())
            //{
            //    //compare treeWalk.NameString yourself
            //    byte[] bytes = treeWalk.ObjectReader.Open(rev.ToObjectId()).GetCachedBytes();
            //    string result = System.Text.Encoding.UTF8.GetString(rev.RawBuffer);
            //}
        }
 /// <summary>Load a collection of notes from a tree.</summary>
 /// <remarks>Load a collection of notes from a tree.</remarks>
 /// <param name="reader">
 /// reader to scan the note branch with. This reader may be
 /// retained by the NoteMap for the life of the map in order to
 /// support lazy loading of entries.
 /// </param>
 /// <param name="tree">the note tree to read.</param>
 /// <returns>the note map read from the tree.</returns>
 /// <exception cref="System.IO.IOException">the repository cannot be accessed through the reader.
 ///     </exception>
 /// <exception cref="NGit.Errors.CorruptObjectException">a tree object is corrupt and cannot be read.
 ///     </exception>
 /// <exception cref="NGit.Errors.IncorrectObjectTypeException">a tree object wasn't actually a tree.
 ///     </exception>
 /// <exception cref="NGit.Errors.MissingObjectException">a reference tree object doesn't exist.
 ///     </exception>
 public static NGit.Notes.NoteMap Read(ObjectReader reader, RevTree tree)
 {
     return(ReadTree(reader, tree));
 }
Esempio n. 23
0
 /// <summary>
 /// Set the common ancestor tree.
 /// </summary>
 /// <param name="id">
 /// Common base treeish; null to automatically compute the common
 /// base from the input commits during
 /// <see cref="Merge(AnyObjectId, AnyObjectId)"/>.
 /// </param>
 /// <exception cref="IncorrectObjectTypeException">
 /// The object is not a <see cref="Treeish"/>.
 /// </exception>
 /// <exception cref="MissingObjectException">
 /// The object does not exist.
 /// </exception>
 /// <exception cref="IOException">
 /// The object could not be read.
 /// </exception>
 public void SetBase(AnyObjectId id)
 {
     _baseTree = id != null?Walk.parseTree(id) : null;
 }
Esempio n. 24
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);
        }
Esempio n. 25
0
 protected RevCommit Commit(RevTree tree, params RevCommit[] parents)
 {
     return(Commit(1, tree, parents));
 }
Esempio n. 26
0
 /// <summary>Open a tree walk and filter to exactly one path.</summary>
 /// <remarks>
 /// Open a tree walk and filter to exactly one path.
 /// <p>
 /// The returned tree walk is already positioned on the requested path, so
 /// the caller should not need to invoke
 /// <see cref="Next()">Next()</see>
 /// unless they are
 /// looking for a possible directory/file name conflict.
 /// </remarks>
 /// <param name="db">repository to read tree object data from.</param>
 /// <param name="path">single path to advance the tree walk instance into.</param>
 /// <param name="tree">the single tree to walk through.</param>
 /// <returns>
 /// a new tree walk configured for exactly this one path; null if no
 /// path was found in any of the trees.
 /// </returns>
 /// <exception cref="System.IO.IOException">reading a pack file or loose object failed.
 ///     </exception>
 /// <exception cref="NGit.Errors.CorruptObjectException">
 /// an tree object could not be read as its data stream did not
 /// appear to be a tree, or could not be inflated.
 /// </exception>
 /// <exception cref="NGit.Errors.IncorrectObjectTypeException">an object we expected to be a tree was not a tree.
 ///     </exception>
 /// <exception cref="NGit.Errors.MissingObjectException">a tree object was not found.
 ///     </exception>
 public static NGit.Treewalk.TreeWalk ForPath(Repository db, string path, RevTree
                                              tree)
 {
     return(ForPath(db, path, new ObjectId[] { tree }));
 }
Esempio n. 27
0
 /// <summary>
 /// Add a subtree, mode is
 /// <see cref="FileMode.TREE">FileMode.TREE</see>
 /// .
 /// </summary>
 /// <param name="name">name of the entry.</param>
 /// <param name="tree">the ObjectId to store in this entry.</param>
 public virtual void Append(string name, RevTree tree)
 {
     Append(name, FileMode.TREE, tree);
 }
Esempio n. 28
0
        /// <exception cref="NGit.Api.Errors.RefAlreadyExistsException">
        /// when trying to create (without force) a branch with a name
        /// that already exists
        /// </exception>
        /// <exception cref="NGit.Api.Errors.RefNotFoundException">if the start point or branch can not be found
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.InvalidRefNameException">
        /// if the provided name is <code>null</code> or otherwise
        /// invalid
        /// </exception>
        /// <returns>the newly created branch</returns>
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        public override Ref Call()
        {
            CheckCallable();
            ProcessOptions();
            try
            {
                if (createBranch)
                {
                    Git git = new Git(repo);
                    CreateBranchCommand command = git.BranchCreate();
                    command.SetName(name);
                    command.SetStartPoint(GetStartPoint().Name);
                    if (upstreamMode != null)
                    {
                        command.SetUpstreamMode(upstreamMode);
                    }
                    command.Call();
                }
                Ref      headRef       = repo.GetRef(Constants.HEAD);
                string   refLogMessage = "checkout: moving from " + headRef.GetTarget().GetName();
                ObjectId branch        = repo.Resolve(name);
                if (branch == null)
                {
                    throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved
                                                                        , name));
                }
                RevWalk          revWalk    = new RevWalk(repo);
                AnyObjectId      headId     = headRef.GetObjectId();
                RevCommit        headCommit = headId == null ? null : revWalk.ParseCommit(headId);
                RevCommit        newCommit  = revWalk.ParseCommit(branch);
                RevTree          headTree   = headCommit == null ? null : headCommit.Tree;
                DirCacheCheckout dco        = new DirCacheCheckout(repo, headTree, repo.LockDirCache(),
                                                                   newCommit.Tree);
                dco.SetFailOnConflict(true);
                try
                {
                    dco.Checkout();
                }
                catch (NGit.Errors.CheckoutConflictException e)
                {
                    status = new CheckoutResult(CheckoutResult.Status.CONFLICTS, dco.GetConflicts());
                    throw;
                }
                Ref @ref = repo.GetRef(name);
                if (@ref != null && [email protected]().StartsWith(Constants.R_HEADS))
                {
                    @ref = null;
                }
                RefUpdate refUpdate = repo.UpdateRef(Constants.HEAD, @ref == null);
                refUpdate.SetForceUpdate(force);
                refUpdate.SetRefLogMessage(refLogMessage + " to " + newCommit.GetName(), false);
                RefUpdate.Result updateResult;
                if (@ref != null)
                {
                    updateResult = refUpdate.Link(@ref.GetName());
                }
                else
                {
                    refUpdate.SetNewObjectId(newCommit);
                    updateResult = refUpdate.ForceUpdate();
                }
                SetCallable(false);
                bool ok = false;
                switch (updateResult)
                {
                case RefUpdate.Result.NEW:
                {
                    ok = true;
                    break;
                }

                case RefUpdate.Result.NO_CHANGE:
                case RefUpdate.Result.FAST_FORWARD:
                case RefUpdate.Result.FORCED:
                {
                    ok = true;
                    break;
                }

                default:
                {
                    break;
                    break;
                }
                }
                if (!ok)
                {
                    throw new JGitInternalException(MessageFormat.Format(JGitText.Get().checkoutUnexpectedResult
                                                                         , updateResult.ToString()));
                }
                if (!dco.GetToBeDeleted().IsEmpty())
                {
                    status = new CheckoutResult(CheckoutResult.Status.NONDELETED, dco.GetToBeDeleted(
                                                    ));
                }
                else
                {
                    status = CheckoutResult.OK_RESULT;
                }
                return(@ref);
            }
            catch (IOException ioe)
            {
                throw new JGitInternalException(ioe.Message, ioe);
            }
            finally
            {
                if (status == null)
                {
                    status = CheckoutResult.ERROR_RESULT;
                }
            }
        }
Esempio n. 29
0
 /*
  * Create a new commit.
  * <p>
  * See {@link #commit(int, RevTree, RevCommit...)}.
  *
  * @param tree
  *            the root tree for the commit.
  * @param parents
  *            zero or more parents of the commit.
  * @return the new commit.
  * @throws Exception
  */
 public RevCommit commit(RevTree tree, params RevCommit[] parents)
 {
     return(commit(1, tree, parents));
 }
Esempio n. 30
0
 /// <summary>Format the differences between two trees.</summary>
 /// <remarks>
 /// Format the differences between two trees.
 /// The patch is expressed as instructions to modify
 /// <code>a</code>
 /// to make it
 /// <code>b</code>
 /// .
 /// </remarks>
 /// <param name="a">the old (or previous) side.</param>
 /// <param name="b">the new (or updated) side.</param>
 /// <exception cref="System.IO.IOException">
 /// trees cannot be read, file contents cannot be read, or the
 /// patch cannot be output.
 /// </exception>
 public virtual void Format(RevTree a, RevTree b)
 {
     Format(Scan(a, b));
 }