Example #1
0
 public override void Apply(DirCacheEntry ent)
 {
     ent.SetObjectId(blobId);
     ent.FileMode = mode;
     try
     {
         DirCacheCheckout.CheckoutEntry(this._enclosing.repo, new FilePath(workTree, ent.PathString
                                                                           ), ent, r);
     }
     catch (IOException e)
     {
         throw new JGitInternalException(MessageFormat.Format(JGitText.Get().checkoutConflictWithFile
                                                              , ent.PathString), e);
     }
 }
Example #2
0
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        private void CheckoutCommit(RevCommit commit)
        {
            RevWalk          walk = new RevWalk(db);
            RevCommit        head = walk.ParseCommit(db.Resolve(Constants.HEAD));
            DirCacheCheckout dco  = new DirCacheCheckout(db, head.Tree, db.LockDirCache(), commit
                                                         .Tree);

            dco.SetFailOnConflict(true);
            dco.Checkout();
            walk.Release();
            // update the HEAD
            RefUpdate refUpdate = db.UpdateRef(Constants.HEAD, true);

            refUpdate.SetNewObjectId(commit);
            refUpdate.ForceUpdate();
        }
Example #3
0
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        protected internal virtual void CheckoutBranch(string branchName)
        {
            RevWalk          walk   = new RevWalk(db);
            RevCommit        head   = walk.ParseCommit(db.Resolve(Constants.HEAD));
            RevCommit        branch = walk.ParseCommit(db.Resolve(branchName));
            DirCacheCheckout dco    = new DirCacheCheckout(db, head.Tree.Id, db.LockDirCache(),
                                                           branch.Tree.Id);

            dco.SetFailOnConflict(true);
            dco.Checkout();
            walk.Release();
            // update the HEAD
            RefUpdate refUpdate = db.UpdateRef(Constants.HEAD);

            refUpdate.Link(branchName);
        }
Example #4
0
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        private void CheckoutBranch(string branchName)
        {
            RevWalk          walk   = new RevWalk(db);
            RevCommit        head   = walk.ParseCommit(db.Resolve(Constants.HEAD));
            RevCommit        branch = walk.ParseCommit(db.Resolve(branchName));
            DirCacheCheckout dco    = new DirCacheCheckout(db, head.Tree, db.LockDirCache(), branch
                                                           .Tree);

            dco.SetFailOnConflict(true);
            NUnit.Framework.Assert.IsTrue(dco.Checkout());
            walk.Release();
            // update the HEAD
            RefUpdate refUpdate = db.UpdateRef(Constants.HEAD);

            NUnit.Framework.Assert.AreEqual(RefUpdate.Result.FORCED, refUpdate.Link(branchName
                                                                                    ));
        }
Example #5
0
        /// <exception cref="System.IO.IOException"></exception>
        private void ApplyChanges(TreeWalk treeWalk, DirCache cache, DirCacheEditor editor
                                  )
        {
            FilePath workingTree = repo.WorkTree;

            while (treeWalk.Next())
            {
                string   path = treeWalk.PathString;
                FilePath file = new FilePath(workingTree, path);
                // State of the stashed HEAD, index, and working directory
                AbstractTreeIterator stashHeadIter    = treeWalk.GetTree <AbstractTreeIterator>(0);
                AbstractTreeIterator stashIndexIter   = treeWalk.GetTree <AbstractTreeIterator>(1);
                AbstractTreeIterator stashWorkingIter = treeWalk.GetTree <AbstractTreeIterator>(2);
                if (stashWorkingIter != null && stashIndexIter != null)
                {
                    // Checkout index change
                    DirCacheEntry entry = cache.GetEntry(path);
                    if (entry == null)
                    {
                        entry = new DirCacheEntry(treeWalk.RawPath);
                    }
                    entry.FileMode = stashIndexIter.EntryFileMode;
                    entry.SetObjectId(stashIndexIter.EntryObjectId);
                    DirCacheCheckout.CheckoutEntry(repo, file, entry, treeWalk.ObjectReader);
                    DirCacheEntry updatedEntry = entry;
                    editor.Add(new _PathEdit_270(updatedEntry, path));
                    // Checkout working directory change
                    if (!stashWorkingIter.IdEqual(stashIndexIter))
                    {
                        entry = new DirCacheEntry(treeWalk.RawPath);
                        entry.SetObjectId(stashWorkingIter.EntryObjectId);
                        DirCacheCheckout.CheckoutEntry(repo, file, entry, treeWalk.ObjectReader);
                    }
                }
                else
                {
                    if (stashIndexIter == null || (stashHeadIter != null && !stashIndexIter.IdEqual(stashHeadIter
                                                                                                    )))
                    {
                        editor.Add(new DirCacheEditor.DeletePath(path));
                    }
                    FileUtils.Delete(file, FileUtils.RETRY | FileUtils.SKIP_MISSING);
                }
            }
        }
