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);
        }
Exemple #2
0
 public static ObjectId CreateCommit(NGit.Repository rep, string message, IList <ObjectId> parents, ObjectId indexTreeId, PersonIdent author, PersonIdent committer)
 {
     try {
         ObjectInserter odi = rep.NewObjectInserter();
         try {
             // Create a Commit object, populate it and write it
             NGit.CommitBuilder commit = new NGit.CommitBuilder();
             commit.Committer = committer;
             commit.Author    = author;
             commit.Message   = message;
             commit.SetParentIds(parents);
             commit.TreeId = indexTreeId;
             ObjectId commitId = odi.Insert(commit);
             odi.Flush();
             return(commitId);
         } finally {
             odi.Release();
         }
     } catch (UnmergedPathException) {
         // since UnmergedPathException is a subclass of IOException
         // which should not be wrapped by a JGitInternalException we
         // have to catch and re-throw it here
         throw;
     } catch (IOException e) {
         throw new JGitInternalException("Commit failed", e);
     }
 }
Exemple #3
0
        /// <exception cref="System.IO.IOException"></exception>
        private RevObject WriteBlob(Repository repo, string data)
        {
            RevWalk revWalk = new RevWalk(repo);

            byte[]         bytes    = Constants.Encode(data);
            ObjectInserter inserter = repo.NewObjectInserter();
            ObjectId       id;

            try
            {
                id = inserter.Insert(Constants.OBJ_BLOB, bytes);
                inserter.Flush();
            }
            finally
            {
                inserter.Release();
            }
            try
            {
                Parse(id);
                NUnit.Framework.Assert.Fail("Object " + id.Name + " should not exist in test repository"
                                            );
            }
            catch (MissingObjectException)
            {
            }
            // Ok
            return(revWalk.LookupBlob(id));
        }
 /// <summary>Write (if necessary) this tree to the object store.</summary>
 /// <remarks>Write (if necessary) this tree to the object store.</remarks>
 /// <param name="cache">the complete cache from DirCache.</param>
 /// <param name="cIdx">
 /// first position of <code>cache</code> that is a member of this
 /// tree. The path of <code>cache[cacheIdx].path</code> for the
 /// range <code>[0,pathOff-1)</code> matches the complete path of
 /// this tree, from the root of the repository.
 /// </param>
 /// <param name="pathOffset">
 /// number of bytes of <code>cache[cacheIdx].path</code> that
 /// matches this tree's path. The value at array position
 /// <code>cache[cacheIdx].path[pathOff-1]</code> is always '/' if
 /// <code>pathOff</code> is &gt; 0.
 /// </param>
 /// <param name="ow">the writer to use when serializing to the store.</param>
 /// <returns>identity of this tree.</returns>
 /// <exception cref="NGit.Errors.UnmergedPathException">
 /// one or more paths contain higher-order stages (stage &gt; 0),
 /// which cannot be stored in a tree object.
 /// </exception>
 /// <exception cref="System.IO.IOException">an unexpected error occurred writing to the object store.
 ///     </exception>
 internal virtual ObjectId WriteTree(DirCacheEntry[] cache, int cIdx, int pathOffset
                                     , ObjectInserter ow)
 {
     if (id == null)
     {
         int           endIdx   = cIdx + entrySpan;
         TreeFormatter fmt      = new TreeFormatter(ComputeSize(cache, cIdx, pathOffset, ow));
         int           childIdx = 0;
         int           entryIdx = cIdx;
         while (entryIdx < endIdx)
         {
             DirCacheEntry e  = cache[entryIdx];
             byte[]        ep = e.path;
             if (childIdx < childCnt)
             {
                 NGit.Dircache.DirCacheTree st = children[childIdx];
                 if (st.Contains(ep, pathOffset, ep.Length))
                 {
                     fmt.Append(st.encodedName, FileMode.TREE, st.id);
                     entryIdx += st.entrySpan;
                     childIdx++;
                     continue;
                 }
             }
             fmt.Append(ep, pathOffset, ep.Length - pathOffset, e.FileMode, e.IdBuffer, e.IdOffset
                        );
             entryIdx++;
         }
         id = ow.Insert(fmt);
     }
     return(id);
 }
Exemple #5
0
        /// <exception cref="System.IO.IOException"></exception>
        private void CommitNoteMap(RevWalk walk, NoteMap map, RevCommit notesCommit, ObjectInserter
                                   inserter, string msg)
        {
            // commit the note
            NGit.CommitBuilder builder = new NGit.CommitBuilder();
            builder.TreeId    = map.WriteTree(inserter);
            builder.Author    = new PersonIdent(repo);
            builder.Committer = builder.Author;
            builder.Message   = msg;
            if (notesCommit != null)
            {
                builder.SetParentIds(notesCommit);
            }
            ObjectId commit = inserter.Insert(builder);

            inserter.Flush();
            RefUpdate refUpdate = repo.UpdateRef(notesRef);

            if (notesCommit != null)
            {
                refUpdate.SetExpectedOldObjectId(notesCommit);
            }
            else
            {
                refUpdate.SetExpectedOldObjectId(ObjectId.ZeroId);
            }
            refUpdate.SetNewObjectId(commit);
            refUpdate.Update(walk);
        }
 /// <exception cref="System.IO.IOException"></exception>
 private RevCommit CommitNoteMap(NoteMap map)
 {
     tr.Tick(600);
     NGit.CommitBuilder builder = new NGit.CommitBuilder();
     builder.TreeId = map.WriteTree(inserter);
     tr.SetAuthorAndCommitter(builder);
     return(tr.GetRevWalk().ParseCommit(inserter.Insert(builder)));
 }
Exemple #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();
            }
        }
