Example usage for org.eclipse.jgit.api.errors NoHeadException NoHeadException

List of usage examples for org.eclipse.jgit.api.errors NoHeadException NoHeadException

Introduction

In this page you can find the example usage for org.eclipse.jgit.api.errors NoHeadException NoHeadException.

Prototype

public NoHeadException(String message) 

Source Link

Document

Constructor for NoHeadException

Usage

From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java

/**
 * Executes the {@code commit} 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 {@link #call()})//from  www  .  jav  a 2s .  c  om
 *
 * @return a {@link RevCommit} object representing the successful commit.
 * @throws NoHeadException
 *             when called on a git repo without a HEAD reference
 * @throws NoMessageException
 *             when called without specifying a commit message
 * @throws UnmergedPathsException
 *             when the current index contained unmerged paths (conflicts)
 * @throws ConcurrentRefUpdateException
 *             when HEAD or branch ref is updated concurrently by someone
 *             else
 * @throws WrongRepositoryStateException
 *             when repository is not in the right state for committing
 * @throws AbortedByHookException
 *             if there are either pre-commit or commit-msg hooks present in
 *             the repository and one of them rejects the commit.
 */
public RevCommit call() throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException,
        ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException {
    checkCallable();
    Collections.sort(only);

    try (RevWalk rw = new RevWalk(repo)) {
        RepositoryState state = repo.getRepositoryState();

        if (!noVerify) {
            Hooks.preCommit(repo, hookOutRedirect).call();
        }

        processOptions(state, rw);

        if (all && !repo.isBare()) {
            try (Git git = new Git(repo)) {
                git.add().addFilepattern(".") //$NON-NLS-1$
                        .setUpdate(true).call();
            } catch (NoFilepatternException e) {
                // should really not happen
                throw new JGitInternalException(e.getMessage(), e);
            }
        }

        Ref head = repo.findRef(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}"); //$NON-NLS-1$
        if (headId == null && amend)
            throw new WrongRepositoryStateException(JGitText.get().commitAmendOnInitialNotPossible);

        if (headId != null) {
            if (amend) {
                RevCommit previousCommit = rw.parseCommit(headId);
                for (RevCommit p : previousCommit.getParents())
                    parents.add(p.getId());
                if (author == null)
                    author = previousCommit.getAuthorIdent();
            } else {
                parents.add(0, headId);
            }
        }
        if (!noVerify) {
            message = Hooks.commitMsg(repo, hookOutRedirect).setCommitMessage(message).call();
        }

        // lock the index
        //         DirCache index = repo.lockDirCache();
        index.lock();
        try (ObjectInserter odi = repo.newObjectInserter()) {
            if (!only.isEmpty())
                index = createTemporaryIndex(headId, index, rw);

            // 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);

            // Check for empty commits
            if (headId != null && !allowEmpty.booleanValue()) {
                RevCommit headCommit = rw.parseCommit(headId);
                headCommit.getTree();
                if (indexTreeId.equals(headCommit.getTree())) {
                    return null;
                }
            }

            // Create a Commit object, populate it and write it
            CommitBuilder commit = new CommitBuilder();
            commit.setCommitter(committer);
            commit.setAuthor(author);
            commit.setMessage(message);

            commit.setParentIds(parents);
            commit.setTreeId(indexTreeId);
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevCommit revCommit = rw.parseCommit(commitId);
            RefUpdate ru = repo.updateRef(Constants.HEAD);
            ru.setNewObjectId(commitId);
            if (reflogComment != null) {
                ru.setRefLogMessage(reflogComment, false);
            } else {
                String prefix = amend ? "commit (amend): " //$NON-NLS-1$
                        : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$
                                : "commit: "; //$NON-NLS-1$
                ru.setRefLogMessage(prefix + revCommit.getShortMessage(), false);
            }
            if (headId != null) {
                ru.setExpectedOldObjectId(headId);
            } else {
                ru.setExpectedOldObjectId(ObjectId.zeroId());
            }
            Result rc = ru.forceUpdate();
            switch (rc) {
            case NEW:
            case FORCED:
            case FAST_FORWARD: {
                setCallable(false);
                if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) {
                    // 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);
                } else if (state == RepositoryState.REVERTING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeRevertHead(null);
                }
                return revCommit;
            }
            case REJECTED:
            case 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 {
            index.unlock();
        }
    } catch (UnmergedPathException e) {
        throw new UnmergedPathsException(e);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
    }
}

From source file:org.codice.git.GitHandler.java

License:Open Source License

@Override
public String getDiff() throws Exception {
    final ObjectId head = repo.resolve(Constants.HEAD + "^{tree}");

    if (head == null) {
        LOGGER.warning("Unable to resolve the HEAD of this git tree");
        throw new NoHeadException(JGitText.get().cannotReadTree);
    }//  w w  w .j  a va  2s  .c om
    final CanonicalTreeParser p = new CanonicalTreeParser();
    final ObjectReader reader = repo.newObjectReader();

    try {
        p.reset(reader, head);
    } finally {
        reader.release();
    }
    final AbstractTreeIterator oldTree = p;
    final AbstractTreeIterator newTree = new DirCacheIterator(repo.readDirCache());
    final OutputStream out = new ByteArrayOutputStream();
    final ChangeOnlyDiffFormatter diffFmt = new ChangeOnlyDiffFormatter(new BufferedOutputStream(out));

    diffFmt.setRepository(repo);
    diffFmt.setPathFilter(TreeFilter.ALL);
    diffFmt.setProgressMonitor(NullProgressMonitor.INSTANCE);

    LOGGER.finer("Scanning the git tree for diffs");
    final List<DiffEntry> result = diffFmt.scan(oldTree, newTree);

    diffFmt.format(result);
    diffFmt.flush();
    diffFmt.release();

    return out.toString();
}

From source file:org.craftercms.studio.impl.v1.util.git.CherryPickCommandEx.java

License:Eclipse Distribution License

/**
 * Executes the {@code Cherry-Pick} command with all the options and
 * parameters collected by the setter methods (e.g. {@link #include(Ref)} 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.
 *
 * @return the result of the cherry-pick
 * @throws GitAPIException//from www  . j  ava 2  s.  com
 * @throws WrongRepositoryStateException
 * @throws ConcurrentRefUpdateException
 * @throws UnmergedPathsException
 * @throws NoMessageException
 * @throws NoHeadException
 */
@Override
public CherryPickResult call() throws GitAPIException {
    RevCommit newHead = null;
    List<Ref> cherryPickedRefs = new LinkedList<>();
    checkCallable();

    try (RevWalk revWalk = new RevWalk(repo)) {

        // get the head commit
        Ref headRef = repo.exactRef(Constants.HEAD);
        if (headRef == null)
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);

        newHead = revWalk.parseCommit(headRef.getObjectId());

        // loop through all refs to be cherry-picked
        for (Ref src : 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);

            Merger merger = strategy.newMerger(repo);
            if (merger.merge(newHead, srcCommit)) {
                if (AnyObjectId.equals(newHead.getTree().getId(), merger.getResultTreeId()))
                    continue;
                DirCacheCheckout dco = new DirCacheCheckout(repo, newHead.getTree(), repo.lockDirCache(),
                        merger.getResultTreeId());
                dco.setFailOnConflict(true);
                dco.checkout();
                if (!noCommit)
                    newHead = new Git(getRepository()).commit().setMessage(srcCommit.getFullMessage())
                            .setReflogComment(reflogPrefix + " " //$NON-NLS-1$
                                    + srcCommit.getShortMessage())
                            .setAuthor(srcCommit.getAuthorIdent()).setNoVerify(true).call();
                cherryPickedRefs.add(src);
            } else {
                return CherryPickResult.CONFLICT;
            }
        }
    } catch (IOException e) {
        throw new JGitInternalException(
                MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, e), e);
    }
    return new CherryPickResult(newHead, cherryPickedRefs);
}

