Пример #1
0
        /// <returns>the requested notes</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        public override IList <Note> Call()
        {
            CheckCallable();
            IList <Note> notes = new AList <Note>();
            RevWalk      walk  = new RevWalk(repo);
            NoteMap      map   = NoteMap.NewEmptyMap();

            try
            {
                Ref @ref = repo.GetRef(notesRef);
                // if we have a notes ref, use it
                if (@ref != null)
                {
                    RevCommit notesCommit = walk.ParseCommit(@ref.GetObjectId());
                    map = NoteMap.Read(walk.GetObjectReader(), notesCommit);
                }
                Iterator <Note> i = map.Iterator();
                while (i.HasNext())
                {
                    notes.AddItem(i.Next());
                }
            }
            catch (IOException e)
            {
                throw new JGitInternalException(e.Message, e);
            }
            finally
            {
                walk.Release();
            }
            return(notes);
        }
Пример #2
0
        /// <exception cref="NGit.Api.Errors.JGitInternalException">upon internal failure</exception>
        public override Note Call()
        {
            CheckCallable();
            RevWalk        walk        = new RevWalk(repo);
            ObjectInserter inserter    = repo.NewObjectInserter();
            NoteMap        map         = NoteMap.NewEmptyMap();
            RevCommit      notesCommit = null;

            try
            {
                Ref @ref = repo.GetRef(notesRef);
                // if we have a notes ref, use it
                if (@ref != null)
                {
                    notesCommit = walk.ParseCommit(@ref.GetObjectId());
                    map         = NoteMap.Read(walk.GetObjectReader(), notesCommit);
                }
                map.Set(id, null, inserter);
                CommitNoteMap(walk, map, notesCommit, inserter, "Notes removed by 'git notes remove'"
                              );
                return(map.GetNote(id));
            }
            catch (IOException e)
            {
                throw new JGitInternalException(e.Message, e);
            }
            finally
            {
                inserter.Release();
                walk.Release();
            }
        }
Пример #3
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);
        }
Пример #4
0
        public ActionResult FileDiff(string path, string fromSha1, string toSha1)
        {
            var nGit = TM_UserData_Git.Current.NGit;

            Func <Repository, string, string, string, string> getDiff =
                (gitRepo, repoPath, fromCommitId, toCommitId) =>
            {
                var fromCommit = gitRepo.Resolve(fromCommitId);
                var toCommit   = gitRepo.Resolve(toCommitId);

                var outputStream = "Sharpen.dll".assembly().type("ByteArrayOutputStream").ctor(new object[0]).cast <OutputStream>();
                //return "diffing from {0} to  {1}".format(fromCommit, toCommit);
                var diffFormater = new DiffFormatter(outputStream);
                var pathFilter   = PathFilter.Create(repoPath);
                diffFormater.SetRepository(gitRepo);
                diffFormater.SetPathFilter(pathFilter);
                //diffFormater.Format(refLog.GetNewId(), refLog.GetOldId());
                diffFormater.Format(fromCommit, toCommit);
                return("result: " + outputStream.str());
            };

            Func <Repository, string, string, string> getFistValue =
                (gitRepo, commitSha1, repoPath) =>
            {
                var revCommit    = nGit.commit(commitSha1);
                var outputStream = "Sharpen.dll".assembly().type("ByteArrayOutputStream").ctor(new object[0]).cast <OutputStream>();
                var diffFormater = new DiffFormatter(outputStream);
                var pathFilter   = PathFilter.Create(repoPath);
                diffFormater.SetRepository(gitRepo);
                diffFormater.SetPathFilter(pathFilter);

                var revWalk             = new RevWalk(gitRepo);
                var canonicalTreeParser = new CanonicalTreeParser(null, revWalk.GetObjectReader(), revCommit.Tree);
                diffFormater.Format(new EmptyTreeIterator(), canonicalTreeParser);
                return(outputStream.str().fix_CRLF());
            };

            var rawDiff = fromSha1 == NGit_Consts.EMPTY_SHA1
                            ? getFistValue(nGit.repository(), fromSha1, path)
                            :  getDiff(nGit.repository(), path, fromSha1, toSha1);


            var viewFile = new View_GitFileDiff()
            {
                FilePath = path,
                FromSha1 = fromSha1,
                ToSha1   = toSha1,
                Diff     = rawDiff
            };

            return(View(viewFile));
        }