Exemple #8
0
        public virtual void TestEmptyTreeCorruption()
        {
            ObjectId  bId = ObjectId.FromString("abbbfafe3129f85747aba7bfac992af77134c607");
            RevTree   tree_root;
            RevTree   tree_A;
            RevTree   tree_AB;
            RevCommit b;

            {
                Tree          root = new Tree(db);
                Tree          A    = root.AddTree("A");
                FileTreeEntry B    = root.AddFile("B");
                B.SetId(bId);
                Tree           A_A      = A.AddTree("A");
                Tree           A_B      = A.AddTree("B");
                ObjectInserter inserter = db.NewObjectInserter();
                try
                {
                    A_A.SetId(inserter.Insert(Constants.OBJ_TREE, A_A.Format()));
                    A_B.SetId(inserter.Insert(Constants.OBJ_TREE, A_B.Format()));
                    A.SetId(inserter.Insert(Constants.OBJ_TREE, A.Format()));
                    root.SetId(inserter.Insert(Constants.OBJ_TREE, root.Format()));
                    inserter.Flush();
                }
                finally
                {
                    inserter.Release();
                }
                tree_root = rw.ParseTree(root.GetId());
                tree_A    = rw.ParseTree(A.GetId());
                tree_AB   = rw.ParseTree(A_A.GetId());
                NUnit.Framework.Assert.AreSame(tree_AB, rw.ParseTree(A_B.GetId()));
                b = Commit(rw.ParseTree(root.GetId()));
            }
            MarkStart(b);
            AssertCommit(b, objw.Next());
            NUnit.Framework.Assert.IsNull(objw.Next());
            NUnit.Framework.Assert.AreSame(tree_root, objw.NextObject());
            NUnit.Framework.Assert.AreSame(tree_A, objw.NextObject());
            NUnit.Framework.Assert.AreSame(tree_AB, objw.NextObject());
            NUnit.Framework.Assert.AreSame(rw.LookupBlob(bId), objw.NextObject());
            NUnit.Framework.Assert.IsNull(objw.NextObject());
        }
Exemple #9
0
        /// <exception cref="System.Exception"></exception>
        private ObjectId Commit(ObjectInserter odi, DirCache treeB, ObjectId[] parentIds)
        {
            NGit.CommitBuilder c = new NGit.CommitBuilder();
            c.TreeId    = treeB.WriteTree(odi);
            c.Author    = new PersonIdent("A U Thor", "a.u.thor", 1L, 0);
            c.Committer = c.Author;
            c.SetParentIds(parentIds);
            c.Message = "Tree " + c.TreeId.Name;
            ObjectId id = odi.Insert(c);

            odi.Flush();
            return(id);
        }
Exemple #10
0
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="Sharpen.UnsupportedEncodingException"></exception>
        private ObjectId InsertTag(TagBuilder tag)
        {
            ObjectInserter oi = db.NewObjectInserter();

            try
            {
                ObjectId id = oi.Insert(tag);
                oi.Flush();
                return(id);
            }
            finally
            {
                oi.Release();
            }
        }
Exemple #11
0
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="Sharpen.UnsupportedEncodingException"></exception>
        private ObjectId InsertCommit(NGit.CommitBuilder builder)
        {
            ObjectInserter oi = db.NewObjectInserter();

            try
            {
                ObjectId id = oi.Insert(builder);
                oi.Flush();
                return(id);
            }
            finally
            {
                oi.Release();
            }
        }
Exemple #12
0
        /// <exception cref="System.IO.IOException"></exception>
        private ObjectId InsertTree(TreeFormatter tree)
        {
            ObjectInserter oi = db.NewObjectInserter();

            try
            {
                ObjectId id = oi.Insert(tree);
                oi.Flush();
                return(id);
            }
            finally
            {
                oi.Release();
            }
        }
Exemple #13
0
        /// <exception cref="System.IO.IOException"></exception>
        private ObjectId InsertTree(Tree tree)
        {
            ObjectInserter oi = db.NewObjectInserter();

            try
            {
                ObjectId id = oi.Insert(Constants.OBJ_TREE, tree.Format());
                oi.Flush();
                return(id);
            }
            finally
            {
                oi.Release();
            }
        }
        /// <summary>Attach a note to an object.</summary>
        /// <remarks>
        /// Attach a note to an object.
        /// If no note exists, a new note is stored. If a note already exists for the
        /// given object, it is replaced (or removed).
        /// </remarks>
        /// <param name="noteOn">
        /// the object to attach the note to. This same ObjectId can later
        /// be used as an argument to
        /// <see cref="Get(NGit.AnyObjectId)">Get(NGit.AnyObjectId)</see>
        /// or
        /// <see cref="GetCachedBytes(NGit.AnyObjectId, int)">GetCachedBytes(NGit.AnyObjectId, int)
        ///     </see>
        /// to read back the
        /// <code>noteData</code>
        /// .
        /// </param>
        /// <param name="noteData">
        /// text to store in the note. The text will be UTF-8 encoded when
        /// stored in the repository. If null the note will be deleted, if
        /// the empty string a note with the empty string will be stored.
        /// </param>
        /// <param name="ins">
        /// inserter to write the encoded
        /// <code>noteData</code>
        /// out as a blob.
        /// The caller must ensure the inserter is flushed before the
        /// updated note map is made available for reading.
        /// </param>
        /// <exception cref="System.IO.IOException">the note data could not be stored in the repository.
        ///     </exception>
        public virtual void Set(AnyObjectId noteOn, string noteData, ObjectInserter ins)
        {
            ObjectId dataId;

            if (noteData != null)
            {
                byte[] dataUTF8 = Constants.Encode(noteData);
                dataId = ins.Insert(Constants.OBJ_BLOB, dataUTF8);
            }
            else
            {
                dataId = null;
            }
            Set(noteOn, dataId);
        }
Exemple #15
0
        /// <exception cref="System.IO.IOException"></exception>
        private ObjectId InsertEmptyBlob()
        {
            ObjectId       emptyId;
            ObjectInserter oi = db.NewObjectInserter();

            try
            {
                emptyId = oi.Insert(Constants.OBJ_BLOB, new byte[] {  });
                oi.Flush();
            }
            finally
            {
                oi.Release();
            }
            return(emptyId);
        }
        /// <exception cref="System.IO.IOException"></exception>
        private DirCacheEntry AddEntryToBuilder(string path, FilePath file, ObjectInserter
                                                newObjectInserter, DirCacheBuilder builder, int stage)
        {
            FileInputStream inputStream = new FileInputStream(file);
            ObjectId        id          = newObjectInserter.Insert(Constants.OBJ_BLOB, file.Length(), inputStream
                                                                   );

            inputStream.Close();
            DirCacheEntry entry = new DirCacheEntry(path, stage);

            entry.SetObjectId(id);
            entry.FileMode     = FileMode.REGULAR_FILE;
            entry.LastModified = file.LastModified();
            entry.SetLength((int)file.Length());
            builder.Add(entry);
            return(entry);
        }