Example #6
0
        /// <summary>Checkout paths into index and working directory</summary>
        /// <returns>this instance</returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException
        ///     </exception>
        protected internal virtual NGit.Api.CheckoutCommand CheckoutPaths()
        {
            RevWalk  revWalk = new RevWalk(repo);
            DirCache dc      = repo.LockDirCache();

            try
            {
                TreeWalk treeWalk = new TreeWalk(revWalk.GetObjectReader());
                treeWalk.Recursive = true;
                treeWalk.AddTree(new DirCacheIterator(dc));
                treeWalk.Filter = PathFilterGroup.CreateFromStrings(paths);
                IList <string> files = new List <string>();
                while (treeWalk.Next())
                {
                    files.AddItem(treeWalk.PathString);
                }
                if (startCommit != null || startPoint != null)
                {
                    DirCacheEditor editor    = dc.Editor();
                    TreeWalk       startWalk = new TreeWalk(revWalk.GetObjectReader());
                    startWalk.Recursive = true;
                    startWalk.Filter    = treeWalk.Filter;
                    startWalk.AddTree(revWalk.ParseCommit(GetStartPoint()).Tree);
                    while (startWalk.Next())
                    {
                        ObjectId blobId = startWalk.GetObjectId(0);
                        editor.Add(new _PathEdit_258(blobId, startWalk.PathString));
                    }
                    editor.Commit();
                }
                FilePath workTree = repo.WorkTree;
                foreach (string file in files)
                {
                    DirCacheCheckout.CheckoutEntry(repo, new FilePath(workTree, file), dc.GetEntry(file
                                                                                                   ));
                }
            }
            finally
            {
                dc.Unlock();
                revWalk.Release();
            }
            return(this);
        }
        public static void HardReset(NGit.Repository repo, ObjectId newHead)
        {
            DirCache dc = null;

            try
            {
                // Reset head to upstream
                RefUpdate ru = repo.UpdateRef(Constants.HEAD);
                ru.SetNewObjectId(newHead);
                ru.SetForceUpdate(true);
                RefUpdate.Result rc = ru.Update();

                switch (rc)
                {
                case RefUpdate.Result.NO_CHANGE:
                case RefUpdate.Result.NEW:
                case RefUpdate.Result.FAST_FORWARD:
                case RefUpdate.Result.FORCED:
                    break;

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

                default:
                    throw new JGitInternalException("Reference update failed: " + rc);
                }

                dc = repo.LockDirCache();
                RevWalk          rw       = new RevWalk(repo);
                RevCommit        c        = rw.ParseCommit(newHead);
                DirCacheCheckout checkout = new DirCacheCheckout(repo, null, dc, c.Tree);
                checkout.Checkout();
            }
            catch
            {
                if (dc != null)
                {
                    dc.Unlock();
                }
                throw;
            }
        }
Example #8
0
 /// <exception cref="NGit.Errors.NoWorkTreeException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 private void Checkout()
 {
     foreach (KeyValuePair <string, DirCacheEntry> entry in toBeCheckedOut.EntrySet())
     {
         FilePath f = new FilePath(db.WorkTree, entry.Key);
         if (entry.Value != null)
         {
             CreateDir(f.GetParentFile());
             DirCacheCheckout.CheckoutEntry(db, f, entry.Value);
         }
         else
         {
             if (!f.Delete())
             {
                 failingPaths.Put(entry.Key, ResolveMerger.MergeFailureReason.COULD_NOT_DELETE);
             }
         }
         modifiedFiles.AddItem(entry.Key);
     }
 }
Example #9
0
        /// <exception cref="NGit.Errors.MissingObjectException"></exception>
        /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        private void Checkout(Repository clonedRepo, FetchResult result)
        {
            Ref head = result.GetAdvertisedRef(branch);

            if (branch.Equals(Constants.HEAD))
            {
                Ref foundBranch = FindBranchToCheckout(result);
                if (foundBranch != null)
                {
                    head = foundBranch;
                }
            }
            if (head == null || head.GetObjectId() == null)
            {
                return;
            }
            // throw exception?
            if (head.GetName().StartsWith(Constants.R_HEADS))
            {
                RefUpdate newHead = clonedRepo.UpdateRef(Constants.HEAD);
                newHead.DisableRefLog();
                newHead.Link(head.GetName());
                AddMergeConfig(clonedRepo, head);
            }
            RevCommit commit   = ParseCommit(clonedRepo, head);
            bool      detached = !head.GetName().StartsWith(Constants.R_HEADS);
            RefUpdate u        = clonedRepo.UpdateRef(Constants.HEAD, detached);

            u.SetNewObjectId(commit.Id);
            u.ForceUpdate();
            if (!bare)
            {
                DirCache         dc = clonedRepo.LockDirCache();
                DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc, commit.Tree);
                co.Checkout();
                if (cloneSubmodules)
                {
                    CloneSubmodules(clonedRepo);
                }
            }
        }
        public virtual void TestIsModifiedSymlink()
        {
            FilePath f   = WriteTrashFile("symlink", "content");
            Git      git = new Git(db);

            git.Add().AddFilepattern("symlink").Call();
            git.Commit().SetMessage("commit").Call();
            // Modify previously committed DirCacheEntry and write it back to disk
            DirCacheEntry dce = db.ReadDirCache().GetEntry("symlink");

            dce.FileMode = FileMode.SYMLINK;
            DirCacheCheckout.CheckoutEntry(db, f, dce);
            FileTreeIterator fti = new FileTreeIterator(trash, db.FileSystem, ((FileBasedConfig
                                                                                )db.GetConfig()).Get(WorkingTreeOptions.KEY));

            while (!fti.EntryPathString.Equals("symlink"))
            {
                fti.Next(1);
            }
            NUnit.Framework.Assert.IsFalse(fti.IsModified(dce, false));
        }