Пример #5
0
        public ActionResult FileDiff(string path, string fromSha1,string toSha1)
        {
            var nGit = TM_UserData_Git.Current.NGit;

            Func<Repository, string, string, string, string> getDiff =
                (gitRepo, repoPath, fromCommitId, toCommitId) =>
                    {

                        var fromCommit = gitRepo.Resolve(fromCommitId);
                        var toCommit = gitRepo.Resolve(toCommitId);

                        var outputStream = "Sharpen.dll".assembly().type("ByteArrayOutputStream").ctor(new object[0]).cast<OutputStream>();
                        //return "diffing from {0} to  {1}".format(fromCommit, toCommit);
                        var diffFormater = new DiffFormatter(outputStream);
                        var pathFilter = PathFilter.Create(repoPath);
                        diffFormater.SetRepository(gitRepo);
                        diffFormater.SetPathFilter(pathFilter);
                        //diffFormater.Format(refLog.GetNewId(), refLog.GetOldId());
                        diffFormater.Format(fromCommit, toCommit);
                        return "result: " + outputStream.str();
                    };

            Func<Repository, string, string, string> getFistValue =
                (gitRepo, commitSha1, repoPath) =>
                    {
                        var revCommit = nGit.commit(commitSha1);
                        var outputStream = "Sharpen.dll".assembly().type("ByteArrayOutputStream").ctor(new object[0]).cast<OutputStream>();
                        var diffFormater = new DiffFormatter(outputStream);
                        var pathFilter = PathFilter.Create(repoPath);
                        diffFormater.SetRepository(gitRepo);
                        diffFormater.SetPathFilter(pathFilter);

                        var revWalk = new RevWalk(gitRepo);
                        var canonicalTreeParser = new CanonicalTreeParser(null, revWalk.GetObjectReader(), revCommit.Tree);
                        diffFormater.Format(new EmptyTreeIterator(), canonicalTreeParser);
                        return outputStream.str().fix_CRLF();
                    };

            var rawDiff = fromSha1 == NGit_Consts.EMPTY_SHA1
                            ? getFistValue(nGit.repository(), fromSha1, path)
                            :  getDiff(nGit.repository(), path, fromSha1, toSha1);

            var viewFile = new View_GitFileDiff()
                {
                    FilePath = path,
                    FromSha1 = fromSha1,
                    ToSha1 = toSha1,
                    Diff = rawDiff
                };
            return View(viewFile);
        }
Пример #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
            {
                DirCacheEditor editor    = dc.Editor();
                TreeWalk       startWalk = new TreeWalk(revWalk.GetObjectReader());
                startWalk.Recursive = true;
                if (!checkoutAllPaths)
                {
                    startWalk.Filter = PathFilterGroup.CreateFromStrings(paths);
                }
                bool checkoutIndex = startCommit == null && startPoint == null;
                if (!checkoutIndex)
                {
                    startWalk.AddTree(revWalk.ParseCommit(GetStartPoint()).Tree);
                }
                else
                {
                    startWalk.AddTree(new DirCacheIterator(dc));
                }
                FilePath     workTree = repo.WorkTree;
                ObjectReader r        = repo.ObjectDatabase.NewReader();
                try
                {
                    while (startWalk.Next())
                    {
                        ObjectId blobId = startWalk.GetObjectId(0);
                        FileMode mode   = startWalk.GetFileMode(0);
                        editor.Add(new _PathEdit_349(this, checkoutIndex, blobId, mode, workTree, r, startWalk
                                                     .PathString));
                    }
                    editor.Commit();
                }
                finally
                {
                    startWalk.Release();
                    r.Release();
                }
            }
            finally
            {
                dc.Unlock();
                revWalk.Release();
            }
            return(this);
        }
Пример #7
0
 private void InitRevPool(bool reverse)
 {
     if (queue != null)
     {
         throw new InvalidOperationException();
     }
     if (revPool != null)
     {
         revPool.Release();
     }
     if (reverse)
     {
         revPool = new ReverseWalk(GetRepository());
     }
     else
     {
         revPool = new RevWalk(GetRepository());
     }
     revPool.SetRetainBody(true);
     SEEN     = revPool.NewFlag("SEEN");
     reader   = revPool.GetObjectReader();
     treeWalk = new TreeWalk(reader);
 }