Exemple #17
0
        public virtual void Test002_WriteEmptyTree()
        {
            // One of our test packs contains the empty tree object. If the pack is
            // open when we create it we won't write the object file out as a loose
            // object (as it already exists in the pack).
            //
            Repository     newdb  = CreateBareRepository();
            ObjectInserter oi     = newdb.NewObjectInserter();
            ObjectId       treeId = oi.Insert(new TreeFormatter());

            oi.Release();
            NUnit.Framework.Assert.AreEqual("4b825dc642cb6eb9a060e54bf8d69288fbee4904", treeId
                                            .Name);
            FilePath o = new FilePath(new FilePath(new FilePath(newdb.Directory, "objects"),
                                                   "4b"), "825dc642cb6eb9a060e54bf8d69288fbee4904");

            NUnit.Framework.Assert.IsTrue(o.IsFile(), "Exists " + o);
            NUnit.Framework.Assert.IsTrue(!o.CanWrite(), "Read-only " + o);
        }
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Note Merge(Note @base, Note ours, Note theirs, ObjectReader reader
                                  , ObjectInserter inserter)
        {
            if (ours == null)
            {
                return(theirs);
            }
            if (theirs == null)
            {
                return(ours);
            }
            if (ours.GetData().Equals(theirs.GetData()))
            {
                return(ours);
            }
            ObjectLoader     lo       = reader.Open(ours.GetData());
            ObjectLoader     lt       = reader.Open(theirs.GetData());
            UnionInputStream union    = new UnionInputStream(lo.OpenStream(), lt.OpenStream());
            ObjectId         noteData = inserter.Insert(Constants.OBJ_BLOB, lo.GetSize() + lt.GetSize
                                                            (), union);

            return(new Note(ours, noteData));
        }
 /// <exception cref="System.IO.IOException"></exception>
 internal override ObjectId WriteTree(ObjectInserter inserter)
 {
     return(inserter.Insert(Build()));
 }
        public virtual void TestMissingSubtree_DetectFileAdded_FileModified()
        {
            ObjectInserter inserter = db.NewObjectInserter();
            ObjectId       aFileId  = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("a"));
            ObjectId       bFileId  = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("b"));
            ObjectId       cFileId1 = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("c-1"));
            ObjectId       cFileId2 = inserter.Insert(Constants.OBJ_BLOB, Constants.Encode("c-2"));
            // Create sub-a/empty, sub-c/empty = hello.
            ObjectId oldTree;
            {
                Tree root = new Tree(db);
                {
                    Tree subA = root.AddTree("sub-a");
                    subA.AddFile("empty").SetId(aFileId);
                    subA.SetId(inserter.Insert(Constants.OBJ_TREE, subA.Format()));
                }
                {
                    Tree subC = root.AddTree("sub-c");
                    subC.AddFile("empty").SetId(cFileId1);
                    subC.SetId(inserter.Insert(Constants.OBJ_TREE, subC.Format()));
                }
                oldTree = inserter.Insert(Constants.OBJ_TREE, root.Format());
            }
            // Create sub-a/empty, sub-b/empty, sub-c/empty.
            ObjectId newTree;

            {
                Tree root = new Tree(db);
                {
                    Tree subA = root.AddTree("sub-a");
                    subA.AddFile("empty").SetId(aFileId);
                    subA.SetId(inserter.Insert(Constants.OBJ_TREE, subA.Format()));
                }
                {
                    Tree subB = root.AddTree("sub-b");
                    subB.AddFile("empty").SetId(bFileId);
                    subB.SetId(inserter.Insert(Constants.OBJ_TREE, subB.Format()));
                }
                {
                    Tree subC = root.AddTree("sub-c");
                    subC.AddFile("empty").SetId(cFileId2);
                    subC.SetId(inserter.Insert(Constants.OBJ_TREE, subC.Format()));
                }
                newTree = inserter.Insert(Constants.OBJ_TREE, root.Format());
            }
            inserter.Flush();
            inserter.Release();
            TreeWalk tw = new TreeWalk(db);

            tw.Reset(oldTree, newTree);
            tw.Recursive = true;
            tw.Filter    = TreeFilter.ANY_DIFF;
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("sub-b/empty", tw.PathString);
            NUnit.Framework.Assert.AreEqual(FileMode.MISSING, tw.GetFileMode(0));
            NUnit.Framework.Assert.AreEqual(FileMode.REGULAR_FILE, tw.GetFileMode(1));
            NUnit.Framework.Assert.AreEqual(ObjectId.ZeroId, tw.GetObjectId(0));
            NUnit.Framework.Assert.AreEqual(bFileId, tw.GetObjectId(1));
            NUnit.Framework.Assert.IsTrue(tw.Next());
            NUnit.Framework.Assert.AreEqual("sub-c/empty", tw.PathString);
            NUnit.Framework.Assert.AreEqual(FileMode.REGULAR_FILE, tw.GetFileMode(0));
            NUnit.Framework.Assert.AreEqual(FileMode.REGULAR_FILE, tw.GetFileMode(1));
            NUnit.Framework.Assert.AreEqual(cFileId1, tw.GetObjectId(0));
            NUnit.Framework.Assert.AreEqual(cFileId2, tw.GetObjectId(1));
            NUnit.Framework.Assert.IsFalse(tw.Next());
        }
        /// <summary>
        /// Stash the contents on the working directory and index in separate commits
        /// and reset to the current HEAD commit.
        /// </summary>
        /// <remarks>
        /// Stash the contents on the working directory and index in separate commits
        /// and reset to the current HEAD commit.
        /// </remarks>
        /// <returns>stashed commit or null if no changes to stash</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException
        ///     </exception>
        public override RevCommit Call()
        {
            CheckCallable();
            Ref          head   = GetHead();
            ObjectReader reader = repo.NewObjectReader();

            try
            {
                RevCommit      headCommit = ParseCommit(reader, head.GetObjectId());
                DirCache       cache      = repo.LockDirCache();
                ObjectInserter inserter   = repo.NewObjectInserter();
                ObjectId       commitId;
                try
                {
                    TreeWalk treeWalk = new TreeWalk(reader);
                    treeWalk.Recursive = true;
                    treeWalk.AddTree(headCommit.Tree);
                    treeWalk.AddTree(new DirCacheIterator(cache));
                    treeWalk.AddTree(new FileTreeIterator(repo));
                    treeWalk.Filter = AndTreeFilter.Create(new SkipWorkTreeFilter(1), new IndexDiffFilter
                                                               (1, 2));
                    // Return null if no local changes to stash
                    if (!treeWalk.Next())
                    {
                        return(null);
                    }
                    MutableObjectId id = new MutableObjectId();
                    IList <DirCacheEditor.PathEdit> wtEdits = new AList <DirCacheEditor.PathEdit>();
                    IList <string> wtDeletes = new AList <string>();
                    do
                    {
                        AbstractTreeIterator headIter  = treeWalk.GetTree <AbstractTreeIterator>(0);
                        DirCacheIterator     indexIter = treeWalk.GetTree <DirCacheIterator>(1);
                        WorkingTreeIterator  wtIter    = treeWalk.GetTree <WorkingTreeIterator>(2);
                        if (headIter != null && indexIter != null && wtIter != null)
                        {
                            if (!indexIter.GetDirCacheEntry().IsMerged())
                            {
                                throw new UnmergedPathsException(new UnmergedPathException(indexIter.GetDirCacheEntry
                                                                                               ()));
                            }
                            if (wtIter.IdEqual(indexIter) || wtIter.IdEqual(headIter))
                            {
                                continue;
                            }
                            treeWalk.GetObjectId(id, 0);
                            DirCacheEntry entry = new DirCacheEntry(treeWalk.RawPath);
                            entry.SetLength(wtIter.GetEntryLength());
                            entry.LastModified = wtIter.GetEntryLastModified();
                            entry.FileMode     = wtIter.EntryFileMode;
                            long        contentLength = wtIter.GetEntryContentLength();
                            InputStream @in           = wtIter.OpenEntryStream();
                            try
                            {
                                entry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, contentLength, @in));
                            }
                            finally
                            {
                                @in.Close();
                            }
                            wtEdits.AddItem(new _PathEdit_273(entry, entry));
                        }
                        else
                        {
                            if (indexIter == null)
                            {
                                wtDeletes.AddItem(treeWalk.PathString);
                            }
                            else
                            {
                                if (wtIter == null && headIter != null)
                                {
                                    wtDeletes.AddItem(treeWalk.PathString);
                                }
                            }
                        }
                    }while (treeWalk.Next());
                    string branch = Repository.ShortenRefName(head.GetTarget().GetName());
                    // Commit index changes
                    NGit.CommitBuilder builder = CreateBuilder(headCommit);
                    builder.TreeId  = cache.WriteTree(inserter);
                    builder.Message = MessageFormat.Format(indexMessage, branch, headCommit.Abbreviate
                                                               (7).Name, headCommit.GetShortMessage());
                    ObjectId indexCommit = inserter.Insert(builder);
                    // Commit working tree changes
                    if (!wtEdits.IsEmpty() || !wtDeletes.IsEmpty())
                    {
                        DirCacheEditor editor = cache.Editor();
                        foreach (DirCacheEditor.PathEdit edit in wtEdits)
                        {
                            editor.Add(edit);
                        }
                        foreach (string path in wtDeletes)
                        {
                            editor.Add(new DirCacheEditor.DeletePath(path));
                        }
                        editor.Finish();
                    }
                    builder.AddParentId(indexCommit);
                    builder.Message = MessageFormat.Format(workingDirectoryMessage, branch, headCommit
                                                           .Abbreviate(7).Name, headCommit.GetShortMessage());
                    builder.TreeId = cache.WriteTree(inserter);
                    commitId       = inserter.Insert(builder);
                    inserter.Flush();
                    UpdateStashRef(commitId, builder.Author, builder.Message);
                }
                finally
                {
                    inserter.Release();
                    cache.Unlock();
                }
                // Hard reset to HEAD
                new ResetCommand(repo).SetMode(ResetCommand.ResetType.HARD).Call();
                // Return stashed commit
                return(ParseCommit(reader, commitId));
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().stashFailed, e);
            }
            finally
            {
                reader.Release();
            }
        }
