Example usage for org.eclipse.jgit.api MergeCommand call

List of usage examples for org.eclipse.jgit.api MergeCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api MergeCommand call.

Prototype

@Override
@SuppressWarnings("boxing")
public MergeResult call()
        throws GitAPIException, NoHeadException, ConcurrentRefUpdateException, CheckoutConflictException,
        InvalidMergeHeadsException, WrongRepositoryStateException, NoMessageException 

Source Link

Document

Execute the Merge command with all the options and parameters collected by the setter methods (e.g.

Usage

From source file:br.com.riselabs.cotonet.builder.NetworkBuilder.java

License:Open Source License

/**
 * Returns the conflicting files of the given scenario.
 * /*w w w  .j a  v  a2  s.  co  m*/
 * @param scenario
 * @return
 * @throws CheckoutConflictException
 * @throws GitAPIException
 */
private List<File> getConflictingFiles(MergeScenario scenario)
        throws CheckoutConflictException, GitAPIException {
    Git git = Git.wrap(getProject().getRepository());
    // this is for the cases of restarting after exception in a conflict
    // scenario analysis
    try {
        git.reset().setRef(scenario.getLeft().getName()).setMode(ResetType.HARD).call();
    } catch (JGitInternalException e) {
        Logger.log(log, "[" + project.getName() + "] JGit Reset Command ended with exception."
                + " Trying external reset command.");
        ExternalGitCommand egit = new ExternalGitCommand();
        try {
            egit.setType(CommandType.RESET).setDirectory(project.getRepository().getDirectory().getParentFile())
                    .call();
        } catch (BlameException e1) {
            Logger.logStackTrace(log, e1);
            return null;
        }
    }

    CheckoutCommand ckoutCmd = git.checkout();
    ckoutCmd.setName(scenario.getLeft().getName());
    ckoutCmd.setStartPoint(scenario.getLeft());
    ckoutCmd.call();

    MergeCommand mergeCmd = git.merge();
    mergeCmd.setCommit(false);
    mergeCmd.setStrategy(MergeStrategy.RECURSIVE);
    mergeCmd.include(scenario.getRight());

    Set<String> conflictingPaths;
    try {
        // dealing with MissingObjectException
        MergeResult mResult = mergeCmd.call();
        // dealing with Ghosts conflicts
        conflictingPaths = mResult.getConflicts().keySet();
    } catch (NullPointerException | JGitInternalException e) {
        StringBuilder sb = new StringBuilder();
        sb.append("[" + project.getName() + ":" + project.getUrl() + "] " + "Skipping merge scenario due to '"
                + e.getMessage() + "'\n");
        sb.append("--> Exception: " + e.getClass());
        sb.append("--> Skipped scenario:\n");
        sb.append("::Base:" + scenario.getBase().getName() + "\n");
        sb.append("::Left:" + scenario.getLeft().getName() + "\n");
        sb.append("::Right:" + scenario.getRight().getName() + "\n");
        Logger.log(log, sb.toString());
        return null;
    }
    List<File> result = new ArrayList<File>();
    for (String path : conflictingPaths) {
        result.add(new File(getProject().getRepository().getDirectory().getParent(), path));
    }
    return result;
}

From source file:br.com.riselabs.cotonet.test.helpers.ConflictBasedRepositoryTestCase.java

License:Open Source License

public MergeResult runMerge(MergeScenario scenario) throws RefAlreadyExistsException, RefNotFoundException,
        InvalidRefNameException, CheckoutConflictException, GitAPIException {
    Git git = Git.wrap(db);//from   w ww  .ja  v a  2s.co m
    CheckoutCommand ckoutCmd = git.checkout();
    ckoutCmd.setName(scenario.getLeft().getName());
    ckoutCmd.setStartPoint(scenario.getLeft());
    ckoutCmd.call();

    MergeCommand mergeCmd = git.merge();
    mergeCmd.setCommit(false);
    mergeCmd.include(scenario.getRight());
    return mergeCmd.call();
}

From source file:com.rimerosolutions.ant.git.tasks.MergeTask.java

License:Apache License

@Override
public void doExecute() {
    try {/*from  www.j  a va  2 s  .  c  o  m*/
        MergeCommand mergeCommand = git.merge().setSquash(squash);
        mergeCommand.include(mergeCommand.getRepository().getRef(branchname));

        setupCredentials(mergeCommand);
        MergeResult mergeResult = mergeCommand.call();

        if (!mergeResult.getMergeStatus().isSuccessful()) {

            if (mergeResult.getFailingPaths() != null && mergeResult.getFailingPaths().size() > 0) {
                throw new BuildException(String.format("%s - Failing paths: %s", MESSAGE_MERGE_FAILED,
                        mergeResult.getFailingPaths()));
            }

            throw new BuildException(
                    String.format(MESSAGE_MERGE_FAILED_WITH_STATUS, mergeResult.getMergeStatus().name()));
        }
    } catch (Exception e) {
        throw new GitBuildException(String.format(MESSAGE_MERGE_FAILED_WITH_URI, getUri()), e);
    }
}

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

License:Apache License

public Pair<Boolean, String> merge(String branchToUpdate, String branchHead, boolean commit) {

    Pair<Boolean, String> ret = new Pair<>(false, "");
    MergeCommand command = _git.merge();
    try {/*from   ww w.j a v  a  2s .  c o m*/
        String refName = !branchHead.contains(REFS_HEADS) ? REFS_REMOTES + branchHead : branchHead;
        command.include(_repo.getRef(refName));
        command.setCommit(commit);
        MergeResult mergeResult = command.call();
        ret = checkResult(branchToUpdate, branchHead, ret, mergeResult);
    } catch (Throwable e) {
        VerigreenLogger.get().log(getClass().getName(), RuntimeUtils.getCurrentMethodName(), String
                .format("Failed to update branch [%s] with parent branch [%s]", branchToUpdate, branchHead));
    }

    return ret;
}

From source file:net.mobid.codetraq.runnables.GitChecker.java

License:Open Source License

private void attachHead(Git g, String branch) {
    LogService.writeMessage("Trying to attach HEAD to " + g.getRepository().toString());
    try {//from  w  w w  .j  a v a 2 s .  co m
        CheckoutCommand temp = g.checkout();
        temp.setCreateBranch(true);
        temp.setName("temp");
        Ref tRef = temp.call();
        CheckoutCommand b = g.checkout();
        b.setName(branch);
        b.setCreateBranch(true);
        b.call();
        MergeCommand merge = g.merge();
        merge.include(tRef);
        merge.call();
    } catch (Exception ex) {
        LogService.getLogger(GitChecker.class.getName()).log(Level.SEVERE, null, ex);
        LogService.writeLog(Level.SEVERE, ex);
    }
}

From source file:org.ajoberstar.gradle.git.tasks.GitMerge.java

License:Apache License

/**
 * Merges some changes with the current branch.
 *///from   w w  w  .j  a  v  a2  s . c  o m
@TaskAction
public void merge() {
    MergeCommand cmd = getGit().merge();
    cmd.include(findRef());
    cmd.setStrategy(getMergeStrategy());
    try {
        cmd.call();
    } catch (CheckoutConflictException e) {
        throw new GradleException("The working tree changes conflict with the specified commit.", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem with merge.", e);
    }
    //TODO add progress monitor to log progress to Gradle status bar
}

From source file:org.codehaus.mojo.versions.BumpMojo.java

License:Apache License

void gitMergeNFF(String c, String m) throws MojoExecutionException {
    try {//from ww w.  ja  v  a  2s. c  om
        MergeCommand ff = git.merge();
        ff.setCommit(false);
        ff.setFastForward(FastForwardMode.NO_FF);
        ff.include(git.getRepository().getRef(m));
        MergeResult f = ff.call();
        if (!f.getMergeStatus().isSuccessful()) {
            throw new MojoExecutionException(f.getMergeStatus().toString());
        }
        git.commit().setAll(true).setMessage(c).call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.eclipse.egit.core.op.MergeOperation.java

License:Open Source License

public void execute(IProgressMonitor m) throws CoreException {
    if (mergeResult != null)
        throw new CoreException(
                new Status(IStatus.ERROR, Activator.getPluginId(), CoreText.OperationAlreadyExecuted));
    IProgressMonitor monitor;//from   www.j a  v  a2  s. co m
    if (m == null)
        monitor = new NullProgressMonitor();
    else
        monitor = m;
    IWorkspaceRunnable action = new IWorkspaceRunnable() {

        public void run(IProgressMonitor mymonitor) throws CoreException {
            IProject[] validProjects = ProjectUtil.getValidProjects(repository);
            mymonitor.beginTask(NLS.bind(CoreText.MergeOperation_ProgressMerge, refName), 3);
            Git git = new Git(repository);
            mymonitor.worked(1);
            MergeCommand merge;
            try {
                merge = git.merge().include(repository.getRef(refName));
            } catch (IOException e) {
                throw new TeamException(CoreText.MergeOperation_InternalError, e);
            }
            if (mergeStrategy != null) {
                merge.setStrategy(mergeStrategy);
            }
            try {
                mergeResult = merge.call();
                mymonitor.worked(1);
                if (MergeResult.MergeStatus.FAILED.equals(mergeResult.getMergeStatus()))
                    throw new TeamException(mergeResult.toString());
                else if (MergeResult.MergeStatus.NOT_SUPPORTED.equals(mergeResult.getMergeStatus()))
                    throw new TeamException(
                            new Status(IStatus.INFO, Activator.getPluginId(), mergeResult.toString()));
            } catch (NoHeadException e) {
                throw new TeamException(CoreText.MergeOperation_MergeFailedNoHead, e);
            } catch (ConcurrentRefUpdateException e) {
                throw new TeamException(CoreText.MergeOperation_MergeFailedRefUpdate, e);
            } catch (GitAPIException e) {
                throw new TeamException(e.getLocalizedMessage(), e.getCause());
            } finally {
                ProjectUtil.refreshValidProjects(validProjects, new SubProgressMonitor(mymonitor, 1));
                mymonitor.done();
            }
        }
    };
    // lock workspace to protect working tree changes
    ResourcesPlugin.getWorkspace().run(action, monitor);
}

From source file:org.eclipse.ptp.internal.rdt.sync.git.core.JGitRepo.java

License:Open Source License

/**
 * Merge changes previously fetched from a remote repository
 *
 * @param monitor/*from  w w  w.  j a  v a2 s.c  o  m*/
 *
 * @return merge results
 * @throws GitAPIException
 *          on JGit-specific problems
 * @throws IOException
 *          on file system problems 
 */
public MergeResult merge(IProgressMonitor monitor) throws IOException, GitAPIException {
    RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 10);
    try {
        Ref remoteMasterRef = git.getRepository().getRef("refs/remotes/" + remoteBranchName + "/master"); //$NON-NLS-1$ //$NON-NLS-2$
        final MergeCommand mergeCommand = git.merge().include(remoteMasterRef);
        subMon.subTask(Messages.JGitRepo_12);
        // Bug 434783: Merge resolution only works once for each Eclipse session.
        // Need to reset flag after each merge.
        mergeMapInitialized = false;
        return mergeCommand.call();
    } finally {
        if (monitor != null) {
            monitor.done();
        }
    }
}

From source file:org.eclipse.ptp.rdt.sync.git.core.GitRemoteSyncConnection.java

License:Open Source License

/**
 * @param monitor//from  w  ww .  jav  a2 s  .  c o m
 * @throws RemoteSyncException
 *             for various problems sync'ing. The specific exception is
 *             nested within the RemoteSyncException. Many of the listed
 *             exceptions appear to be unrecoverable, caused by errors in
 *             the initial setup. It is vital, though, that failed syncs are
 *             reported and handled. So all exceptions are checked
 *             exceptions, embedded in a RemoteSyncException.
 */
public void syncRemoteToLocal(IProgressMonitor monitor, boolean includeUntrackedFiles)
        throws RemoteSyncException {

    // TODO: Figure out why pull doesn't work and why we have to fetch and
    // merge instead.
    // PullCommand pullCommand = gitConnection.getGit().pull().
    // try {
    // pullCommand.call();
    // } catch (WrongRepositoryStateException e) {
    // throw new RemoteSyncException(e);
    // } catch (InvalidConfigurationException e) {
    // throw new RemoteSyncException(e);
    // } catch (DetachedHeadException e) {
    // throw new RemoteSyncException(e);
    // } catch (InvalidRemoteException e) {
    // throw new RemoteSyncException(e);
    // } catch (CanceledException e) {
    // throw new RemoteSyncException(e);
    // }
    SubMonitor subMon = SubMonitor.convert(monitor, 10);
    subMon.subTask(Messages.GitRemoteSyncConnection_sync_remote_to_local);
    try {
        // First, commit in case any changes have occurred remotely.
        if (prepareRemoteForCommit(subMon.newChild(5), includeUntrackedFiles)) {
            commitRemoteFiles(subMon.newChild(5));
        }
        // Next, fetch the remote repository 
        //TODO: we currently need to do this always because we don't keep track of failed commits. We first need to decide whether we want to do commits based on delta or (as currently) based on git searching modified files
        //Than we can either keep track of deltas not transported yet or we can compare SHA-numbers (HEAD to remote-ref from last pull) to see whether something needs to be transported
        transport.fetch(new EclipseGitProgressTransformer(subMon.newChild(5)), null);

        // Now merge. Before merging we set the head for merging to master.
        Ref masterRef = git.getRepository().getRef("refs/remotes/" + remoteProjectName + "/master"); //$NON-NLS-1$ //$NON-NLS-2$

        final MergeCommand mergeCommand = git.merge().include(masterRef);

        mergeCommand.call();
    } catch (TransportException e) {
        if (e.getMessage().startsWith("Remote does not have ")) { //$NON-NLS-1$
            //just means that the remote branch isn't set up yet (and thus nothing too fetch). Can be ignored.
        } else {
            throw new RemoteSyncException(e);
        }
    } catch (IOException e) {
        throw new RemoteSyncException(e);
    } catch (GitAPIException e) {
        throw new RemoteSyncException(e);
    } finally {
        if (monitor != null) {
            monitor.done();
        }
    }
}