Пример #8
0
        /// <exception cref="NGit.Api.Errors.RefNotFoundException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="NGit.Api.Errors.NoHeadException"></exception>
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        private RebaseResult InitFilesAndRewind()
        {
            // we need to store everything into files so that we can implement
            // --skip, --continue, and --abort
            // first of all, we determine the commits to be applied
            IList <RevCommit> cherryPickList = new AList <RevCommit>();
            Ref head = repo.GetRef(Constants.HEAD);

            if (head == null || head.GetObjectId() == null)
            {
                throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved
                                                                    , Constants.HEAD));
            }
            string headName;

            if (head.IsSymbolic())
            {
                headName = head.GetTarget().GetName();
            }
            else
            {
                headName = "detached HEAD";
            }
            ObjectId headId = head.GetObjectId();

            if (headId == null)
            {
                throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved
                                                                    , Constants.HEAD));
            }
            RevCommit headCommit = walk.LookupCommit(headId);

            monitor.BeginTask(JGitText.Get().obtainingCommitsForCherryPick, ProgressMonitor.UNKNOWN
                              );
            LogCommand           cmd          = new Git(repo).Log().AddRange(upstreamCommit, headCommit);
            Iterable <RevCommit> commitsToUse = cmd.Call();

            foreach (RevCommit commit in commitsToUse)
            {
                cherryPickList.AddItem(commit);
            }
            // if the upstream commit is in a direct line to the current head,
            // the log command will not report any commits; in this case,
            // we create the cherry-pick list ourselves
            if (cherryPickList.IsEmpty())
            {
                Iterable <RevCommit> parents = new Git(repo).Log().Add(upstreamCommit).Call();
                foreach (RevCommit parent in parents)
                {
                    if (parent.Equals(headCommit))
                    {
                        break;
                    }
                    if (parent.ParentCount != 1)
                    {
                        throw new JGitInternalException(JGitText.Get().canOnlyCherryPickCommitsWithOneParent
                                                        );
                    }
                    cherryPickList.AddItem(parent);
                }
            }
            // nothing to do: return with UP_TO_DATE_RESULT
            if (cherryPickList.IsEmpty())
            {
                return(RebaseResult.UP_TO_DATE_RESULT);
            }
            Sharpen.Collections.Reverse(cherryPickList);
            // create the folder for the meta information
            FileUtils.Mkdir(rebaseDir);
            CreateFile(repo.Directory, Constants.ORIG_HEAD, headId.Name);
            CreateFile(rebaseDir, REBASE_HEAD, headId.Name);
            CreateFile(rebaseDir, HEAD_NAME, headName);
            CreateFile(rebaseDir, ONTO, upstreamCommit.Name);
            CreateFile(rebaseDir, INTERACTIVE, string.Empty);
            BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream
                                                                              (new FilePath(rebaseDir, GIT_REBASE_TODO)), Constants.CHARACTER_ENCODING));

            fw.Write("# Created by EGit: rebasing " + upstreamCommit.Name + " onto " + headId
                     .Name);
            fw.NewLine();
            try
            {
                StringBuilder sb     = new StringBuilder();
                ObjectReader  reader = walk.GetObjectReader();
                foreach (RevCommit commit_1 in cherryPickList)
                {
                    sb.Length = 0;
                    sb.Append(RebaseCommand.Action.PICK.ToToken());
                    sb.Append(" ");
                    sb.Append(reader.Abbreviate(commit_1).Name);
                    sb.Append(" ");
                    sb.Append(commit_1.GetShortMessage());
                    fw.Write(sb.ToString());
                    fw.NewLine();
                }
            }
            finally
            {
                fw.Close();
            }
            monitor.EndTask();
            // we rewind to the upstream commit
            monitor.BeginTask(MessageFormat.Format(JGitText.Get().rewinding, upstreamCommit.GetShortMessage
                                                       ()), ProgressMonitor.UNKNOWN);
            CheckoutCommit(upstreamCommit);
            monitor.EndTask();
            return(null);
        }