Example #11
0
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        private void CheckoutIndex(RevCommit commit)
        {
            DirCache dc = repo.LockDirCache();

            try
            {
                DirCacheCheckout checkout = new DirCacheCheckout(repo, dc, commit.Tree);
                checkout.SetFailOnConflict(false);
                try
                {
                    checkout.Checkout();
                }
                catch (NGit.Errors.CheckoutConflictException cce)
                {
                    throw new NGit.Api.Errors.CheckoutConflictException(checkout.GetConflicts(), cce);
                }
            }
            finally
            {
                dc.Unlock();
            }
        }
Example #12
0
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="NGit.Api.Errors.NoHeadException"></exception>
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        private RevCommit CheckoutCurrentHead()
        {
            ObjectId headTree = repo.Resolve(Constants.HEAD + "^{tree}");

            if (headTree == null)
            {
                throw new NoHeadException(JGitText.Get().cannotRebaseWithoutCurrentHead);
            }
            DirCache dc = repo.LockDirCache();

            try
            {
                DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
                dco.SetFailOnConflict(false);
                bool needsDeleteFiles = dco.Checkout();
                if (needsDeleteFiles)
                {
                    IList <string> fileList = dco.GetToBeDeleted();
                    foreach (string filePath in fileList)
                    {
                        FilePath fileToDelete = new FilePath(repo.WorkTree, filePath);
                        if (fileToDelete.Exists())
                        {
                            FileUtils.Delete(fileToDelete, FileUtils.RECURSIVE | FileUtils.RETRY);
                        }
                    }
                }
            }
            finally
            {
                dc.Unlock();
            }
            RevWalk   rw     = new RevWalk(repo);
            RevCommit commit = rw.ParseCommit(repo.Resolve(Constants.HEAD));

            rw.Release();
            return(commit);
        }
Example #13
0
        /// <exception cref="System.IO.IOException"></exception>
        private void CheckoutIndex(RevCommit commit)
        {
            DirCache dc = null;

            try
            {
                dc = repo.LockDirCache();
                DirCacheCheckout checkout = new DirCacheCheckout(repo, dc, commit.Tree);
                checkout.SetFailOnConflict(false);
                checkout.Checkout();
            }
            catch (IOException e)
            {
                throw;
            }
            finally
            {
                if (dc != null)
                {
                    dc.Unlock();
                }
            }
        }
Example #14
0
            public override void Apply(DirCacheEntry ent)
            {
                if (checkoutIndex && ent.Stage > DirCacheEntry.STAGE_0)
                {
                    UnmergedPathException e = new UnmergedPathException(ent);
                    throw new JGitInternalException(e.Message, e);
                }
                ent.SetObjectId(blobId);
                ent.FileMode = mode;
                FilePath file      = new FilePath(workTree, ent.PathString);
                FilePath parentDir = file.GetParentFile();

                try
                {
                    FileUtils.Mkdirs(parentDir, true);
                    DirCacheCheckout.CheckoutEntry(this._enclosing.repo, file, ent, r);
                }
                catch (IOException e)
                {
                    throw new JGitInternalException(MessageFormat.Format(JGitText.Get().checkoutConflictWithFile
                                                                         , ent.PathString), e);
                }
            }
Example #15
0
        /// <exception cref="System.IO.IOException"></exception>
        private bool CheckoutCommit(RevCommit commit)
        {
            try
            {
                RevCommit        head = walk.ParseCommit(repo.Resolve(Constants.HEAD));
                DirCacheCheckout dco  = new DirCacheCheckout(repo, head.Tree, repo.LockDirCache(),
                                                             commit.Tree);
                dco.SetFailOnConflict(true);
                dco.Checkout();
                // update the HEAD
                RefUpdate refUpdate = repo.UpdateRef(Constants.HEAD, true);
                refUpdate.SetExpectedOldObjectId(head);
                refUpdate.SetNewObjectId(commit);
                RefUpdate.Result res = refUpdate.ForceUpdate();
                switch (res)
                {
                case RefUpdate.Result.FAST_FORWARD:
                case RefUpdate.Result.NO_CHANGE:
                case RefUpdate.Result.FORCED:
                {
                    break;
                }

                default:
                {
                    throw new IOException("Could not rewind to upstream commit");
                }
                }
            }
            finally
            {
                walk.Release();
                monitor.EndTask();
            }
            return(true);
        }