From source file:org.eclipse.orion.server.gerritfs.DiffCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Diff} command with all the options and parameters collected by the setter methods (e.g. {@link #setCached(boolean)} 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.
 *
 * @return a DiffEntry for each path which is different
 *//*from  ww  w.j  a  va 2 s . c  o  m*/
@Override
public List<DiffEntry> call() throws GitAPIException {
    final DiffFormatter diffFmt;
    if (out != null && !showNameAndStatusOnly)
        diffFmt = new DiffFormatter(new BufferedOutputStream(out));
    else
        diffFmt = new DiffFormatter(NullOutputStream.INSTANCE);
    if (ignoreWS)
        diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
    diffFmt.setRepository(repo);
    diffFmt.setProgressMonitor(monitor);
    try {
        if (cached) {
            if (oldTree == null) {
                ObjectId head = repo.resolve(HEAD + "^{tree}"); //$NON-NLS-1$
                if (head == null)
                    throw new NoHeadException(JGitText.get().cannotReadTree);
                CanonicalTreeParser p = new CanonicalTreeParser();
                ObjectReader reader = repo.newObjectReader();
                try {
                    p.reset(reader, head);
                } finally {
                    reader.release();
                }
                oldTree = p;
            }
            newTree = new DirCacheIterator(repo.readDirCache());
        } else {
            if (oldTree == null)
                oldTree = new DirCacheIterator(repo.readDirCache());
            if (newTree == null)
                newTree = new FileTreeIterator(repo);
        }

        diffFmt.setPathFilter(pathFilter);

        List<DiffEntry> result = diffFmt.scan(oldTree, newTree);
        if (showNameAndStatusOnly)
            return result;
        else {
            if (contextLines >= 0)
                diffFmt.setContext(contextLines);
            if (destinationPrefix != null)
                diffFmt.setNewPrefix(destinationPrefix);
            if (sourcePrefix != null)
                diffFmt.setOldPrefix(sourcePrefix);
            diffFmt.format(result);
            diffFmt.flush();
            return result;
        }
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    } finally {
        diffFmt.release();
    }
}

From source file:org.eclipse.orion.server.git.jobs.LogCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Log} command with all the options and parameters collected by the setter methods (e.g. {@link #add(AnyObjectId)},
 * {@link #not(AnyObjectId)}, ..) 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.//from ww w. ja  v a2s.  c o m
 *
 * @return an iteration over RevCommits
 * @throws NoHeadException
 *             of the references ref cannot be resolved
 */
@Override
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException {
    checkCallable();
    ArrayList<RevFilter> filters = new ArrayList<RevFilter>();

    if (pathFilters.size() > 0)
        walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF));

    if (msgFilter != null)
        filters.add(msgFilter);
    if (authorFilter != null)
        filters.add(authorFilter);
    if (committerFilter != null)
        filters.add(committerFilter);
    if (sha1Filter != null)
        filters.add(sha1Filter);
    if (dateFilter != null)
        filters.add(dateFilter);
    if (skip > -1)
        filters.add(SkipRevFilter.create(skip));
    if (maxCount > -1)
        filters.add(MaxCountRevFilter.create(maxCount));
    RevFilter filter = null;
    if (filters.size() > 1) {
        filter = AndRevFilter.create(filters);
    } else if (filters.size() == 1) {
        filter = filters.get(0);
    }

    if (filter != null)
        walk.setRevFilter(filter);

    if (!startSpecified) {
        try {
            ObjectId headId = repo.resolve(Constants.HEAD);
            if (headId == null)
                throw new NoHeadException(JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified);
            add(headId);
        } catch (IOException e) {
            // all exceptions thrown by add() shouldn't occur and represent
            // severe low-level exception which are therefore wrapped
            throw new JGitInternalException(JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e);
        }
    }
    setCallable(false);
    return walk;
}

From source file:org.eclipse.orion.server.git.jobs.StashApplyCommand.java

License:Eclipse Distribution License

/**
 * Apply the changes in a stashed commit to the working directory and index
 *
 * @return id of stashed commit that was applied TODO: Does anyone depend on this, or could we make it more like Merge/CherryPick/Revert?
 * @throws GitAPIException/*w  ww  . j  a va2  s.  c  om*/
 * @throws WrongRepositoryStateException
 * @throws NoHeadException
 * @throws StashApplyFailureException
 */
@Override
public ObjectId call()
        throws GitAPIException, WrongRepositoryStateException, NoHeadException, StashApplyFailureException {
    checkCallable();

    if (!ignoreRepositoryState && repo.getRepositoryState() != RepositoryState.SAFE)
        throw new WrongRepositoryStateException(
                MessageFormat.format(JGitText.get().stashApplyOnUnsafeRepository, repo.getRepositoryState()));

    ObjectReader reader = repo.newObjectReader();
    try {
        RevWalk revWalk = new RevWalk(reader);

        ObjectId headCommit = repo.resolve(Constants.HEAD);
        if (headCommit == null)
            throw new NoHeadException(JGitText.get().stashApplyWithoutHead);

        final ObjectId stashId = getStashId();
        RevCommit stashCommit = revWalk.parseCommit(stashId);
        if (stashCommit.getParentCount() < 2 || stashCommit.getParentCount() > 3)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().stashCommitIncorrectNumberOfParents, stashId.name(),
                            Integer.valueOf(stashCommit.getParentCount())));

        ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
        ObjectId stashIndexCommit = revWalk.parseCommit(stashCommit.getParent(1));
        ObjectId stashHeadCommit = stashCommit.getParent(0);
        ObjectId untrackedCommit = null;
        if (applyUntracked && stashCommit.getParentCount() == 3)
            untrackedCommit = revWalk.parseCommit(stashCommit.getParent(2));

        ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
        merger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stash" });
        merger.setBase(stashHeadCommit);
        merger.setWorkingTreeIterator(new FileTreeIterator(repo));
        if (merger.merge(headCommit, stashCommit)) {
            DirCache dc = repo.lockDirCache();
            DirCacheCheckout dco = new DirCacheCheckout(repo, headTree, dc, merger.getResultTreeId());
            dco.setFailOnConflict(true);
            dco.checkout(); // Ignoring failed deletes....
            if (applyIndex) {
                ResolveMerger ixMerger = (ResolveMerger) strategy.newMerger(repo, true);
                ixMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stashed index" });
                ixMerger.setBase(stashHeadCommit);
                boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
                if (ok) {
                    resetIndex(revWalk.parseTree(ixMerger.getResultTreeId()));
                } else {
                    throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
                }
            }

            if (untrackedCommit != null) {
                ResolveMerger untrackedMerger = (ResolveMerger) strategy.newMerger(repo, true);
                untrackedMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "untracked files" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                untrackedMerger.setBase(stashHeadCommit);
                boolean ok = untrackedMerger.merge(stashHeadCommit, untrackedCommit);
                if (ok)
                    try {
                        RevTree untrackedTree = revWalk.parseTree(untrackedMerger.getResultTreeId());
                        resetUntracked(untrackedTree);
                    } catch (CheckoutConflictException e) {
                        throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
                    }
                else
                    throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
            }
        } else {
            throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
        }
        return stashId;

    } catch (JGitInternalException e) {
        throw e;
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
    } finally {
        reader.release();
    }
}