Пример #9
0
        /// <exception cref="System.IO.IOException"></exception>
        private void SendPack()
        {
            bool sideband = options.Contains(OPTION_SIDE_BAND) || options.Contains(OPTION_SIDE_BAND_64K
                                                                                   );
            ProgressMonitor      pm      = NullProgressMonitor.INSTANCE;
            OutputStream         packOut = rawOut;
            SideBandOutputStream msgOut  = null;

            if (sideband)
            {
                int bufsz = SideBandOutputStream.SMALL_BUF;
                if (options.Contains(OPTION_SIDE_BAND_64K))
                {
                    bufsz = SideBandOutputStream.MAX_BUF;
                }
                packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA, bufsz, rawOut);
                if (!options.Contains(OPTION_NO_PROGRESS))
                {
                    msgOut = new SideBandOutputStream(SideBandOutputStream.CH_PROGRESS, bufsz, rawOut
                                                      );
                    pm = new SideBandProgressMonitor(msgOut);
                }
            }
            PackConfig cfg = packConfig;

            if (cfg == null)
            {
                cfg = new PackConfig(db);
            }
            PackWriter pw = new PackWriter(cfg, walk.GetObjectReader());

            try
            {
                pw.SetUseCachedPacks(true);
                pw.SetReuseDeltaCommits(true);
                pw.SetDeltaBaseAsOffset(options.Contains(OPTION_OFS_DELTA));
                pw.SetThin(options.Contains(OPTION_THIN_PACK));
                pw.SetReuseValidatingObjects(false);
                if (commonBase.IsEmpty())
                {
                    ICollection <ObjectId> tagTargets = new HashSet <ObjectId>();
                    foreach (Ref @ref in refs.Values)
                    {
                        if (@ref.GetPeeledObjectId() != null)
                        {
                            tagTargets.AddItem(@ref.GetPeeledObjectId());
                        }
                        else
                        {
                            if (@ref.GetObjectId() == null)
                            {
                                continue;
                            }
                            else
                            {
                                if (@ref.GetName().StartsWith(Constants.R_HEADS))
                                {
                                    tagTargets.AddItem(@ref.GetObjectId());
                                }
                            }
                        }
                    }
                    pw.SetTagTargets(tagTargets);
                }
                RevWalk rw = walk;
                if (wantAll.IsEmpty())
                {
                    pw.PreparePack(pm, wantIds, commonBase);
                }
                else
                {
                    walk.Reset();
                    ObjectWalk ow = walk.ToObjectWalkWithSameObjects();
                    pw.PreparePack(pm, ow, wantAll, commonBase);
                    rw = ow;
                }
                if (options.Contains(OPTION_INCLUDE_TAG))
                {
                    foreach (Ref vref in refs.Values)
                    {
                        Ref      @ref     = vref;
                        ObjectId objectId = @ref.GetObjectId();
                        // If the object was already requested, skip it.
                        if (wantAll.IsEmpty())
                        {
                            if (wantIds.Contains(objectId))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            RevObject obj = rw.LookupOrNull(objectId);
                            if (obj != null && obj.Has(WANT))
                            {
                                continue;
                            }
                        }
                        if ([email protected]())
                        {
                            @ref = db.Peel(@ref);
                        }
                        ObjectId peeledId = @ref.GetPeeledObjectId();
                        if (peeledId == null)
                        {
                            continue;
                        }
                        objectId = @ref.GetObjectId();
                        if (pw.WillInclude(peeledId) && !pw.WillInclude(objectId))
                        {
                            pw.AddObject(rw.ParseAny(objectId));
                        }
                    }
                }
                pw.WritePack(pm, NullProgressMonitor.INSTANCE, packOut);
                statistics = pw.GetStatistics();
                if (msgOut != null)
                {
                    string msg = pw.GetStatistics().GetMessage() + '\n';
                    msgOut.Write(Constants.Encode(msg));
                    msgOut.Flush();
                }
            }
            finally
            {
                pw.Release();
            }
            if (sideband)
            {
                pckOut.End();
            }
            if (logger != null && statistics != null)
            {
                logger.OnPackStatistics(statistics);
            }
        }
