Example usage for org.eclipse.jgit.dircache DirCacheCheckout getConflicts

List of usage examples for org.eclipse.jgit.dircache DirCacheCheckout getConflicts

Introduction

In this page you can find the example usage for org.eclipse.jgit.dircache DirCacheCheckout getConflicts.

Prototype

public List<String> getConflicts() 

Source Link

Document

Get a list of conflicts created by this checkout

Usage

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;//  ww  w .jav a2 s . 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();
        }
    }
}

From source file:util.ChkoutCmd.java

License:Eclipse Distribution License

/**
 * @throws RefAlreadyExistsException//from ww w  . j ava  2  s. c o m
 *             when trying to create (without force) a branch with a name
 *             that already exists
 * @throws RefNotFoundException
 *             if the start point or branch can not be found
 * @throws InvalidRefNameException
 *             if the provided name is <code>null</code> or otherwise
 *             invalid
 * @throws CheckoutConflictException
 *             if the checkout results in a conflict
 * @return the newly created branch
 */
public Ref call() throws GitAPIException, RefAlreadyExistsException, RefNotFoundException,
        InvalidRefNameException, CheckoutConflictException {
    checkCallable();
    processOptions();
    try {
        if (checkoutAllPaths || !paths.isEmpty()) {
            checkoutPaths();
            status = new CheckoutResult(Status.OK, paths);
            setCallable(false);
            return null;
        }

        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 shortHeadRef = getShortBranchName(headRef);
        String refLogMessage = "checkout: moving from " + shortHeadRef; //$NON-NLS-1$
        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.getTree();
        DirCacheCheckout dco;
        DirCache dc = repo.lockDirCache();
        try {
            dco = new DirCacheCheckout(repo, headTree, dc, newCommit.getTree());
            dco.setFailOnConflict(false);
            try {
                dco.checkout();
            } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
                status = new CheckoutResult(Status.CONFLICTS, dco.getConflicts());
                throw new CheckoutConflictException(dco.getConflicts(), e);
            }
        } finally {
            dc.unlock();
        }
        Ref ref = repo.getRef(name);
        if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
            ref = null;
        String toName = Repository.shortenRefName(name);
        RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
        refUpdate.setForceUpdate(force);
        refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false); //$NON-NLS-1$
        Result updateResult;
        if (ref != null)
            updateResult = refUpdate.link(ref.getName());
        else {
            refUpdate.setNewObjectId(newCommit);
            updateResult = refUpdate.forceUpdate();
        }

        setCallable(false);

        boolean ok = false;
        switch (updateResult) {
        case NEW:
            ok = true;
            break;
        case NO_CHANGE:
        case FAST_FORWARD:
        case FORCED:
            ok = true;
            break;
        default:
            break;
        }

        if (!ok)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().checkoutUnexpectedResult, updateResult.name()));

        if (!dco.getToBeDeleted().isEmpty()) {
            status = new CheckoutResult(Status.NONDELETED, dco.getToBeDeleted());
        } else
            status = new CheckoutResult(new ArrayList<String>(dco.getUpdated().keySet()), dco.getRemoved());

        return ref;
    } catch (IOException ioe) {
        throw new JGitInternalException(ioe.getMessage(), ioe);
    } finally {
        if (status == null)
            status = CheckoutResult.ERROR_RESULT;
    }
}