Example #16
0
        /// <summary>
        /// Executes the
        /// <code>revert</code>
        /// command with all the options and parameters
        /// collected by the setter methods (e.g.
        /// <see cref="Include(NGit.Ref)">Include(NGit.Ref)</see>
        /// of this
        /// class. Each instance of this class should only be used for one invocation
        /// of the command. Don't call this method twice on an instance.
        /// </summary>
        /// <returns>
        /// on success the
        /// <see cref="NGit.Revwalk.RevCommit">NGit.Revwalk.RevCommit</see>
        /// pointed to by the new HEAD is
        /// returned. If a failure occurred during revert <code>null</code>
        /// is returned. The list of successfully reverted
        /// <see cref="NGit.Ref">NGit.Ref</see>
        /// 's can
        /// be obtained by calling
        /// <see cref="GetRevertedRefs()">GetRevertedRefs()</see>
        /// </returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        public override RevCommit Call()
        {
            RevCommit newHead = null;

            CheckCallable();
            RevWalk revWalk = new RevWalk(repo);

            try
            {
                // get the head commit
                Ref headRef = repo.GetRef(Constants.HEAD);
                if (headRef == null)
                {
                    throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported
                                              );
                }
                RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId());
                newHead = headCommit;
                // loop through all refs to be reverted
                foreach (Ref src in commits)
                {
                    // get the commit to be reverted
                    // handle annotated tags
                    ObjectId srcObjectId = src.GetPeeledObjectId();
                    if (srcObjectId == null)
                    {
                        srcObjectId = src.GetObjectId();
                    }
                    RevCommit srcCommit = revWalk.ParseCommit(srcObjectId);
                    // get the parent of the commit to revert
                    if (srcCommit.ParentCount != 1)
                    {
                        throw new MultipleParentsNotAllowedException(JGitText.Get().canOnlyRevertCommitsWithOneParent
                                                                     );
                    }
                    RevCommit srcParent = srcCommit.GetParent(0);
                    revWalk.ParseHeaders(srcParent);
                    ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger
                                                               (repo));
                    merger.SetWorkingTreeIterator(new FileTreeIterator(repo));
                    merger.SetBase(srcCommit.Tree);
                    if (merger.Merge(headCommit, srcParent))
                    {
                        if (AnyObjectId.Equals(headCommit.Tree.Id, merger.GetResultTreeId()))
                        {
                            continue;
                        }
                        DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache
                                                                        (), merger.GetResultTreeId());
                        dco.SetFailOnConflict(true);
                        dco.Checkout();
                        string newMessage = "Revert \"" + srcCommit.GetShortMessage() + "\"" + "\n\n" + "This reverts commit "
                                            + srcCommit.Id.GetName() + "\n";
                        newHead = new Git(GetRepository()).Commit().SetMessage(newMessage).Call();
                        revertedRefs.AddItem(src);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (IOException e)
            {
                throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionCaughtDuringExecutionOfRevertCommand
                                                                     , e), e);
            }
            finally
            {
                revWalk.Release();
            }
            return(newHead);
        }
Example #17
0
        public static MergeCommandResult MergeTrees(ProgressMonitor monitor, NGit.Repository repo, RevCommit srcBase, RevCommit srcCommit, string sourceDisplayName, bool commitResult)
        {
            RevCommit newHead;
            RevWalk   revWalk = new RevWalk(repo);

            try
            {
                // get the head commit
                Ref headRef = repo.GetRef(Constants.HEAD);
                if (headRef == null)
                {
                    throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported
                                              );
                }
                RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId());

                ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger
                                                           (repo));

                merger.SetWorkingTreeIterator(new FileTreeIterator(repo));

                merger.SetBase(srcBase);

                bool noProblems;
                IDictionary <string, MergeResult <Sequence> >          lowLevelResults = null;
                IDictionary <string, ResolveMerger.MergeFailureReason> failingPaths    = null;
                IList <string> modifiedFiles = null;

                ResolveMerger resolveMerger = merger;
                resolveMerger.SetCommitNames(new string[] { "BASE", "HEAD", sourceDisplayName });
                noProblems      = merger.Merge(headCommit, srcCommit);
                lowLevelResults = resolveMerger.GetMergeResults();
                modifiedFiles   = resolveMerger.GetModifiedFiles();
                failingPaths    = resolveMerger.GetFailingPaths();

                if (monitor != null)
                {
                    monitor.Update(50);
                }

                if (noProblems)
                {
                    if (modifiedFiles != null && modifiedFiles.Count == 0)
                    {
                        return(new MergeCommandResult(headCommit, null, new ObjectId[] { headCommit.Id, srcCommit
                                                                                         .Id }, MergeStatus.ALREADY_UP_TO_DATE, MergeStrategy.RESOLVE, null, null));
                    }
                    DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache
                                                                    (), merger.GetResultTreeId());
                    dco.SetFailOnConflict(true);
                    dco.Checkout();
                    if (commitResult)
                    {
                        newHead = new NGit.Api.Git(repo).Commit().SetMessage(srcCommit.GetFullMessage()
                                                                             ).SetAuthor(srcCommit.GetAuthorIdent()).Call();
                        return(new MergeCommandResult(newHead.Id, null, new ObjectId[] { headCommit.Id, srcCommit
                                                                                         .Id }, MergeStatus.MERGED, MergeStrategy.RESOLVE, null, null));
                    }
                    else
                    {
                        return(new MergeCommandResult(headCommit, null, new ObjectId[] { headCommit.Id, srcCommit
                                                                                         .Id }, MergeStatus.MERGED, MergeStrategy.RESOLVE, null, null));
                    }
                }
                else
                {
                    if (failingPaths != null)
                    {
                        return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] {
                            headCommit.Id, srcCommit.Id
                        }, MergeStatus.FAILED, MergeStrategy.RESOLVE, lowLevelResults
                                                      , failingPaths, null));
                    }
                    else
                    {
                        return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] {
                            headCommit.Id, srcCommit.Id
                        }, MergeStatus.CONFLICTING, MergeStrategy.RESOLVE, lowLevelResults
                                                      , null));
                    }
                }
            }
            finally
            {
                revWalk.Release();
            }
        }