Пример #10
0
        /// <exception cref="System.IO.IOException"></exception>
        private void SendPack()
        {
            bool sideband = options.Contains(OPTION_SIDE_BAND) || options.Contains(OPTION_SIDE_BAND_64K
                                                                                   );

            if (!biDirectionalPipe)
            {
                // Ensure the request was fully consumed. Any remaining input must
                // be a protocol error. If we aren't at EOF the implementation is broken.
                int eof = rawIn.Read();
                if (0 <= eof)
                {
                    throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().expectedEOFReceived
                                                                          , "\\x" + Sharpen.Extensions.ToHexString(eof)));
                }
            }
            ProgressMonitor      pm      = NullProgressMonitor.INSTANCE;
            OutputStream         packOut = rawOut;
            SideBandOutputStream msgOut  = null;

            if (sideband)
            {
                int bufsz = SideBandOutputStream.SMALL_BUF;
                if (options.Contains(OPTION_SIDE_BAND_64K))
                {
                    bufsz = SideBandOutputStream.MAX_BUF;
                }
                packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA, bufsz, rawOut);
                if (!options.Contains(OPTION_NO_PROGRESS))
                {
                    msgOut = new SideBandOutputStream(SideBandOutputStream.CH_PROGRESS, bufsz, rawOut
                                                      );
                    pm = new SideBandProgressMonitor(msgOut);
                }
            }
            try
            {
                if (wantAll.IsEmpty())
                {
                    preUploadHook.OnSendPack(this, wantIds, commonBase);
                }
                else
                {
                    preUploadHook.OnSendPack(this, wantAll, commonBase);
                }
            }
            catch (UploadPackMayNotContinueException noPack)
            {
                if (sideband && noPack.Message != null)
                {
                    noPack.SetOutput();
                    SideBandOutputStream err = new SideBandOutputStream(SideBandOutputStream.CH_ERROR
                                                                        , SideBandOutputStream.SMALL_BUF, rawOut);
                    err.Write(Constants.Encode(noPack.Message));
                    err.Flush();
                }
                throw;
            }
            PackConfig cfg = packConfig;

            if (cfg == null)
            {
                cfg = new PackConfig(db);
            }
            PackWriter pw = new PackWriter(cfg, walk.GetObjectReader());

            try
            {
                pw.SetUseCachedPacks(true);
                pw.SetReuseDeltaCommits(true);
                pw.SetDeltaBaseAsOffset(options.Contains(OPTION_OFS_DELTA));
                pw.SetThin(options.Contains(OPTION_THIN_PACK));
                pw.SetReuseValidatingObjects(false);
                if (commonBase.IsEmpty())
                {
                    ICollection <ObjectId> tagTargets = new HashSet <ObjectId>();
                    foreach (Ref @ref in refs.Values)
                    {
                        if (@ref.GetPeeledObjectId() != null)
                        {
                            tagTargets.AddItem(@ref.GetPeeledObjectId());
                        }
                        else
                        {
                            if (@ref.GetObjectId() == null)
                            {
                                continue;
                            }
                            else
                            {
                                if (@ref.GetName().StartsWith(Constants.R_HEADS))
                                {
                                    tagTargets.AddItem(@ref.GetObjectId());
                                }
                            }
                        }
                    }
                    pw.SetTagTargets(tagTargets);
                }
                RevWalk rw = walk;
                if (wantAll.IsEmpty())
                {
                    pw.PreparePack(pm, wantIds, commonBase);
                }
                else
                {
                    walk.Reset();
                    ObjectWalk ow = walk.ToObjectWalkWithSameObjects();
                    pw.PreparePack(pm, ow, wantAll, commonBase);
                    rw = ow;
                }
                if (options.Contains(OPTION_INCLUDE_TAG))
                {
                    foreach (Ref vref in refs.Values)
                    {
                        Ref      @ref     = vref;
                        ObjectId objectId = @ref.GetObjectId();
                        // If the object was already requested, skip it.
                        if (wantAll.IsEmpty())
                        {
                            if (wantIds.Contains(objectId))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            RevObject obj = rw.LookupOrNull(objectId);
                            if (obj != null && obj.Has(WANT))
                            {
                                continue;
                            }
                        }
                        if ([email protected]())
                        {
                            @ref = db.Peel(@ref);
                        }
                        ObjectId peeledId = @ref.GetPeeledObjectId();
                        if (peeledId == null)
                        {
                            continue;
                        }
                        objectId = @ref.GetObjectId();
                        if (pw.WillInclude(peeledId) && !pw.WillInclude(objectId))
                        {
                            pw.AddObject(rw.ParseAny(objectId));
                        }
                    }
                }
                pw.WritePack(pm, NullProgressMonitor.INSTANCE, packOut);
                statistics = pw.GetStatistics();
                if (msgOut != null)
                {
                    string msg = pw.GetStatistics().GetMessage() + '\n';
                    msgOut.Write(Constants.Encode(msg));
                    msgOut.Flush();
                }
            }
            finally
            {
                pw.Release();
            }
            if (sideband)
            {
                pckOut.End();
            }
            if (logger != null && statistics != null)
            {
                logger.OnPackStatistics(statistics);
            }
        }