From source file:org.flowerplatform.web.git.GitUtils.java

License:Open Source License

@SuppressWarnings("restriction")
public Object[] getFetchPushUpstreamDataRefSpecAndRemote(Repository repository)
        throws InvalidConfigurationException, NoHeadException, DetachedHeadException {

    String branchName;// www.ja va2 s.co m
    String fullBranch;
    try {
        fullBranch = repository.getFullBranch();
        if (fullBranch == null) {
            throw new NoHeadException(JGitText.get().pullOnRepoWithoutHEADCurrentlyNotSupported);
        }
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            // we can not pull if HEAD is detached and branch is not
            // specified explicitly
            throw new DetachedHeadException();
        }
        branchName = fullBranch.substring(Constants.R_HEADS.length());
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e);
    }
    // get the configured remote for the currently checked out branch
    // stored in configuration key branch.<branch name>.remote
    Config repoConfig = repository.getConfig();
    String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REMOTE);
    if (remote == null) {
        // fall back to default remote
        remote = Constants.DEFAULT_REMOTE_NAME;
    }

    // get the name of the branch in the remote repository
    // stored in configuration key branch.<branch name>.merge
    String remoteBranchName = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_MERGE);

    if (remoteBranchName == null) {
        String missingKey = ConfigConstants.CONFIG_BRANCH_SECTION + "." + branchName + "."
                + ConfigConstants.CONFIG_KEY_MERGE;
        throw new InvalidConfigurationException(
                MessageFormat.format(JGitText.get().missingConfigurationForKey, missingKey));
    }

    // check if the branch is configured for pull-rebase
    boolean doRebase = repoConfig.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REBASE, false);

    final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
    String remoteUri;
    if (isRemote) {
        remoteUri = repoConfig.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remote,
                ConfigConstants.CONFIG_KEY_URL);
        if (remoteUri == null) {
            String missingKey = ConfigConstants.CONFIG_REMOTE_SECTION + "." + remote + "."
                    + ConfigConstants.CONFIG_KEY_URL;
            throw new InvalidConfigurationException(
                    MessageFormat.format(JGitText.get().missingConfigurationForKey, missingKey));
        }

        return new Object[] { fullBranch, remoteBranchName, remoteUri, doRebase };
    }
    return null;
}