Example #18
0
        public static void Checkout(NGit.Repository repo, RevCommit commit, string working_directory)
        {
            DirCacheCheckout co = new DirCacheCheckout(repo, null, repo.ReadDirCache(), commit.Tree);

            co.Checkout();
        }
Example #19
0
        /// <exception cref="NGit.Api.Errors.RefAlreadyExistsException">
        /// when trying to create (without force) a branch with a name
        /// that already exists
        /// </exception>
        /// <exception cref="NGit.Api.Errors.RefNotFoundException">if the start point or branch can not be found
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.InvalidRefNameException">
        /// if the provided name is <code>null</code> or otherwise
        /// invalid
        /// </exception>
        /// <returns>the newly created branch</returns>
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        public override Ref Call()
        {
            CheckCallable();
            ProcessOptions();
            try
            {
                if (createBranch)
                {
                    Git git = new Git(repo);
                    CreateBranchCommand command = git.BranchCreate();
                    command.SetName(name);
                    command.SetStartPoint(GetStartPoint().Name);
                    if (upstreamMode != null)
                    {
                        command.SetUpstreamMode(upstreamMode);
                    }
                    command.Call();
                }
                Ref      headRef       = repo.GetRef(Constants.HEAD);
                string   refLogMessage = "checkout: moving from " + headRef.GetTarget().GetName();
                ObjectId branch        = repo.Resolve(name);
                if (branch == null)
                {
                    throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved
                                                                        , name));
                }
                RevWalk          revWalk    = new RevWalk(repo);
                AnyObjectId      headId     = headRef.GetObjectId();
                RevCommit        headCommit = headId == null ? null : revWalk.ParseCommit(headId);
                RevCommit        newCommit  = revWalk.ParseCommit(branch);
                RevTree          headTree   = headCommit == null ? null : headCommit.Tree;
                DirCacheCheckout dco        = new DirCacheCheckout(repo, headTree, repo.LockDirCache(),
                                                                   newCommit.Tree);
                dco.SetFailOnConflict(true);
                try
                {
                    dco.Checkout();
                }
                catch (NGit.Errors.CheckoutConflictException e)
                {
                    status = new CheckoutResult(CheckoutResult.Status.CONFLICTS, dco.GetConflicts());
                    throw;
                }
                Ref @ref = repo.GetRef(name);
                if (@ref != null && [email protected]().StartsWith(Constants.R_HEADS))
                {
                    @ref = null;
                }
                RefUpdate refUpdate = repo.UpdateRef(Constants.HEAD, @ref == null);
                refUpdate.SetForceUpdate(force);
                refUpdate.SetRefLogMessage(refLogMessage + " to " + newCommit.GetName(), false);
                RefUpdate.Result updateResult;
                if (@ref != null)
                {
                    updateResult = refUpdate.Link(@ref.GetName());
                }
                else
                {
                    refUpdate.SetNewObjectId(newCommit);
                    updateResult = refUpdate.ForceUpdate();
                }
                SetCallable(false);
                bool ok = false;
                switch (updateResult)
                {
                case RefUpdate.Result.NEW:
                {
                    ok = true;
                    break;
                }

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

                default:
                {
                    break;
                    break;
                }
                }
                if (!ok)
                {
                    throw new JGitInternalException(MessageFormat.Format(JGitText.Get().checkoutUnexpectedResult
                                                                         , updateResult.ToString()));
                }
                if (!dco.GetToBeDeleted().IsEmpty())
                {
                    status = new CheckoutResult(CheckoutResult.Status.NONDELETED, dco.GetToBeDeleted(
                                                    ));
                }
                else
                {
                    status = CheckoutResult.OK_RESULT;
                }
                return(@ref);
            }
            catch (IOException ioe)
            {
                throw new JGitInternalException(ioe.Message, ioe);
            }
            finally
            {
                if (status == null)
                {
                    status = CheckoutResult.ERROR_RESULT;
                }
            }
        }