Exemple #22
0
        public virtual void Test026_CreateCommitMultipleparents()
        {
            ObjectId       treeId;
            ObjectInserter oi = db.NewObjectInserter();

            try
            {
                ObjectId blobId = oi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString
                                                ("and this is the data in me\n", Constants.CHARSET.Name()));
                TreeFormatter fmt = new TreeFormatter();
                fmt.Append("i-am-a-file", FileMode.REGULAR_FILE, blobId);
                treeId = oi.Insert(fmt);
                oi.Flush();
            }
            finally
            {
                oi.Release();
            }
            NUnit.Framework.Assert.AreEqual(ObjectId.FromString("00b1f73724f493096d1ffa0b0f1f1482dbb8c936"
                                                                ), treeId);
            NGit.CommitBuilder c1 = new NGit.CommitBuilder();
            c1.Author    = new PersonIdent(author, 1154236443000L, -4 * 60);
            c1.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60);
            c1.Message   = "A Commit\n";
            c1.TreeId    = treeId;
            NUnit.Framework.Assert.AreEqual(treeId, c1.TreeId);
            ObjectId actid1 = InsertCommit(c1);
            ObjectId cmtid1 = ObjectId.FromString("803aec4aba175e8ab1d666873c984c0308179099");

            NUnit.Framework.Assert.AreEqual(cmtid1, actid1);
            NGit.CommitBuilder c2 = new NGit.CommitBuilder();
            c2.Author    = new PersonIdent(author, 1154236443000L, -4 * 60);
            c2.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60);
            c2.Message   = "A Commit 2\n";
            c2.TreeId    = treeId;
            NUnit.Framework.Assert.AreEqual(treeId, c2.TreeId);
            c2.SetParentIds(actid1);
            ObjectId actid2 = InsertCommit(c2);
            ObjectId cmtid2 = ObjectId.FromString("95d068687c91c5c044fb8c77c5154d5247901553");

            NUnit.Framework.Assert.AreEqual(cmtid2, actid2);
            RevCommit rm2 = ParseCommit(cmtid2);

            NUnit.Framework.Assert.AreNotSame(c2, rm2);
            // assert the parsed objects is not from the
            // cache
            NUnit.Framework.Assert.AreEqual(c2.Author, rm2.GetAuthorIdent());
            NUnit.Framework.Assert.AreEqual(actid2, rm2.Id);
            NUnit.Framework.Assert.AreEqual(c2.Message, rm2.GetFullMessage());
            NUnit.Framework.Assert.AreEqual(c2.TreeId, rm2.Tree.Id);
            NUnit.Framework.Assert.AreEqual(1, rm2.ParentCount);
            NUnit.Framework.Assert.AreEqual(actid1, rm2.GetParent(0));
            NGit.CommitBuilder c3 = new NGit.CommitBuilder();
            c3.Author    = new PersonIdent(author, 1154236443000L, -4 * 60);
            c3.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60);
            c3.Message   = "A Commit 3\n";
            c3.TreeId    = treeId;
            NUnit.Framework.Assert.AreEqual(treeId, c3.TreeId);
            c3.SetParentIds(actid1, actid2);
            ObjectId actid3 = InsertCommit(c3);
            ObjectId cmtid3 = ObjectId.FromString("ce6e1ce48fbeeb15a83f628dc8dc2debefa066f4");

            NUnit.Framework.Assert.AreEqual(cmtid3, actid3);
            RevCommit rm3 = ParseCommit(cmtid3);

            NUnit.Framework.Assert.AreNotSame(c3, rm3);
            // assert the parsed objects is not from the
            // cache
            NUnit.Framework.Assert.AreEqual(c3.Author, rm3.GetAuthorIdent());
            NUnit.Framework.Assert.AreEqual(actid3, rm3.Id);
            NUnit.Framework.Assert.AreEqual(c3.Message, rm3.GetFullMessage());
            NUnit.Framework.Assert.AreEqual(c3.TreeId, rm3.Tree.Id);
            NUnit.Framework.Assert.AreEqual(2, rm3.ParentCount);
            NUnit.Framework.Assert.AreEqual(actid1, rm3.GetParent(0));
            NUnit.Framework.Assert.AreEqual(actid2, rm3.GetParent(1));
            NGit.CommitBuilder c4 = new NGit.CommitBuilder();
            c4.Author    = new PersonIdent(author, 1154236443000L, -4 * 60);
            c4.Committer = new PersonIdent(committer, 1154236443000L, -4 * 60);
            c4.Message   = "A Commit 4\n";
            c4.TreeId    = treeId;
            NUnit.Framework.Assert.AreEqual(treeId, c3.TreeId);
            c4.SetParentIds(actid1, actid2, actid3);
            ObjectId actid4 = InsertCommit(c4);
            ObjectId cmtid4 = ObjectId.FromString("d1fca9fe3fef54e5212eb67902c8ed3e79736e27");

            NUnit.Framework.Assert.AreEqual(cmtid4, actid4);
            RevCommit rm4 = ParseCommit(cmtid4);

            NUnit.Framework.Assert.AreNotSame(c4, rm3);
            // assert the parsed objects is not from the
            // cache
            NUnit.Framework.Assert.AreEqual(c4.Author, rm4.GetAuthorIdent());
            NUnit.Framework.Assert.AreEqual(actid4, rm4.Id);
            NUnit.Framework.Assert.AreEqual(c4.Message, rm4.GetFullMessage());
            NUnit.Framework.Assert.AreEqual(c4.TreeId, rm4.Tree.Id);
            NUnit.Framework.Assert.AreEqual(3, rm4.ParentCount);
            NUnit.Framework.Assert.AreEqual(actid1, rm4.GetParent(0));
            NUnit.Framework.Assert.AreEqual(actid2, rm4.GetParent(1));
            NUnit.Framework.Assert.AreEqual(actid3, rm4.GetParent(2));
        }
