Example usage for org.eclipse.jgit.api MergeResult getNewHead

List of usage examples for org.eclipse.jgit.api MergeResult getNewHead

Introduction

In this page you can find the example usage for org.eclipse.jgit.api MergeResult getNewHead.

Prototype

public ObjectId getNewHead() 

Source Link

Document

Get the object the head points at after the merge

Usage

From source file:com.chungkwong.jgitgui.BranchTreeItem.java

License:Open Source License

private void gitMerge() {
    try {//from  ww  w.  java 2 s .  co  m
        MergeResult result = ((Git) getParent().getParent().getValue()).merge().include((Ref) getValue())
                .call();
        if (result.getMergeStatus().equals(MergeResult.MergeStatus.MERGED)) {
            RevCommit commit = ((Git) getParent().getParent().getValue()).log()
                    .addRange(result.getNewHead(), result.getNewHead()).call().iterator().next();
            getParent().getParent().getChildren().filtered(item -> item instanceof LocalTreeItem)
                    .forEach((item) -> item.getChildren().add(new CommitTreeItem(commit)));
        } else {
            new Alert(Alert.AlertType.INFORMATION, result.getMergeStatus().toString(), ButtonType.CLOSE).show();
        }
    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        Util.informUser(ex);
    }
}

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

private Pair<Boolean, String> checkResult(String branchToUpdate, String branchHead, Pair<Boolean, String> ret,
        MergeResult mergeResult) throws IOException {

    if (mergeResult.getMergeStatus().equals(MergeStatus.CONFLICTING)
            || mergeResult.getMergeStatus().equals(MergeStatus.FAILED)) {
        VerigreenLogger.get().log(getClass().getName(), RuntimeUtils.getCurrentMethodName(), String.format(
                "Merge conflicts for parent_branch:%s into:%s. rejecting commit", branchHead, branchToUpdate));
        reset(_repo.getRef(branchToUpdate).getName());
    } else if (mergeResult.getMergeStatus().equals(MergeStatus.ALREADY_UP_TO_DATE)
            || mergeResult.getMergeStatus().equals(MergeStatus.FAST_FORWARD)) {
        VerigreenLogger.get().log(getClass().getName(), RuntimeUtils.getCurrentMethodName(),
                String.format("Merge not needed for parent_branch:%s into:%s", branchHead, branchToUpdate));
        ret = new Pair<>(true, "");
    } else if (mergeResult.getMergeStatus().equals(MergeStatus.MERGED_NOT_COMMITTED)) {
        String autoMergeMessage = createMessageAutoCommit(mergeResult);
        String commitId = commit(commited_By_Collector, email_Address, autoMergeMessage);
        String adjustCommitId = commitId.substring(0, 7) + "_" + commited_By_Collector;
        VerigreenLogger.get().log(getClass().getName(), RuntimeUtils.getCurrentMethodName(), String.format(
                "Verigreen merge for parent_branch:%s into:%s was not committed. Performing auto commit [%s]",
                branchHead, branchToUpdate, adjustCommitId));
        ret = new Pair<>(true, adjustCommitId);
    } else if (mergeResult.getMergeStatus().equals(MergeStatus.MERGED)) {
        VerigreenLogger.get().log(getClass().getName(), RuntimeUtils.getCurrentMethodName(),
                "Merge was made after diverted branch with auto commit");
        ret = new Pair<>(true, "");
        new RestClientImpl().post(
                CollectorApi.getPostVerigreenNeededRequest(mergeResult.getNewHead().getName().substring(0, 7)));
    }// w w w .ja v  a 2  s.c  o m
    return ret;
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws MergeFailure/*from  www. j av  a2s  . c om*/
 * @throws AuthenticationException 
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateFromRemote(java.io.File, java.lang.String, java.lang.String,
 * gov.va.isaac.interfaces.sync.MergeFailOption)
 */
@Override
public Set<String> updateFromRemote(String username, String password, MergeFailOption mergeFailOption)
        throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException {
    Set<String> filesChangedDuringPull;
    try {
        log.info("update from remote called ");

        Git git = getGit();

        log.debug("Fetching from remote");

        if (git.status().call().getConflicting().size() > 0) {
            log.info("Previous merge failure not yet resolved");
            throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>());
        }

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));
        log.debug("Fetch Message" + git.fetch().setCredentialsProvider(cp).call().getMessages());

        ObjectId masterIdBeforeMerge = git.getRepository().getRef("master").getObjectId();
        if (git.getRepository().getRef("refs/remotes/origin/master").getObjectId().getName()
                .equals(masterIdBeforeMerge.getName())) {
            log.info("No changes to merge");
            return new HashSet<String>();
        }

        RevCommit stash = null;
        if (git.status().call().getUncommittedChanges().size() > 0) {
            log.info("Stashing uncommitted changes");
            stash = git.stashCreate().call();
        }

        {
            log.debug("Merging from remotes/origin/master");
            MergeResult mr = git.merge().include(git.getRepository().getRef("refs/remotes/origin/master"))
                    .call();
            AnyObjectId headAfterMergeID = mr.getNewHead();

            if (!mr.getMergeStatus().isSuccessful()) {
                if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) {
                    addNote(NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE
                            + (stash == null ? ":NO_STASH" : STASH_MARKER + stash.getName()), git);
                    //We can use the status here - because we already stashed the stuff that they had uncommitted above.
                    throw new MergeFailure(mr.getConflicts().keySet(),
                            git.status().call().getUncommittedChanges());
                } else if (MergeFailOption.KEEP_LOCAL == mergeFailOption
                        || MergeFailOption.KEEP_REMOTE == mergeFailOption) {
                    HashMap<String, MergeFailOption> resolutions = new HashMap<>();
                    for (String s : mr.getConflicts().keySet()) {
                        resolutions.put(s, mergeFailOption);
                    }
                    log.debug("Resolving merge failures with option {}", mergeFailOption);
                    filesChangedDuringPull = resolveMergeFailures(MergeFailType.REMOTE_TO_LOCAL,
                            (stash == null ? null : stash.getName()), resolutions);
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            } else {
                //Conflict free merge - or perhaps, no merge at all.
                if (masterIdBeforeMerge.getName().equals(headAfterMergeID.getName())) {
                    log.debug("Merge didn't result in a commit - no incoming changes");
                    filesChangedDuringPull = new HashSet<>();
                } else {
                    filesChangedDuringPull = listFilesChangedInCommit(git.getRepository(), masterIdBeforeMerge,
                            headAfterMergeID);
                }
            }
        }

        if (stash != null) {
            log.info("Replaying stash");
            try {
                git.stashApply().setStashRef(stash.getName()).call();
                log.debug("stash applied cleanly, dropping stash");
                git.stashDrop().call();
            } catch (StashApplyFailureException e) {
                log.debug("Stash failed to merge");
                if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) {
                    addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git);
                    throw new MergeFailure(git.status().call().getConflicting(), filesChangedDuringPull);
                }

                else if (MergeFailOption.KEEP_LOCAL == mergeFailOption
                        || MergeFailOption.KEEP_REMOTE == mergeFailOption) {
                    HashMap<String, MergeFailOption> resolutions = new HashMap<>();
                    for (String s : git.status().call().getConflicting()) {
                        resolutions.put(s, mergeFailOption);
                    }
                    log.debug("Resolving stash apply merge failures with option {}", mergeFailOption);
                    resolveMergeFailures(MergeFailType.STASH_TO_LOCAL, null, resolutions);
                    //When we auto resolve to KEEP_LOCAL - these files won't have really changed, even though we recorded a change above.
                    for (Entry<String, MergeFailOption> r : resolutions.entrySet()) {
                        if (MergeFailOption.KEEP_LOCAL == r.getValue()) {
                            filesChangedDuringPull.remove(r.getKey());
                        }
                    }
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            }
        }
        log.info("Files changed during updateFromRemote: {}", filesChangedDuringPull);
        return filesChangedDuringPull;
    } catch (CheckoutConflictException e) {
        log.error("Unexpected", e);
        throw new IOException(
                "A local file exists (but is not yet added to source control) which conflicts with a file from the server."
                        + "  Either delete the local file, or call addFile(...) on the offending file prior to attempting to update from remote.",
                e);
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:org.craftercms.deployer.impl.processors.GitPullProcessor.java

License:Open Source License

protected ChangeSet pullChanges(Git git) {
    try {// w  w  w . j  a  va 2  s.  co  m
        logger.info("Executing git pull for repository {}...", localRepositoryFolder);

        ObjectId head = git.getRepository().resolve(Constants.HEAD);
        PullResult pullResult = git.pull().call();

        if (pullResult.isSuccessful()) {
            MergeResult mergeResult = pullResult.getMergeResult();
            switch (mergeResult.getMergeStatus()) {
            case FAST_FORWARD:
                logger.info("Changes successfully pulled from remote {} for repository {}. Processing them...",
                        remoteRepositoryUrl, localRepositoryFolder);

                return resolveChangeSetFromPull(git, head, mergeResult.getNewHead());
            case ALREADY_UP_TO_DATE:
                logger.info("Git repository {} up to date (no changes pulled from remote {})",
                        localRepositoryFolder, remoteRepositoryUrl);
                return new ChangeSetImpl();
            default:
                // Not supported merge results
                throw new DeploymentException("Received unsupported merge result after executing pull command: "
                        + mergeResult.getMergeStatus());
            }
        }
    } catch (Exception e) {
        throw new DeploymentException("Git pull for repository " + localRepositoryFolder + " failed", e);
    }

    return new ChangeSetImpl();
}

From source file:org.eclipse.emf.compare.git.pgm.internal.app.LogicalMergeApplication.java

License:Open Source License

/**
 * Builds the message to display to the user when the merge ends on a FAST_FORWARD state.
 * //from  w w  w .  j a v a2  s .  c om
 * @param mergeResult
 *            The merge result.
 * @param oldHead
 *            The previous head before merge.
 * @return a message.
 */
private String buildFastForwardMessage(MergeResult mergeResult, Ref oldHead) {
    final StringBuilder messageBuilder = new StringBuilder();
    ObjectId oldHeadId = oldHead.getObjectId();
    messageBuilder.append("Updating ").append(oldHeadId.abbreviate(SHORT_COMMIT_ID_LENGTH).name()).append("..")
            .append(mergeResult.getNewHead().abbreviate(SHORT_COMMIT_ID_LENGTH).name()).append(EOL);
    messageBuilder.append(mergeResult.getMergeStatus().toString());
    return messageBuilder.toString();
}

From source file:org.gitistics.treewalk.SingleTreeDiffFilterTest.java

License:Open Source License

/**
 * master - merge//  w  w  w . j av a  2s  .co m
 * |                \
 * commit3 (+file3)   branch1 - commit2 (+file2)
 * |                /
 * commit1 (+file1)
  */
@Test
public void testMultipleParents() throws Exception {
    g.add("file1", "A");
    g.commit("commit1");
    g.branch("branch1");
    g.checkout("master");
    g.add("file2", "A");
    g.commit("commit2");
    g.checkout("branch1");
    g.add("file3", "A");
    RevCommit commit3 = g.commit("commit3").get();
    g.checkout("master");
    MergeResult merge = g.merge(commit3).get();

    SingleTreeDiffFilter filter = new SingleTreeDiffFilter(2);

    // The merge has nothing interesting
    TreeWalk walk = TreeUtils.withParents(repo, CommitUtils.getCommit(repo, merge.getNewHead()));
    walk.setFilter(filter);
    assertThat(walk.next(), equalTo(false));

    // The parents relative to each other will have +file2 or +file3
    // I.e. If commit3 is chosen we will get +file2 as +file2 is added
    // in both the other trees
    filter = new SingleTreeDiffFilter(1);
    walk = TreeUtils.withParents(repo, CommitUtils.getCommit(repo, merge.getNewHead()));
    walk.setFilter(filter);
    assertThat(walk.next(), equalTo(true));
    assertThat(walk.getPathString(), Matchers.anyOf(equalTo("file2"), equalTo("file3")));
    assertThat(walk.next(), equalTo(false));

}

From source file:org.gitistics.visitor.commit.TreeWalkVisitorStandardTest.java

License:Open Source License

/**
 * Test merge where no changes occur in the commit (its just a fast forward - so in the end 1 parent)
 * //from   w  ww. j av a 2  s . co  m
 * commit2 (+file1) (master,branch1)
 * commit1 
 * 
 */
@Test
public void testMergeFastForward() throws Exception {
    SimpleFileChangeCallback callback = new SimpleFileChangeCallback();
    g.commit("commit1");
    g.branch("branch1");
    g.add("file1", "A");
    RevCommit commit2 = g.commit("commit2").get();
    g.checkout("master");
    MergeResult result = g.merge(commit2).get();
    execute(CommitUtils.getCommit(repo, result.getNewHead()), callback);
    assertThat(callback.getFilesChanged().size(), equalTo(1));
}

From source file:org.gitistics.visitor.commit.TreeWalkVisitorStandardTest.java

License:Open Source License

/**
 * Test merge from two parents where we've only added files
 * //  ww w  . j  ava2  s  .  c  om
 * merge relative to commit2 has +file3
 * merge relative to commit3 has +file2 
 * 
 * We treat this as no files changed in this commit as we did nothing
 * in the merge itself
 * 
 * master - merge
 * |                \
 * commit3 (+file3)   branch1 - commit2 (+file2)
 * |                /
 * commit1 (+file1)
 */
@Test
public void testMultipleParentMultipleAddFileNoChanges() throws Exception {
    SimpleFileChangeCallback callback = new SimpleFileChangeCallback();
    g.add("file1", "A");
    g.commit("commit1");
    g.branch("branch1");
    g.checkout("master");
    g.add("file2", "A");
    g.commit("commit2");
    g.checkout("branch1");
    g.add("file3", "A");
    RevCommit commit3 = g.commit("commit3").get();
    g.checkout("master");
    MergeResult result = g.merge(commit3).get();
    execute(CommitUtils.getCommit(repo, result.getNewHead()), callback);
    assertThat(callback.getFilesChanged().size(), equalTo(0));
}

From source file:org.gitistics.visitor.commit.TreeWalkVisitorStandardTest.java

License:Open Source License

/**
 * Test merge from two parents where we've modified on both branches
 * but in different regions of the file/*from ww  w . jav  a 2s  .c o  m*/
 * 
 * Will be no merge conflict. 
 * 
 * Should only have changes where the merged commit
 * (Edit b sequence is shared across all parent commits)
  * 
 * 
 * master - merge
 * |                \
 * commit2 (~file1)   branch1 - commit3 (~file1)
 * |                /
 * commit1 (+file1)
 */
@Ignore
public void testMergeCommitWithModificationsInDifferentRegions() throws Exception {
    SimpleFileChangeCallback callback = new SimpleFileChangeCallback();
    g.add("file1", "A\nB\nC\nD\nE\nF\n");
    g.commit("commit1");
    g.branch("branch1");
    g.checkout("master");
    g.modify("file1", "A\nB\nC\nD\nE\nF\nG\nH\nI\n");
    g.commit("commit2");
    g.checkout("branch1");
    g.modify("file1", "X\nY\nZ\nA\nB\nC\nD\nE\nF\n");
    RevCommit commit3 = g.commit("commit3").get();
    g.checkout("master");
    MergeResult result = g.merge(commit3).get();
    execute(CommitUtils.getCommit(repo, result.getNewHead()), callback);
    assertThat(CommitUtils.getCommit(repo, result.getNewHead()).getParentCount(), equalTo(2));
    assertThat(callback.getFilesChanged().size(), equalTo(0));
}

From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * Update from remote./* w  ww . j  av  a  2  s .  co m*/
 *
 * @param username the username
 * @param password the password
 * @param mergeFailOption the merge fail option
 * @return the set
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MergeFailure the merge failure
 * @throws AuthenticationException the authentication exception
 * @see sh.isaac.api.sync.SyncFiles#updateFromRemote(java.io.File, java.lang.String, java.lang.String,
 * sh.isaac.api.sync.MergeFailOption)
 */