Example #20
0
        /// <summary>
        /// Executes the
        /// <code>Merge</code>
        /// command with all the options and parameters
        /// collected by the setter methods (e.g.
        /// <see cref="Include(NGit.Ref)">Include(NGit.Ref)</see>
        /// ) of this
        /// class. Each instance of this class should only be used for one invocation
        /// of the command. Don't call this method twice on an instance.
        /// </summary>
        /// <returns>the result of the merge</returns>
        /// <exception cref="NGit.Api.Errors.NoHeadException"></exception>
        /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException"></exception>
        /// <exception cref="NGit.Api.Errors.CheckoutConflictException"></exception>
        /// <exception cref="NGit.Api.Errors.InvalidMergeHeadsException"></exception>
        /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException"></exception>
        /// <exception cref="NGit.Api.Errors.NoMessageException"></exception>
        public override MergeCommandResult Call()
        {
            CheckCallable();
            if (commits.Count != 1)
            {
                throw new InvalidMergeHeadsException(commits.IsEmpty() ? JGitText.Get().noMergeHeadSpecified
                                         : MessageFormat.Format(JGitText.Get().mergeStrategyDoesNotSupportHeads, mergeStrategy
                                                                .GetName(), Sharpen.Extensions.ValueOf(commits.Count)));
            }
            RevWalk revWalk = null;

            try
            {
                Ref head = repo.GetRef(Constants.HEAD);
                if (head == null)
                {
                    throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported
                                              );
                }
                StringBuilder refLogMessage = new StringBuilder("merge ");
                // Check for FAST_FORWARD, ALREADY_UP_TO_DATE
                revWalk = new RevWalk(repo);
                // we know for now there is only one commit
                Ref @ref = commits[0];
                refLogMessage.Append(@ref.GetName());
                // handle annotated tags
                ObjectId objectId = @ref.GetPeeledObjectId();
                if (objectId == null)
                {
                    objectId = @ref.GetObjectId();
                }
                RevCommit srcCommit = revWalk.LookupCommit(objectId);
                ObjectId  headId    = head.GetObjectId();
                if (headId == null)
                {
                    revWalk.ParseHeaders(srcCommit);
                    DirCacheCheckout dco = new DirCacheCheckout(repo, repo.LockDirCache(), srcCommit.
                                                                Tree);
                    dco.SetFailOnConflict(true);
                    dco.Checkout();
                    RefUpdate refUpdate = repo.UpdateRef(head.GetTarget().GetName());
                    refUpdate.SetNewObjectId(objectId);
                    refUpdate.SetExpectedOldObjectId(null);
                    refUpdate.SetRefLogMessage("initial pull", false);
                    if (refUpdate.Update() != RefUpdate.Result.NEW)
                    {
                        throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported
                                                  );
                    }
                    SetCallable(false);
                    return(new MergeCommandResult(srcCommit, srcCommit, new ObjectId[] { null, srcCommit }, MergeStatus.FAST_FORWARD, mergeStrategy, null, null));
                }
                RevCommit headCommit = revWalk.LookupCommit(headId);
                if (revWalk.IsMergedInto(srcCommit, headCommit))
                {
                    SetCallable(false);
                    return(new MergeCommandResult(headCommit, srcCommit, new ObjectId[] { headCommit,
                                                                                          srcCommit }, MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null, null));
                }
                else
                {
                    if (revWalk.IsMergedInto(headCommit, srcCommit))
                    {
                        // FAST_FORWARD detected: skip doing a real merge but only
                        // update HEAD
                        refLogMessage.Append(": " + MergeStatus.FAST_FORWARD);
                        DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache
                                                                        (), srcCommit.Tree);
                        dco.SetFailOnConflict(true);
                        dco.Checkout();
                        UpdateHead(refLogMessage, srcCommit, headId);
                        SetCallable(false);
                        return(new MergeCommandResult(srcCommit, srcCommit, new ObjectId[] { headCommit,
                                                                                             srcCommit }, MergeStatus.FAST_FORWARD, mergeStrategy, null, null));
                    }
                    else
                    {
                        repo.WriteMergeCommitMsg(new MergeMessageFormatter().Format(commits, head));
                        repo.WriteMergeHeads(Arrays.AsList(@ref.GetObjectId()));
                        ThreeWayMerger merger = (ThreeWayMerger)mergeStrategy.NewMerger(repo);
                        bool           noProblems;
                        IDictionary <string, MergeResult <NGit.Diff.Sequence> > lowLevelResults = null;
                        IDictionary <string, ResolveMerger.MergeFailureReason>  failingPaths    = null;
                        if (merger is ResolveMerger)
                        {
                            ResolveMerger resolveMerger = (ResolveMerger)merger;
                            resolveMerger.SetCommitNames(new string[] { "BASE", "HEAD", @ref.GetName() });
                            resolveMerger.SetWorkingTreeIterator(new FileTreeIterator(repo));
                            noProblems      = merger.Merge(headCommit, srcCommit);
                            lowLevelResults = resolveMerger.GetMergeResults();
                            failingPaths    = resolveMerger.GetFailingPaths();
                        }
                        else
                        {
                            noProblems = merger.Merge(headCommit, srcCommit);
                        }
                        if (noProblems)
                        {
                            DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache
                                                                            (), merger.GetResultTreeId());
                            dco.SetFailOnConflict(true);
                            dco.Checkout();
                            RevCommit newHead = new Git(GetRepository()).Commit().Call();
                            return(new MergeCommandResult(newHead.Id, null, new ObjectId[] { headCommit.Id, srcCommit
                                                                                             .Id }, MergeStatus.MERGED, mergeStrategy, null, null));
                        }
                        else
                        {
                            if (failingPaths != null)
                            {
                                repo.WriteMergeCommitMsg(null);
                                repo.WriteMergeHeads(null);
                                return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] {
                                    headCommit.Id, srcCommit.Id
                                }, MergeStatus.FAILED, mergeStrategy, lowLevelResults
                                                              , null));
                            }
                            else
                            {
                                return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] {
                                    headCommit.Id, srcCommit.Id
                                }, MergeStatus.CONFLICTING, mergeStrategy, lowLevelResults
                                                              , null));
                            }
                        }
                    }
                }
            }
            catch (IOException e)
            {
                throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionCaughtDuringExecutionOfMergeCommand
                                                                     , e), e);
            }
            finally
            {
                if (revWalk != null)
                {
                    revWalk.Release();
                }
            }
        }