Exemple #23
0
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        private bool ContentMerge(CanonicalTreeParser @base, CanonicalTreeParser ours, CanonicalTreeParser
                                  theirs)
        {
            MergeFormatter fmt      = new MergeFormatter();
            RawText        baseText = @base == null ? RawText.EMPTY_TEXT : GetRawText(@base.EntryObjectId
                                                                                      , db);
            // do the merge
            MergeResult <RawText> result = mergeAlgorithm.Merge(RawTextComparator.DEFAULT, baseText
                                                                , GetRawText(ours.EntryObjectId, db), GetRawText(theirs.EntryObjectId, db));
            FilePath         of = null;
            FileOutputStream fos;

            if (!inCore)
            {
                FilePath workTree = db.WorkTree;
                if (workTree == null)
                {
                    // TODO: This should be handled by WorkingTreeIterators which
                    // support write operations
                    throw new NotSupportedException();
                }
                of  = new FilePath(workTree, tw.PathString);
                fos = new FileOutputStream(of);
                try
                {
                    fmt.FormatMerge(fos, result, Arrays.AsList(commitNames), Constants.CHARACTER_ENCODING
                                    );
                }
                finally
                {
                    fos.Close();
                }
            }
            else
            {
                if (!result.ContainsConflicts())
                {
                    // When working inCore, only trivial merges can be handled,
                    // so we generate objects only in conflict free cases
                    of  = FilePath.CreateTempFile("merge_", "_temp", null);
                    fos = new FileOutputStream(of);
                    try
                    {
                        fmt.FormatMerge(fos, result, Arrays.AsList(commitNames), Constants.CHARACTER_ENCODING
                                        );
                    }
                    finally
                    {
                        fos.Close();
                    }
                }
            }
            if (result.ContainsConflicts())
            {
                // a conflict occurred, the file will contain conflict markers
                // the index will be populated with the three stages and only the
                // workdir (if used) contains the halfways merged content
                Add(tw.RawPath, @base, DirCacheEntry.STAGE_1);
                Add(tw.RawPath, ours, DirCacheEntry.STAGE_2);
                Add(tw.RawPath, theirs, DirCacheEntry.STAGE_3);
                mergeResults.Put(tw.PathString, result.Upcast());
                return(false);
            }
            else
            {
                // no conflict occurred, the file will contain fully merged content.
                // the index will be populated with the new merged version
                DirCacheEntry dce = new DirCacheEntry(tw.PathString);
                dce.FileMode     = tw.GetFileMode(0);
                dce.LastModified = of.LastModified();
                dce.SetLength((int)of.Length());
                InputStream @is = new FileInputStream(of);
                try
                {
                    dce.SetObjectId(oi.Insert(Constants.OBJ_BLOB, of.Length(), @is));
                }
                finally
                {
                    @is.Close();
                    if (inCore)
                    {
                        FileUtils.Delete(of);
                    }
                }
                builder.Add(dce);
                return(true);
            }
        }