@Override
public Set<String> updateFromRemote(String username, char[] password, MergeFailOption mergeFailOption)
        throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException {
    LOG.info("update from remote called ");

    Set<String> filesChangedDuringPull;

    try (Git git = getGit()) {
        LOG.debug("Fetching from remote");

        if (git.status().call().getConflicting().size() > 0) {
            LOG.info("Previous merge failure not yet resolved");
            throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>());
        }

        final CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                ((password == null) ? new char[] {} : password));

        LOG.debug("Fetch Message" + git.fetch().setCredentialsProvider(cp).call().getMessages());

        final ObjectId masterIdBeforeMerge = git.getRepository().findRef("master").getObjectId();

        if (git.getRepository().exactRef("refs/remotes/origin/master").getObjectId().getName()
                .equals(masterIdBeforeMerge.getName())) {
            LOG.info("No changes to merge");
            return new HashSet<>();
        }

        RevCommit stash = null;

        if (git.status().call().getUncommittedChanges().size() > 0) {
            LOG.info("Stashing uncommitted changes");
            stash = git.stashCreate().call();
        }

        {
            LOG.debug("Merging from remotes/origin/master");

            final MergeResult mr = git.merge()
                    .include(git.getRepository().exactRef("refs/remotes/origin/master")).call();
            final AnyObjectId headAfterMergeID = mr.getNewHead();

            if (!mr.getMergeStatus().isSuccessful()) {
                if ((mergeFailOption == null) || (MergeFailOption.FAIL == mergeFailOption)) {
                    addNote(this.NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE
                            + ((stash == null) ? ":NO_STASH" : this.STASH_MARKER + stash.getName()), git);

                    // We can use the status here - because we already stashed the stuff that they had uncommitted above.
                    throw new MergeFailure(mr.getConflicts().keySet(),
                            git.status().call().getUncommittedChanges());
                } else if ((MergeFailOption.KEEP_LOCAL == mergeFailOption)
                        || (MergeFailOption.KEEP_REMOTE == mergeFailOption)) {
                    final HashMap<String, MergeFailOption> resolutions = new HashMap<>();

                    mr.getConflicts().keySet().forEach((s) -> {
                        resolutions.put(s, mergeFailOption);
                    });

                    LOG.debug("Resolving merge failures with option {}", mergeFailOption);
                    filesChangedDuringPull = resolveMergeFailures(MergeFailType.REMOTE_TO_LOCAL,
                            ((stash == null) ? null : stash.getName()), resolutions);
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            } else {
                // Conflict free merge - or perhaps, no merge at all.
                if (masterIdBeforeMerge.getName().equals(headAfterMergeID.getName())) {
                    LOG.debug("Merge didn't result in a commit - no incoming changes");
                    filesChangedDuringPull = new HashSet<>();
                } else {
                    filesChangedDuringPull = listFilesChangedInCommit(git.getRepository(), masterIdBeforeMerge,
                            headAfterMergeID);
                }
            }
        }

        if (stash != null) {
            LOG.info("Replaying stash");

            try {
                git.stashApply().setStashRef(stash.getName()).call();
                LOG.debug("stash applied cleanly, dropping stash");
                git.stashDrop().call();
            } catch (final StashApplyFailureException e) {
                LOG.debug("Stash failed to merge");

                if ((mergeFailOption == null) || (MergeFailOption.FAIL == mergeFailOption)) {
                    addNote(this.NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git);
                    throw new MergeFailure(git.status().call().getConflicting(), filesChangedDuringPull);
                } else if ((MergeFailOption.KEEP_LOCAL == mergeFailOption)
                        || (MergeFailOption.KEEP_REMOTE == mergeFailOption)) {
                    final HashMap<String, MergeFailOption> resolutions = new HashMap<>();

                    for (final String s : git.status().call().getConflicting()) {
                        resolutions.put(s, mergeFailOption);
                    }

                    LOG.debug("Resolving stash apply merge failures with option {}", mergeFailOption);
                    resolveMergeFailures(MergeFailType.STASH_TO_LOCAL, null, resolutions);

                    // When we auto resolve to KEEP_LOCAL - these files won't have really changed, even though we recorded a change above.
                    resolutions.entrySet().stream().filter((r) -> (MergeFailOption.KEEP_LOCAL == r.getValue()))
                            .forEachOrdered((r) -> {
                                filesChangedDuringPull.remove(r.getKey());
                            });
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            }
        }

        LOG.info("Files changed during updateFromRemote: {}", filesChangedDuringPull);
        return filesChangedDuringPull;
    } catch (final CheckoutConflictException e) {
        LOG.error("Unexpected", e);
        throw new IOException(
                "A local file exists (but is not yet added to source control) which conflicts with a file from the server."
                        + "  Either delete the local file, or call addFile(...) on the offending file prior to attempting to update from remote.",
                e);
    } catch (final TransportException te) {
        if (te.getMessage().contains("Auth fail") || te.getMessage().contains("not authorized")) {
            LOG.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            LOG.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (final GitAPIException e) {
        LOG.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}