Example #21
0
        /// <exception cref="System.IO.IOException"></exception>
        private RebaseResult Abort(RebaseResult result)
        {
            try
            {
                string commitId = ReadFile(repo.Directory, Constants.ORIG_HEAD);
                monitor.BeginTask(MessageFormat.Format(JGitText.Get().abortingRebase, commitId),
                                  ProgressMonitor.UNKNOWN);
                DirCacheCheckout dco;
                RevCommit        commit = walk.ParseCommit(repo.Resolve(commitId));
                if (result.GetStatus().Equals(RebaseResult.Status.FAILED))
                {
                    RevCommit head = walk.ParseCommit(repo.Resolve(Constants.HEAD));
                    dco = new DirCacheCheckout(repo, head.Tree, repo.LockDirCache(), commit.Tree);
                }
                else
                {
                    dco = new DirCacheCheckout(repo, repo.LockDirCache(), commit.Tree);
                }
                dco.SetFailOnConflict(false);
                dco.Checkout();
                walk.Release();
            }
            finally
            {
                monitor.EndTask();
            }
            try
            {
                string headName = ReadFile(rebaseDir, HEAD_NAME);
                if (headName.StartsWith(Constants.R_REFS))
                {
                    monitor.BeginTask(MessageFormat.Format(JGitText.Get().resettingHead, headName), ProgressMonitor
                                      .UNKNOWN);
                    // update the HEAD
                    RefUpdate        refUpdate = repo.UpdateRef(Constants.HEAD, false);
                    RefUpdate.Result res       = refUpdate.Link(headName);
                    switch (res)
                    {
                    case RefUpdate.Result.FAST_FORWARD:
                    case RefUpdate.Result.FORCED:
                    case RefUpdate.Result.NO_CHANGE:
                    {
                        break;
                    }

                    default:
                    {
                        throw new JGitInternalException(JGitText.Get().abortingRebaseFailed);
                    }
                    }
                }
                // cleanup the files
                FileUtils.Delete(rebaseDir, FileUtils.RECURSIVE);
                repo.WriteCherryPickHead(null);
                return(result);
            }
            finally
            {
                monitor.EndTask();
            }
        }