Пример #11
0
        /// <exception cref="NGit.Api.Errors.RefNotFoundException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="NGit.Api.Errors.NoHeadException"></exception>
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        private RebaseResult InitFilesAndRewind()
        {
            // we need to store everything into files so that we can implement
            // --skip, --continue, and --abort
            Ref head = repo.GetRef(Constants.HEAD);

            if (head == null || head.GetObjectId() == null)
            {
                throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved
                                                                    , Constants.HEAD));
            }
            string headName;

            if (head.IsSymbolic())
            {
                headName = head.GetTarget().GetName();
            }
            else
            {
                headName = "detached HEAD";
            }
            ObjectId headId = head.GetObjectId();

            if (headId == null)
            {
                throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved
                                                                    , Constants.HEAD));
            }
            RevCommit headCommit = walk.LookupCommit(headId);
            RevCommit upstream   = walk.LookupCommit(upstreamCommit.Id);

            if (walk.IsMergedInto(upstream, headCommit))
            {
                return(RebaseResult.UP_TO_DATE_RESULT);
            }
            else
            {
                if (walk.IsMergedInto(headCommit, upstream))
                {
                    // head is already merged into upstream, fast-foward
                    monitor.BeginTask(MessageFormat.Format(JGitText.Get().resettingHead, upstreamCommit
                                                           .GetShortMessage()), ProgressMonitor.UNKNOWN);
                    CheckoutCommit(upstreamCommit);
                    monitor.EndTask();
                    UpdateHead(headName, upstreamCommit);
                    return(RebaseResult.FAST_FORWARD_RESULT);
                }
            }
            monitor.BeginTask(JGitText.Get().obtainingCommitsForCherryPick, ProgressMonitor.UNKNOWN
                              );
            // determine the commits to be applied
            LogCommand           cmd            = new Git(repo).Log().AddRange(upstreamCommit, headCommit);
            Iterable <RevCommit> commitsToUse   = cmd.Call();
            IList <RevCommit>    cherryPickList = new AList <RevCommit>();

            foreach (RevCommit commit in commitsToUse)
            {
                if (commit.ParentCount != 1)
                {
                    throw new JGitInternalException(JGitText.Get().canOnlyCherryPickCommitsWithOneParent
                                                    );
                }
                cherryPickList.AddItem(commit);
            }
            Sharpen.Collections.Reverse(cherryPickList);
            // create the folder for the meta information
            FileUtils.Mkdir(rebaseDir);
            CreateFile(repo.Directory, Constants.ORIG_HEAD, headId.Name);
            CreateFile(rebaseDir, REBASE_HEAD, headId.Name);
            CreateFile(rebaseDir, HEAD_NAME, headName);
            CreateFile(rebaseDir, ONTO, upstreamCommit.Name);
            CreateFile(rebaseDir, INTERACTIVE, string.Empty);
            BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream
                                                                              (new FilePath(rebaseDir, GIT_REBASE_TODO)), Constants.CHARACTER_ENCODING));

            fw.Write("# Created by EGit: rebasing " + upstreamCommit.Name + " onto " + headId
                     .Name);
            fw.NewLine();
            try
            {
                StringBuilder sb     = new StringBuilder();
                ObjectReader  reader = walk.GetObjectReader();
                foreach (RevCommit commit_1 in cherryPickList)
                {
                    sb.Length = 0;
                    sb.Append(RebaseCommand.Action.PICK.ToToken());
                    sb.Append(" ");
                    sb.Append(reader.Abbreviate(commit_1).Name);
                    sb.Append(" ");
                    sb.Append(commit_1.GetShortMessage());
                    fw.Write(sb.ToString());
                    fw.NewLine();
                }
            }
            finally
            {
                fw.Close();
            }
            monitor.EndTask();
            // we rewind to the upstream commit
            monitor.BeginTask(MessageFormat.Format(JGitText.Get().rewinding, upstreamCommit.GetShortMessage
                                                       ()), ProgressMonitor.UNKNOWN);
            bool checkoutOk = false;

            try
            {
                checkoutOk = CheckoutCommit(upstreamCommit);
            }
            finally
            {
                if (!checkoutOk)
                {
                    FileUtils.Delete(rebaseDir, FileUtils.RECURSIVE);
                }
            }
            monitor.EndTask();
            return(null);
        }