Exemple #24
0
        /// <exception cref="System.IO.IOException"></exception>
        private DirCache CreateTemporaryIndex(ObjectId headId, DirCache index)
        {
            ObjectInserter inserter = null;
            // get DirCacheEditor to modify the index if required
            DirCacheEditor dcEditor = index.Editor();
            // get DirCacheBuilder for newly created in-core index to build a
            // temporary index for this commit
            DirCache        inCoreIndex = DirCache.NewInCore();
            DirCacheBuilder dcBuilder   = inCoreIndex.Builder();

            onlyProcessed = new bool[only.Count];
            bool     emptyCommit = true;
            TreeWalk treeWalk    = new TreeWalk(repo);
            int      dcIdx       = treeWalk.AddTree(new DirCacheIterator(index));
            int      fIdx        = treeWalk.AddTree(new FileTreeIterator(repo));
            int      hIdx        = -1;

            if (headId != null)
            {
                hIdx = treeWalk.AddTree(new RevWalk(repo).ParseTree(headId));
            }
            treeWalk.Recursive = true;
            while (treeWalk.Next())
            {
                string path = treeWalk.PathString;
                // check if current entry's path matches a specified path
                int pos = LookupOnly(path);
                CanonicalTreeParser hTree = null;
                if (hIdx != -1)
                {
                    hTree = treeWalk.GetTree <CanonicalTreeParser>(hIdx);
                }
                if (pos >= 0)
                {
                    // include entry in commit
                    DirCacheIterator dcTree = treeWalk.GetTree <DirCacheIterator>(dcIdx);
                    FileTreeIterator fTree  = treeWalk.GetTree <FileTreeIterator>(fIdx);
                    // check if entry refers to a tracked file
                    bool tracked = dcTree != null || hTree != null;
                    if (!tracked)
                    {
                        break;
                    }
                    if (fTree != null)
                    {
                        // create a new DirCacheEntry with data retrieved from disk
                        DirCacheEntry dcEntry     = new DirCacheEntry(path);
                        long          entryLength = fTree.GetEntryLength();
                        dcEntry.SetLength(entryLength);
                        dcEntry.LastModified = fTree.GetEntryLastModified();
                        dcEntry.FileMode     = fTree.GetIndexFileMode(dcTree);
                        bool objectExists = (dcTree != null && fTree.IdEqual(dcTree)) || (hTree != null &&
                                                                                          fTree.IdEqual(hTree));
                        if (objectExists)
                        {
                            dcEntry.SetObjectId(fTree.EntryObjectId);
                        }
                        else
                        {
                            if (FileMode.GITLINK.Equals(dcEntry.FileMode))
                            {
                                dcEntry.SetObjectId(fTree.EntryObjectId);
                            }
                            else
                            {
                                // insert object
                                if (inserter == null)
                                {
                                    inserter = repo.NewObjectInserter();
                                }
                                long        contentLength = fTree.GetEntryContentLength();
                                InputStream inputStream   = fTree.OpenEntryStream();
                                try
                                {
                                    dcEntry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, contentLength, inputStream
                                                                        ));
                                }
                                finally
                                {
                                    inputStream.Close();
                                }
                            }
                        }
                        // update index
                        dcEditor.Add(new _PathEdit_375(dcEntry, path));
                        // add to temporary in-core index
                        dcBuilder.Add(dcEntry);
                        if (emptyCommit && (hTree == null || !hTree.IdEqual(fTree) || hTree.EntryRawMode
                                            != fTree.EntryRawMode))
                        {
                            // this is a change
                            emptyCommit = false;
                        }
                    }
                    else
                    {
                        // if no file exists on disk, remove entry from index and
                        // don't add it to temporary in-core index
                        dcEditor.Add(new DirCacheEditor.DeletePath(path));
                        if (emptyCommit && hTree != null)
                        {
                            // this is a change
                            emptyCommit = false;
                        }
                    }
                    // keep track of processed path
                    onlyProcessed[pos] = true;
                }
                else
                {
                    // add entries from HEAD for all other paths
                    if (hTree != null)
                    {
                        // create a new DirCacheEntry with data retrieved from HEAD
                        DirCacheEntry dcEntry = new DirCacheEntry(path);
                        dcEntry.SetObjectId(hTree.EntryObjectId);
                        dcEntry.FileMode = hTree.EntryFileMode;
                        // add to temporary in-core index
                        dcBuilder.Add(dcEntry);
                    }
                }
            }
            // there must be no unprocessed paths left at this point; otherwise an
            // untracked or unknown path has been specified
            for (int i = 0; i < onlyProcessed.Length; i++)
            {
                if (!onlyProcessed[i])
                {
                    throw new JGitInternalException(MessageFormat.Format(JGitText.Get().entryNotFoundByPath
                                                                         , only[i]));
                }
            }
            // there must be at least one change
            if (emptyCommit)
            {
                throw new JGitInternalException(JGitText.Get().emptyCommit);
            }
            // update index
            dcEditor.Commit();
            // finish temporary in-core index used for this commit
            dcBuilder.Finish();
            return(inCoreIndex);
        }
