Example usage for org.eclipse.jgit.merge Merger getResultTreeId

List of usage examples for org.eclipse.jgit.merge Merger getResultTreeId

Introduction

In this page you can find the example usage for org.eclipse.jgit.merge Merger getResultTreeId.

Prototype

public abstract ObjectId getResultTreeId();

Source Link

Document

Get resulting tree.

Usage

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//w  w w . ja  v a 2s  . c  o  m
 * @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.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static MergeResult mergeBranches(final Git git, final String source, final String target)
        throws Exception {

    final Repository repo = git.getRepository();
    final MergeStrategy mergeStrategy = MergeStrategy.RESOLVE;
    final List<Ref> commits = new LinkedList<Ref>();
    final boolean squash = false;

    RevWalk revWalk = null;//from www  . j av a 2s . c  o m
    DirCacheCheckout dco = null;
    try {
        Ref head = repo.getRef(Constants.HEAD);
        if (head == null) {
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
        }
        final 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.get(0);

        refLogMessage.append(ref.getName());

        // handle annotated tags
        ObjectId objectId = ref.getPeeledObjectId();
        if (objectId == null) {
            objectId = ref.getObjectId();
        }

        final RevCommit srcCommit = revWalk.lookupCommit(objectId);

        ObjectId headId = head.getObjectId();
        if (headId == null) {
            revWalk.parseHeaders(srcCommit);
            dco = new DirCacheCheckout(repo, repo.lockDirCache(), srcCommit.getTree());
            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);
            }

            return new MergeResult(srcCommit, srcCommit, new ObjectId[] { null, srcCommit },
                    MergeStatus.FAST_FORWARD, mergeStrategy, null, null);
        }

        final RevCommit headCommit = revWalk.lookupCommit(headId);

        if (revWalk.isMergedInto(srcCommit, headCommit)) {
            return new MergeResult(headCommit, srcCommit, new ObjectId[] { headCommit, srcCommit },
                    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(": " + FAST_FORWARD);
            dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(), srcCommit.getTree());
            dco.setFailOnConflict(true);
            dco.checkout();
            String msg = null;
            ObjectId newHead, base = null;
            final MergeStatus mergeStatus;
            if (!squash) {
                updateHead(git, refLogMessage, srcCommit, headId);
                newHead = base = srcCommit;
                mergeStatus = FAST_FORWARD;
            } else {
                msg = JGitText.get().squashCommitNotUpdatingHEAD;
                newHead = base = headId;
                mergeStatus = FAST_FORWARD_SQUASHED;
                final List<RevCommit> squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit);
                final String squashMessage = new SquashMessageFormatter().format(squashedCommits, head);
                repo.writeSquashCommitMsg(squashMessage);
            }
            return new MergeResult(newHead, base, new ObjectId[] { headCommit, srcCommit }, mergeStatus,
                    mergeStrategy, null, msg);
        } else {
            String mergeMessage = "";
            if (!squash) {
                mergeMessage = new MergeMessageFormatter().format(commits, head);
                repo.writeMergeCommitMsg(mergeMessage);
                repo.writeMergeHeads(Arrays.asList(ref.getObjectId()));
            } else {
                final List<RevCommit> squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit);
                final String squashMessage = new SquashMessageFormatter().format(squashedCommits, head);
                repo.writeSquashCommitMsg(squashMessage);
            }
            boolean noProblems;
            final Merger merger = mergeStrategy.newMerger(repo);
            final Map<String, org.eclipse.jgit.merge.MergeResult<?>> lowLevelResults;
            final Map<String, ResolveMerger.MergeFailureReason> failingPaths;
            final List<String> unmergedPaths;

            if (merger instanceof 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();
                unmergedPaths = resolveMerger.getUnmergedPaths();
            } else {
                noProblems = merger.merge(headCommit, srcCommit);
                lowLevelResults = emptyMap();
                failingPaths = emptyMap();
                unmergedPaths = emptyList();
            }

            refLogMessage.append(": Merge made by ");
            refLogMessage.append(mergeStrategy.getName());
            refLogMessage.append('.');
            if (noProblems) {
                dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(),
                        merger.getResultTreeId());
                dco.setFailOnConflict(true);
                dco.checkout();

                String msg = null;
                RevCommit newHead = null;
                MergeStatus mergeStatus = null;
                if (!squash) {
                    newHead = new Git(repo).commit().setReflogComment(refLogMessage.toString()).call();
                    mergeStatus = MERGED;
                } else {
                    msg = JGitText.get().squashCommitNotUpdatingHEAD;
                    newHead = headCommit;
                    mergeStatus = MERGED_SQUASHED;
                }
                return new MergeResult(newHead.getId(), null,
                        new ObjectId[] { headCommit.getId(), srcCommit.getId() }, mergeStatus, mergeStrategy,
                        null, msg);
            } else {
                if (failingPaths != null && !failingPaths.isEmpty()) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeMergeHeads(null);
                    return new MergeResult(null, merger.getBaseCommit(0, 1),
                            new ObjectId[] { headCommit.getId(), srcCommit.getId() }, FAILED, mergeStrategy,
                            lowLevelResults, failingPaths, null);
                } else {
                    final String mergeMessageWithConflicts = new MergeMessageFormatter()
                            .formatWithConflicts(mergeMessage, unmergedPaths);
                    repo.writeMergeCommitMsg(mergeMessageWithConflicts);
                    return new MergeResult(null, merger.getBaseCommit(0, 1),
                            new ObjectId[] { headCommit.getId(), srcCommit.getId() }, CONFLICTING,
                            mergeStrategy, lowLevelResults, null);
                }
            }
        }
    } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
        final List<String> conflicts = (dco == null) ? Collections.<String>emptyList() : dco.getConflicts();
        throw new CheckoutConflictException(conflicts, e);
    } catch (java.io.IOException e) {
        throw new JGitInternalException(
                MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand, e), e);
    } finally {
        if (revWalk != null) {
            revWalk.release();
        }
    }
}