From source file:org.impressivecode.depress.scm.git.GitOnlineLogParser.java

License:Open Source License

private static Git initializeGit(final String path) throws IOException, NoHeadException {
    RepositoryBuilder gitRepoBuilder = new RepositoryBuilder();
    Repository gitRepo = gitRepoBuilder.setGitDir(new File(path)).readEnvironment().findGitDir().build();
    Git git = new Git(gitRepo);

    // Make sure path contains a git repository.
    if (!gitRepo.getObjectDatabase().exists()) {
        throw new NoHeadException("Directory " + path + " does not look like a git repository.");
    }//from  w w w. j ava  2 s.  c  o m

    return git;
}

From source file:org.jboss.forge.addon.git.GitUtilsImpl.java

License:Open Source License

@Override
public CherryPickResult cherryPickNoMerge(final Git git, Ref src)
        throws GitAPIException, CantMergeCommitException {
    // Does the same as the original git-cherryPick
    // except commiting after running merger
    Repository repo = git.getRepository();

    RevCommit newHead = null;//from  ww  w.j av  a2  s .c  o  m
    List<Ref> cherryPickedRefs = new LinkedList<Ref>();

    try (RevWalk revWalk = new RevWalk(repo)) {
        // get the head commit
        Ref headRef = repo.findRef(Constants.HEAD);
        if (headRef == null)
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
        RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());

        newHead = headCommit;

        // 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.getParentCount() == 0)
            throw new CantMergeCommitException("Commit with zero parents cannot be merged");

        if (srcCommit.getParentCount() > 1)
            throw new MultipleParentsNotAllowedException(
                    MessageFormat.format(JGitText.get().canOnlyCherryPickCommitsWithOneParent, srcCommit.name(),
                            Integer.valueOf(srcCommit.getParentCount())));

        RevCommit srcParent = srcCommit.getParent(0);
        revWalk.parseHeaders(srcParent);

        ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE.newMerger(repo);
        merger.setWorkingTreeIterator(new FileTreeIterator(repo));
        merger.setBase(srcParent.getTree());
        if (merger.merge(headCommit, srcCommit)) {
            DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(),
                    merger.getResultTreeId());
            dco.setFailOnConflict(true);
            dco.checkout();

            cherryPickedRefs.add(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.getId());
            repo.writeMergeCommitMsg(message);

            return CherryPickResult.CONFLICT;
        }
    } catch (IOException e) {
        throw new JGitInternalException(
                MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, e), e);
    }
    return new CherryPickResult(newHead, cherryPickedRefs);
}