Exemple #25
0
        /// <summary>
        /// Executes the
        /// <code>commit</code>
        /// command with all the options and parameters
        /// collected by the setter methods of this class. Each instance of this
        /// class should only be used for one invocation of the command (means: one
        /// call to
        /// <see cref="Call()">Call()</see>
        /// )
        /// </summary>
        /// <returns>
        /// a
        /// <see cref="NGit.Revwalk.RevCommit">NGit.Revwalk.RevCommit</see>
        /// object representing the successful commit.
        /// </returns>
        /// <exception cref="NGit.Api.Errors.NoHeadException">when called on a git repo without a HEAD reference
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.NoMessageException">when called without specifying a commit message
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.UnmergedPathsException">when the current index contained unmerged paths (conflicts)
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException">
        /// when HEAD or branch ref is updated concurrently by someone
        /// else
        /// </exception>
        /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">when repository is not in the right state for committing
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        public override RevCommit Call()
        {
            CheckCallable();
            RepositoryState state = repo.GetRepositoryState();

            if (!state.CanCommit())
            {
                throw new WrongRepositoryStateException(MessageFormat.Format(JGitText.Get().cannotCommitOnARepoWithState
                                                                             , state.Name()));
            }
            ProcessOptions(state);
            try
            {
                if (all && !repo.IsBare && repo.WorkTree != null)
                {
                    Git git = new Git(repo);
                    try
                    {
                        git.Add().AddFilepattern(".").SetUpdate(true).Call();
                    }
                    catch (NoFilepatternException e)
                    {
                        // should really not happen
                        throw new JGitInternalException(e.Message, e);
                    }
                }
                Ref head = repo.GetRef(Constants.HEAD);
                if (head == null)
                {
                    throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported
                                              );
                }
                // determine the current HEAD and the commit it is referring to
                ObjectId headId = repo.Resolve(Constants.HEAD + "^{commit}");
                if (headId == null && amend)
                {
                    throw new WrongRepositoryStateException(JGitText.Get().commitAmendOnInitialNotPossible
                                                            );
                }
                if (headId != null)
                {
                    if (amend)
                    {
                        RevCommit   previousCommit = new RevWalk(repo).ParseCommit(headId);
                        RevCommit[] p = previousCommit.Parents;
                        for (int i = 0; i < p.Length; i++)
                        {
                            parents.Add(0, p[i].Id);
                        }
                        if (author == null)
                        {
                            author = previousCommit.GetAuthorIdent();
                        }
                    }
                    else
                    {
                        parents.Add(0, headId);
                    }
                }
                // lock the index
                DirCache index = repo.LockDirCache();
                try
                {
                    if (!only.IsEmpty())
                    {
                        index = CreateTemporaryIndex(headId, index);
                    }
                    ObjectInserter odi = repo.NewObjectInserter();
                    try
                    {
                        // Write the index as tree to the object database. This may
                        // fail for example when the index contains unmerged paths
                        // (unresolved conflicts)
                        ObjectId indexTreeId = index.WriteTree(odi);
                        if (insertChangeId)
                        {
                            InsertChangeId(indexTreeId);
                        }
                        // Create a Commit object, populate it and write it
                        NGit.CommitBuilder commit = new NGit.CommitBuilder();
                        commit.Committer = committer;
                        commit.Author    = author;
                        commit.Message   = message;
                        commit.SetParentIds(parents);
                        commit.TreeId = indexTreeId;
                        ObjectId commitId = odi.Insert(commit);
                        odi.Flush();
                        RevWalk revWalk = new RevWalk(repo);
                        try
                        {
                            RevCommit revCommit = revWalk.ParseCommit(commitId);
                            RefUpdate ru        = repo.UpdateRef(Constants.HEAD);
                            ru.SetNewObjectId(commitId);
                            if (reflogComment != null)
                            {
                                ru.SetRefLogMessage(reflogComment, false);
                            }
                            else
                            {
                                string prefix = amend ? "commit (amend): " : "commit: ";
                                ru.SetRefLogMessage(prefix + revCommit.GetShortMessage(), false);
                            }
                            if (headId != null)
                            {
                                ru.SetExpectedOldObjectId(headId);
                            }
                            else
                            {
                                ru.SetExpectedOldObjectId(ObjectId.ZeroId);
                            }
                            RefUpdate.Result rc = ru.ForceUpdate();
                            switch (rc)
                            {
                            case RefUpdate.Result.NEW:
                            case RefUpdate.Result.FORCED:
                            case RefUpdate.Result.FAST_FORWARD:
                            {
                                SetCallable(false);
                                if (state == RepositoryState.MERGING_RESOLVED)
                                {
                                    // Commit was successful. Now delete the files
                                    // used for merge commits
                                    repo.WriteMergeCommitMsg(null);
                                    repo.WriteMergeHeads(null);
                                }
                                else
                                {
                                    if (state == RepositoryState.CHERRY_PICKING_RESOLVED)
                                    {
                                        repo.WriteMergeCommitMsg(null);
                                        repo.WriteCherryPickHead(null);
                                    }
                                }
                                return(revCommit);
                            }

                            case RefUpdate.Result.REJECTED:
                            case RefUpdate.Result.LOCK_FAILURE:
                            {
                                throw new ConcurrentRefUpdateException(JGitText.Get().couldNotLockHEAD, ru.GetRef
                                                                           (), rc);
                            }

                            default:
                            {
                                throw new JGitInternalException(MessageFormat.Format(JGitText.Get().updatingRefFailed
                                                                                     , Constants.HEAD, commitId.ToString(), rc));
                            }
                            }
                        }
                        finally
                        {
                            revWalk.Release();
                        }
                    }
                    finally
                    {
                        odi.Release();
                    }
                }
                finally
                {
                    index.Unlock();
                }
            }
            catch (UnmergedPathException e)
            {
                throw new UnmergedPathsException(e);
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfCommitCommand
                                                , e);
            }
        }