Example #22
0
 /// <summary>Execute the SubmoduleUpdateCommand command.</summary>
 /// <remarks>Execute the SubmoduleUpdateCommand command.</remarks>
 /// <returns>a collection of updated submodule paths</returns>
 /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException">NGit.Api.Errors.ConcurrentRefUpdateException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.CheckoutConflictException">NGit.Api.Errors.CheckoutConflictException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.InvalidMergeHeadsException">NGit.Api.Errors.InvalidMergeHeadsException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.InvalidConfigurationException">NGit.Api.Errors.InvalidConfigurationException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.NoHeadException">NGit.Api.Errors.NoHeadException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.NoMessageException">NGit.Api.Errors.NoMessageException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">NGit.Api.Errors.WrongRepositoryStateException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException
 ///     </exception>
 public override ICollection <string> Call()
 {
     CheckCallable();
     try
     {
         SubmoduleWalk generator = SubmoduleWalk.ForIndex(repo);
         if (!paths.IsEmpty())
         {
             generator.SetFilter(PathFilterGroup.CreateFromStrings(paths));
         }
         IList <string> updated = new AList <string>();
         while (generator.Next())
         {
             // Skip submodules not registered in .gitmodules file
             if (generator.GetModulesPath() == null)
             {
                 continue;
             }
             // Skip submodules not registered in parent repository's config
             string url = generator.GetConfigUrl();
             if (url == null)
             {
                 continue;
             }
             Repository submoduleRepo = generator.GetRepository();
             // Clone repository is not present
             if (submoduleRepo == null)
             {
                 CloneCommand clone = Git.CloneRepository();
                 Configure(clone);
                 clone.SetURI(url);
                 clone.SetDirectory(generator.GetDirectory());
                 if (monitor != null)
                 {
                     clone.SetProgressMonitor(monitor);
                 }
                 submoduleRepo = clone.Call().GetRepository();
             }
             try
             {
                 RevWalk   walk   = new RevWalk(submoduleRepo);
                 RevCommit commit = walk.ParseCommit(generator.GetObjectId());
                 string    update = generator.GetConfigUpdate();
                 if (ConfigConstants.CONFIG_KEY_MERGE.Equals(update))
                 {
                     MergeCommand merge = new MergeCommand(submoduleRepo);
                     merge.Include(commit);
                     merge.Call();
                 }
                 else
                 {
                     if (ConfigConstants.CONFIG_KEY_REBASE.Equals(update))
                     {
                         RebaseCommand rebase = new RebaseCommand(submoduleRepo);
                         rebase.SetUpstream(commit);
                         rebase.Call();
                     }
                     else
                     {
                         // Checkout commit referenced in parent repository's
                         // index as a detached HEAD
                         DirCacheCheckout co = new DirCacheCheckout(submoduleRepo, submoduleRepo.LockDirCache
                                                                        (), commit.Tree);
                         co.SetFailOnConflict(true);
                         co.Checkout();
                         RefUpdate refUpdate = submoduleRepo.UpdateRef(Constants.HEAD, true);
                         refUpdate.SetNewObjectId(commit);
                         refUpdate.ForceUpdate();
                     }
                 }
             }
             finally
             {
                 submoduleRepo.Close();
             }
             updated.AddItem(generator.GetPath());
         }
         return(updated);
     }
     catch (IOException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
     catch (ConfigInvalidException e)
     {
         throw new InvalidConfigurationException(e.Message, e);
     }
 }
Example #23
0
        /// <summary>
        /// Executes the
        /// <code>Cherry-Pick</code>
        /// command with all the options and
        /// parameters collected by the setter methods (e.g.
        /// <see cref="Include(NGit.Ref)">Include(NGit.Ref)</see>
        /// of
        /// this class. Each instance of this class should only be used for one
        /// invocation of the command. Don't call this method twice on an instance.
        /// </summary>
        /// <returns>the result of the cherry-pick</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        public override CherryPickResult Call()
        {
            RevCommit   newHead          = null;
            IList <Ref> cherryPickedRefs = new List <Ref>();

            CheckCallable();
            RevWalk revWalk = new RevWalk(repo);

            try
            {
                // get the head commit
                Ref headRef = repo.GetRef(Constants.HEAD);
                if (headRef == null)
                {
                    throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported
                                              );
                }
                RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId());
                newHead = headCommit;
                // loop through all refs to be cherry-picked
                foreach (Ref src in commits)
                {
                    // get the commit to be cherry-picked
                    // handle annotated tags
                    ObjectId srcObjectId = src.GetPeeledObjectId();
                    if (srcObjectId == null)
                    {
                        srcObjectId = src.GetObjectId();
                    }
                    RevCommit srcCommit = revWalk.ParseCommit(srcObjectId);
                    // get the parent of the commit to cherry-pick
                    if (srcCommit.ParentCount != 1)
                    {
                        throw new MultipleParentsNotAllowedException(JGitText.Get().canOnlyCherryPickCommitsWithOneParent
                                                                     );
                    }
                    RevCommit srcParent = srcCommit.GetParent(0);
                    revWalk.ParseHeaders(srcParent);
                    ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger
                                                               (repo));
                    merger.SetWorkingTreeIterator(new FileTreeIterator(repo));
                    merger.SetBase(srcParent.Tree);
                    if (merger.Merge(headCommit, srcCommit))
                    {
                        if (AnyObjectId.Equals(headCommit.Tree.Id, merger.GetResultTreeId()))
                        {
                            continue;
                        }
                        DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache
                                                                        (), merger.GetResultTreeId());
                        dco.SetFailOnConflict(true);
                        dco.Checkout();
                        newHead = new Git(GetRepository()).Commit().SetMessage(srcCommit.GetFullMessage()
                                                                               ).SetAuthor(srcCommit.GetAuthorIdent()).Call();
                        cherryPickedRefs.AddItem(src);
                    }
                    else
                    {
                        if (merger.Failed())
                        {
                            return(new CherryPickResult(merger.GetFailingPaths()));
                        }
                        // there are merge conflicts
                        string message = new MergeMessageFormatter().FormatWithConflicts(srcCommit.GetFullMessage
                                                                                             (), merger.GetUnmergedPaths());
                        repo.WriteCherryPickHead(srcCommit.Id);
                        repo.WriteMergeCommitMsg(message);
                        return(CherryPickResult.CONFLICT);
                    }
                }
            }
            catch (IOException e)
            {
                throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionCaughtDuringExecutionOfCherryPickCommand
                                                                     , e), e);
            }
            finally
            {
                revWalk.Release();
            }
            return(new CherryPickResult(newHead, cherryPickedRefs));
        }