Beispiel #1
0
 /// <summary>Performs the merge.</summary>
 /// <remarks>Performs the merge.</remarks>
 /// <param name="base">base version of the note tree</param>
 /// <param name="ours">ours version of the note tree</param>
 /// <param name="theirs">theirs version of the note tree</param>
 /// <returns>merge result as a new NoteMap</returns>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public virtual NoteMap Merge(NoteMap @base, NoteMap ours, NoteMap theirs)
 {
     try
     {
         InMemoryNoteBucket mergedBucket = Merge(0, @base.GetRoot(), ours.GetRoot(), theirs
                                                 .GetRoot());
         inserter.Flush();
         return(NoteMap.NewMap(mergedBucket, reader));
     }
     finally
     {
         reader.Release();
         inserter.Release();
     }
 }
Beispiel #2
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);
        }
Beispiel #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));
        }
Beispiel #4
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);
     }
 }
Beispiel #5
0
 /// <exception cref="NGit.Errors.TransportException"></exception>
 protected internal override void DoFetch(ProgressMonitor monitor, ICollection <Ref
                                                                                > want, ICollection <ObjectId> have)
 {
     VerifyPrerequisites();
     try
     {
         ObjectInserter ins = transport.local.NewObjectInserter();
         try
         {
             PackParser parser = ins.NewPackParser(bin);
             parser.SetAllowThin(true);
             parser.SetObjectChecking(transport.IsCheckFetchedObjects());
             parser.SetLockMessage(lockMessage);
             packLock = parser.Parse(NullProgressMonitor.INSTANCE);
             ins.Flush();
         }
         finally
         {
             ins.Release();
         }
     }
     catch (IOException err)
     {
         Close();
         throw new TransportException(transport.uri, err.Message, err);
     }
     catch (RuntimeException err)
     {
         Close();
         throw new TransportException(transport.uri, err.Message, err);
     }
 }
        /// <exception cref="System.IO.IOException"></exception>
        private void ReceivePack(ProgressMonitor monitor)
        {
            OnReceivePack();
            InputStream input = @in;

            if (sideband)
            {
                input = new SideBandInputStream(input, monitor, GetMessageWriter());
            }
            ObjectInserter ins = local.NewObjectInserter();

            try
            {
                PackParser parser = ins.NewPackParser(input);
                parser.SetAllowThin(thinPack);
                parser.SetObjectChecking(transport.IsCheckFetchedObjects());
                parser.SetLockMessage(lockMessage);
                packLock = parser.Parse(monitor);
                ins.Flush();
            }
            finally
            {
                ins.Release();
            }
        }
        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);
        }
Beispiel #8
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);
        }
Beispiel #9
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();
            }
        }
Beispiel #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();
            }
        }
Beispiel #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();
            }
        }
Beispiel #12
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();
            }
        }
Beispiel #13
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);
        }
Beispiel #14
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());
        }
Beispiel #15
0
 /// <summary>Merge together two or more tree-ish objects.</summary>
 /// <remarks>
 /// Merge together two or more tree-ish objects.
 /// <p>
 /// Any tree-ish may be supplied as inputs. Commits and/or tags pointing at
 /// trees or commits may be passed as input objects.
 /// </remarks>
 /// <param name="tips">
 /// source trees to be combined together. The merge base is not
 /// included in this set.
 /// </param>
 /// <returns>
 /// true if the merge was completed without conflicts; false if the
 /// merge strategy cannot handle this merge or there were conflicts
 /// preventing it from automatically resolving all paths.
 /// </returns>
 /// <exception cref="NGit.Errors.IncorrectObjectTypeException">
 /// one of the input objects is not a commit, but the strategy
 /// requires it to be a commit.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// one or more sources could not be read, or outputs could not
 /// be written to the Repository.
 /// </exception>
 public virtual bool Merge(params AnyObjectId[] tips)
 {
     sourceObjects = new RevObject[tips.Length];
     for (int i = 0; i < tips.Length; i++)
     {
         sourceObjects[i] = walk.ParseAny(tips[i]);
     }
     sourceCommits = new RevCommit[sourceObjects.Length];
     for (int i_1 = 0; i_1 < sourceObjects.Length; i_1++)
     {
         try
         {
             sourceCommits[i_1] = walk.ParseCommit(sourceObjects[i_1]);
         }
         catch (IncorrectObjectTypeException)
         {
             sourceCommits[i_1] = null;
         }
     }
     sourceTrees = new RevTree[sourceObjects.Length];
     for (int i_2 = 0; i_2 < sourceObjects.Length; i_2++)
     {
         sourceTrees[i_2] = walk.ParseTree(sourceObjects[i_2]);
     }
     try
     {
         bool ok = MergeImpl();
         if (ok && inserter != null)
         {
             inserter.Flush();
         }
         return(ok);
     }
     finally
     {
         if (inserter != null)
         {
             inserter.Release();
         }
         reader.Release();
     }
 }
        /// <summary>
        /// Stash the contents on the working directory and index in separate commits
        /// and reset to the current HEAD commit.
        /// </summary>
        /// <remarks>
        /// Stash the contents on the working directory and index in separate commits
        /// and reset to the current HEAD commit.
        /// </remarks>
        /// <returns>stashed commit or null if no changes to stash</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException
        ///     </exception>
        public override RevCommit Call()
        {
            CheckCallable();
            Ref          head   = GetHead();
            ObjectReader reader = repo.NewObjectReader();

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

                builder = cache.Builder();
                while (tw.Next())
                {
                    int modeO = tw.GetRawMode(T_OURS);
                    int modeT = tw.GetRawMode(T_THEIRS);
                    if (modeO == modeT && tw.IdEqual(T_OURS, T_THEIRS))
                    {
                        Add(T_OURS, DirCacheEntry.STAGE_0);
                        continue;
                    }
                    int modeB = tw.GetRawMode(T_BASE);
                    if (modeB == modeO && tw.IdEqual(T_BASE, T_OURS))
                    {
                        Add(T_THEIRS, DirCacheEntry.STAGE_0);
                    }
                    else
                    {
                        if (modeB == modeT && tw.IdEqual(T_BASE, T_THEIRS))
                        {
                            Add(T_OURS, DirCacheEntry.STAGE_0);
                        }
                        else
                        {
                            if (NonTree(modeB))
                            {
                                Add(T_BASE, DirCacheEntry.STAGE_1);
                                hasConflict = true;
                            }
                            if (NonTree(modeO))
                            {
                                Add(T_OURS, DirCacheEntry.STAGE_2);
                                hasConflict = true;
                            }
                            if (NonTree(modeT))
                            {
                                Add(T_THEIRS, DirCacheEntry.STAGE_3);
                                hasConflict = true;
                            }
                            if (tw.IsSubtree)
                            {
                                tw.EnterSubtree();
                            }
                        }
                    }
                }
                builder.Finish();
                builder = null;
                if (hasConflict)
                {
                    return(false);
                }
                try
                {
                    ObjectInserter odi = GetObjectInserter();
                    resultTree = cache.WriteTree(odi);
                    odi.Flush();
                    return(true);
                }
                catch (UnmergedPathException)
                {
                    resultTree = null;
                    return(false);
                }
            }
Beispiel #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));
        }