Exemple #26
0
        /// <summary>
        /// Executes the
        /// <code>Add</code>
        /// command. 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>the DirCache after Add</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        /// <exception cref="NGit.Api.Errors.NoFilepatternException"></exception>
        public override DirCache Call()
        {
            if (filepatterns.IsEmpty())
            {
                throw new NoFilepatternException(JGitText.Get().atLeastOnePatternIsRequired);
            }
            CheckCallable();
            DirCache dc     = null;
            bool     addAll = false;

            if (filepatterns.Contains("."))
            {
                addAll = true;
            }
            ObjectInserter inserter = repo.NewObjectInserter();

            try
            {
                dc = repo.LockDirCache();
                DirCacheIterator c;
                DirCacheBuilder  builder = dc.Builder();
                TreeWalk         tw      = new TreeWalk(repo);
                tw.AddTree(new DirCacheBuildIterator(builder));
                if (workingTreeIterator == null)
                {
                    workingTreeIterator = new FileTreeIterator(repo);
                }
                tw.AddTree(workingTreeIterator);
                tw.Recursive = true;
                if (!addAll)
                {
                    tw.Filter = PathFilterGroup.CreateFromStrings(filepatterns);
                }
                string lastAddedFile = null;
                while (tw.Next())
                {
                    string path           = tw.PathString;
                    WorkingTreeIterator f = tw.GetTree <WorkingTreeIterator>(1);
                    if (tw.GetTree <DirCacheIterator>(0) == null && f != null && f.IsEntryIgnored())
                    {
                    }
                    else
                    {
                        // file is not in index but is ignored, do nothing
                        // In case of an existing merge conflict the
                        // DirCacheBuildIterator iterates over all stages of
                        // this path, we however want to add only one
                        // new DirCacheEntry per path.
                        if (!(path.Equals(lastAddedFile)))
                        {
                            if (!(update && tw.GetTree <DirCacheIterator>(0) == null))
                            {
                                c = tw.GetTree <DirCacheIterator>(0);
                                if (f != null)
                                {
                                    // the file exists
                                    long          sz    = f.GetEntryLength();
                                    DirCacheEntry entry = new DirCacheEntry(path);
                                    if (c == null || c.GetDirCacheEntry() == null || !c.GetDirCacheEntry().IsAssumeValid)
                                    {
                                        FileMode mode = f.GetIndexFileMode(c);
                                        entry.FileMode = mode;
                                        if (FileMode.GITLINK != mode)
                                        {
                                            entry.SetLength(sz);
                                            entry.LastModified = f.GetEntryLastModified();
                                            long        contentSize = f.GetEntryContentLength();
                                            InputStream @in         = f.OpenEntryStream();
                                            try
                                            {
                                                entry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, contentSize, @in));
                                            }
                                            finally
                                            {
                                                @in.Close();
                                            }
                                        }
                                        else
                                        {
                                            entry.SetObjectId(f.EntryObjectId);
                                        }
                                        builder.Add(entry);
                                        lastAddedFile = path;
                                    }
                                    else
                                    {
                                        builder.Add(c.GetDirCacheEntry());
                                    }
                                }
                                else
                                {
                                    if (c != null && (!update || FileMode.GITLINK == c.EntryFileMode))
                                    {
                                        builder.Add(c.GetDirCacheEntry());
                                    }
                                }
                            }
                        }
                    }
                }
                inserter.Flush();
                builder.Commit();
                SetCallable(false);
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfAddCommand
                                                , e);
            }
            finally
            {
                inserter.Release();
                if (dc != null)
                {
                    dc.Unlock();
                }
            }
            return(dc);
        }
Exemple #27
0
        /// <summary>
        /// Executes the
        /// <code>tag</code>
        /// command with all the options and parameters
        /// collected by the setter methods of this class. Each instance of this
        /// class should only be used for one invocation of the command (means: one
        /// call to
        /// <see cref="Call()">Call()</see>
        /// )
        /// </summary>
        /// <returns>
        /// a
        /// <see cref="NGit.Ref">NGit.Ref</see>
        /// a ref pointing to a tag
        /// </returns>
        /// <exception cref="NGit.Api.Errors.NoHeadException">when called on a git repo without a HEAD reference
        ///     </exception>
        /// <since>2.0</since>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException"></exception>
        /// <exception cref="NGit.Api.Errors.InvalidTagNameException"></exception>
        public override Ref Call()
        {
            CheckCallable();
            RepositoryState state = repo.GetRepositoryState();

            ProcessOptions(state);
            try
            {
                // create the tag object
                TagBuilder newTag = new TagBuilder();
                newTag.SetTag(name);
                newTag.SetMessage(message);
                newTag.SetTagger(tagger);
                // if no id is set, we should attempt to use HEAD
                if (id == null)
                {
                    ObjectId objectId = repo.Resolve(Constants.HEAD + "^{commit}");
                    if (objectId == null)
                    {
                        throw new NoHeadException(JGitText.Get().tagOnRepoWithoutHEADCurrentlyNotSupported
                                                  );
                    }
                    newTag.SetObjectId(objectId, Constants.OBJ_COMMIT);
                }
                else
                {
                    newTag.SetObjectId(id);
                }
                // write the tag object
                ObjectInserter inserter = repo.NewObjectInserter();
                try
                {
                    ObjectId tagId = inserter.Insert(newTag);
                    inserter.Flush();
                    RevWalk revWalk = new RevWalk(repo);
                    try
                    {
                        string    refName = Constants.R_TAGS + newTag.GetTag();
                        RefUpdate tagRef  = repo.UpdateRef(refName);
                        tagRef.SetNewObjectId(tagId);
                        tagRef.SetForceUpdate(forceUpdate);
                        tagRef.SetRefLogMessage("tagged " + name, false);
                        RefUpdate.Result updateResult = tagRef.Update(revWalk);
                        switch (updateResult)
                        {
                        case RefUpdate.Result.NEW:
                        case RefUpdate.Result.FORCED:
                        {
                            return(repo.GetRef(refName));
                        }

                        case RefUpdate.Result.LOCK_FAILURE:
                        {
                            throw new ConcurrentRefUpdateException(JGitText.Get().couldNotLockHEAD, tagRef.GetRef
                                                                       (), updateResult);
                        }

                        default:
                        {
                            throw new JGitInternalException(MessageFormat.Format(JGitText.Get().updatingRefFailed
                                                                                 , refName, newTag.ToString(), updateResult));
                        }
                        }
                    }
                    finally
                    {
                        revWalk.Release();
                    }
                }
                finally
                {
                    inserter.Release();
                }
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfTagCommand
                                                , e);
            }
        }