From source file:org.jboss.forge.git.GitUtils.java

License:Open Source License

public static CherryPickResult cherryPickNoMerge(final Git git, Ref src)
        throws GitAPIException, CantMergeCommitWithZeroParentsException {
    // Does the same as the original git-cherryPick
    // except commiting after running merger
    Repository repo = git.getRepository();

    RevCommit newHead = null;/*  w ww. ja v  a2  s . co  m*/
    List<Ref> cherryPickedRefs = new LinkedList<Ref>();

    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;

        // 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.getParentCount() == 0)
            throw new CantMergeCommitWithZeroParentsException("Commit with zero parents cannot be merged");

        if (srcCommit.getParentCount() > 1)
            throw new MultipleParentsNotAllowedException(
                    MessageFormat.format(JGitText.get().canOnlyCherryPickCommitsWithOneParent, srcCommit.name(),
                            Integer.valueOf(srcCommit.getParentCount())));

        RevCommit srcParent = srcCommit.getParent(0);
        revWalk.parseHeaders(srcParent);

        ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE.newMerger(repo);
        merger.setWorkingTreeIterator(new FileTreeIterator(repo));
        merger.setBase(srcParent.getTree());
        if (merger.merge(headCommit, srcCommit)) {
            DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(),
                    merger.getResultTreeId());
            dco.setFailOnConflict(true);
            dco.checkout();

            cherryPickedRefs.add(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.getId());
            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);
}