Example usage for org.eclipse.jgit.lib RepositoryState MERGING

List of usage examples for org.eclipse.jgit.lib RepositoryState MERGING

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib RepositoryState MERGING.

Prototype

RepositoryState MERGING

To view the source code for org.eclipse.jgit.lib RepositoryState MERGING.

Click Source Link

Document

An unfinished merge.

Usage

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public PullResponse pull(PullRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;/*from   ww w . jav  a  2s.co  m*/
    try {
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            throw new GitException(ERROR_PULL_MERGING);
        }
        String fullBranch = repository.getFullBranch();
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
        }

        String branch = fullBranch.substring(Constants.R_HEADS.length());

        StoredConfig config = repository.getConfig();
        if (remoteName == null) {
            remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_REMOTE);
            if (remoteName == null) {
                remoteName = Constants.DEFAULT_REMOTE_NAME;
            }
        }
        remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
                ConfigConstants.CONFIG_KEY_URL);

        String remoteBranch;
        RefSpec fetchRefSpecs = null;
        String refSpec = request.getRefSpec();
        if (refSpec != null) {
            fetchRefSpecs = (refSpec.indexOf(':') < 0) //
                    ? new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) //
                    : new RefSpec(refSpec);
            remoteBranch = fetchRefSpecs.getSource();
        } else {
            remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_MERGE);
        }

        if (remoteBranch == null) {
            remoteBranch = fullBranch;
        }

        FetchCommand fetchCommand = getGit().fetch();
        fetchCommand.setRemote(remoteName);
        if (fetchRefSpecs != null) {
            fetchCommand.setRefSpecs(fetchRefSpecs);
        }
        int timeout = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }

        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand);

        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(String.format(ERROR_PULL_REF_MISSING, remoteBranch));
        }
        org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
        if (mergeResult.getMergeStatus()
                .equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
            return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
        }

        if (mergeResult.getConflicts() != null) {
            StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
            message.append(lineSeparator());
            Map<String, int[][]> allConflicts = mergeResult.getConflicts();
            for (String path : allConflicts.keySet()) {
                message.append(path).append(lineSeparator());
            }
            message.append(ERROR_PULL_AUTO_MERGE_FAILED);
            throw new GitException(message.toString());
        }
    } catch (CheckoutConflictException exception) {
        StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
        message.append(lineSeparator());
        for (String path : exception.getConflictingPaths()) {
            message.append(path).append(lineSeparator());
        }
        message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
        throw new GitException(message.toString(), exception);
    } catch (IOException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else {
            errorMessage = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}

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

License:Open Source License

private void reset(IProgressMonitor monitor) throws CoreException {
    monitor.beginTask(NLS.bind(CoreText.ResetOperation_performingReset, type.toString().toLowerCase(), refName),
            3);//w  w w  .java2  s .c  om

    IProject[] validProjects = null;
    if (type == ResetType.HARD)
        validProjects = ProjectUtil.getValidProjects(repository);
    boolean merging = false;
    if (repository.getRepositoryState().equals(RepositoryState.MERGING)
            || repository.getRepositoryState().equals(RepositoryState.MERGING_RESOLVED))
        merging = true;

    mapObjects();
    monitor.worked(1);

    writeRef();
    monitor.worked(1);

    switch (type) {
    case HARD:
        checkoutIndex();
        monitor.worked(1);
        if (merging)
            resetMerge();
        monitor.worked(1);
        // only refresh if working tree changes
        ProjectUtil.refreshValidProjects(validProjects, new SubProgressMonitor(monitor, 1));
        monitor.worked(1);
        break;

    case MIXED:
        // Change the
        resetIndex();
        monitor.worked(2);
        if (merging)
            resetMerge();
        monitor.worked(1);
        break;

    case SOFT:
        // only change the ref
        monitor.worked(3);
    }
    monitor.done();
}

From source file:org.eclipse.egit.ui.internal.merge.GitMergeEditorInput.java

License:Open Source License

@Override
protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    final Set<IFile> files = new HashSet<IFile>();
    List<IContainer> folders = new ArrayList<IContainer>();
    Set<IProject> projects = new HashSet<IProject>();

    // collect all projects and sort the selected
    // resources into files and folders; skip
    // ignored resources
    for (IResource res : resources) {
        projects.add(res.getProject());/*from  w  w w .j  av a 2 s .  com*/
        if (Team.isIgnoredHint(res))
            continue;
        if (res.getType() == IResource.FILE)
            files.add((IFile) res);
        else
            folders.add((IContainer) res);
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // make sure all resources belong to the same repository
    Repository repo = null;
    for (IProject project : projects) {
        RepositoryMapping map = RepositoryMapping.getMapping(project);
        if (repo != null && repo != map.getRepository())
            throw new InvocationTargetException(
                    new IllegalStateException(UIText.AbstractHistoryCommanndHandler_NoUniqueRepository));
        repo = map.getRepository();
    }

    if (repo == null)
        throw new InvocationTargetException(
                new IllegalStateException(UIText.AbstractHistoryCommanndHandler_NoUniqueRepository));

    if (monitor.isCanceled())
        throw new InterruptedException();

    // collect all file children of the selected folders
    IResourceVisitor fileCollector = new IResourceVisitor() {
        public boolean visit(IResource resource) throws CoreException {
            if (Team.isIgnoredHint(resource))
                return false;
            if (resource.getType() == IResource.FILE) {
                files.add((IFile) resource);
            }
            return true;
        }
    };

    for (IContainer cont : folders) {
        try {
            cont.accept(fileCollector);
        } catch (CoreException e) {
            // ignore here
        }
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // our root node
    this.compareResult = new DiffNode(Differencer.CONFLICTING);

    final RevWalk rw = new RevWalk(repo);

    // get the "right" side (MERGE_HEAD for merge, ORIG_HEAD for rebase)
    final RevCommit rightCommit;
    try {
        String target;
        if (repo.getRepositoryState().equals(RepositoryState.MERGING))
            target = Constants.MERGE_HEAD;
        else if (repo.getRepositoryState().equals(RepositoryState.REBASING_INTERACTIVE))
            target = readFile(repo.getDirectory(),
                    RebaseCommand.REBASE_MERGE + File.separatorChar + RebaseCommand.STOPPED_SHA);
        else
            target = Constants.ORIG_HEAD;
        ObjectId mergeHead = repo.resolve(target);
        if (mergeHead == null)
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, target));
        rightCommit = rw.parseCommit(mergeHead);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    // we need the HEAD, also to determine the common
    // ancestor
    final RevCommit headCommit;
    try {
        ObjectId head = repo.resolve(Constants.HEAD);
        if (head == null)
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, Constants.HEAD));
        headCommit = rw.parseCommit(head);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    final String fullBranch;
    try {
        fullBranch = repo.getFullBranch();
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    // try to obtain the common ancestor
    List<RevCommit> startPoints = new ArrayList<RevCommit>();
    rw.setRevFilter(RevFilter.MERGE_BASE);
    startPoints.add(rightCommit);
    startPoints.add(headCommit);
    RevCommit ancestorCommit;
    try {
        rw.markStart(startPoints);
        ancestorCommit = rw.next();
    } catch (Exception e) {
        ancestorCommit = null;
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // set the labels
    CompareConfiguration config = getCompareConfiguration();
    config.setRightLabel(NLS.bind(LABELPATTERN, rightCommit.getShortMessage(), rightCommit.name()));

    if (!useWorkspace)
        config.setLeftLabel(NLS.bind(LABELPATTERN, headCommit.getShortMessage(), headCommit.name()));
    else
        config.setLeftLabel(UIText.GitMergeEditorInput_WorkspaceHeader);

    if (ancestorCommit != null)
        config.setAncestorLabel(
                NLS.bind(LABELPATTERN, ancestorCommit.getShortMessage(), ancestorCommit.name()));

    // set title and icon
    setTitle(NLS.bind(UIText.GitMergeEditorInput_MergeEditorTitle,
            new Object[] { Activator.getDefault().getRepositoryUtil().getRepositoryName(repo),
                    rightCommit.getShortMessage(), fullBranch }));

    // now we calculate the nodes containing the compare information
    try {
        for (IFile file : files) {
            if (monitor.isCanceled())
                throw new InterruptedException();

            monitor.setTaskName(file.getFullPath().toString());

            RepositoryMapping map = RepositoryMapping.getMapping(file);
            String gitPath = map.getRepoRelativePath(file);
            if (gitPath == null)
                continue;

            // ignore everything in .git
            if (gitPath.startsWith(Constants.DOT_GIT))
                continue;

            fileToDiffNode(file, gitPath, map, this.compareResult, rightCommit, headCommit, ancestorCommit, rw,
                    monitor);
        }
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
    return compareResult;
}

From source file:org.eclipse.emf.compare.egit.ui.internal.merge.ModelGitMergeEditorInput.java

License:Open Source License

private RevCommit getRightCommit(RevWalk revWalk, Repository repository) throws InvocationTargetException {
    try {/*from w w  w . ja v a  2s.co m*/
        String target;
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            target = Constants.MERGE_HEAD;
        } else if (repository.getRepositoryState().equals(RepositoryState.CHERRY_PICKING)) {
            target = Constants.CHERRY_PICK_HEAD;
        } else if (repository.getRepositoryState().equals(RepositoryState.REBASING_INTERACTIVE)) {
            target = readFile(repository.getDirectory(),
                    RebaseCommand.REBASE_MERGE + File.separatorChar + RebaseCommand.STOPPED_SHA);
        } else {
            target = Constants.ORIG_HEAD;
        }
        ObjectId mergeHead = repository.resolve(target);
        if (mergeHead == null) {
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, target));
        }
        return revWalk.parseCommit(mergeHead);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
}

From source file:org.eclipse.emf.compare.git.pgm.internal.cmd.LogicalMergeCommand.java

License:Open Source License

/**
 * {@inheritDoc}//from  w w  w  .ja  va2s  .co m
 * 
 * @see org.eclipse.emf.compare.git.pgm.internal.cmd.AbstractLogicalCommand#run()
 */
@Override
protected Integer internalRun() throws Die {
    // Checks we are not already in a conflict state
    // Checks that the repository is in conflict state
    if (getRepository().getRepositoryState() == RepositoryState.MERGING) {
        StringBuilder message = new StringBuilder(
                "error: 'merge' is not possible because you have unmerged files.").append(EOL);
        message.append("hint: Use the logicalmergetool command to fix them up un the work tree").append(EOL);
        message.append("hint: and then use the 'git add/rm <file>' as").append(EOL);
        message.append("hint: appropriate to mark resolution").append(EOL);
        System.out.println(message);
        throw new DiesOn(DeathType.FATAL).displaying("Exiting because of an unresolved conflict.").ready();
    }

    OS os = getPerformer().getOS();

    if (!os.isCurrent()) {
        return Returns.ERROR.code();
    }

    try {
        out().println("Launching the installed product...");
    } catch (IOException e) {
        throw new DiesOn(DeathType.FATAL).duedTo(e).ready();
    }

    String setupFileAbsolutePath = this.getSetupFile().getAbsolutePath();
    String setupFileBasePath = Paths.get(setupFileAbsolutePath).getParent().toString();

    String eclipseDir = os.getEclipseDir();
    String eclipseExecutable = os.getEclipseExecutable();
    File eclipseFile = EMFCompareGitPGMUtil.toFileWithAbsolutePath(setupFileBasePath, Paths
            .get(getPerformer().getInstallationLocation().getPath(), eclipseDir, eclipseExecutable).toString());

    List<String> command = new ArrayList<String>();
    command.add(eclipseFile.toString());
    command.add("-nosplash"); //$NON-NLS-1$
    command.add("--launcher.suppressErrors"); //$NON-NLS-1$
    command.add("-application"); //$NON-NLS-1$
    command.add("emf.compare.git.logicalmerge"); //$NON-NLS-1$

    // Propagates the show stack trace option to the application.
    if (isShowStackTrace()) {
        command.add(SHOW_STACK_TRACE_OPT);
    }

    command.add(getRepository().getDirectory().getAbsolutePath());

    command.add(setupFileAbsolutePath);

    if (commit != null) {
        command.add(commit.name());
    } else {
        command.add("HEAD"); //$NON-NLS-1$
    }

    if (message != null) {
        command.add("-m"); //$NON-NLS-1$
        command.add(message);
    }

    if (getPerformer().getWorkspaceLocation() != null) {
        command.add("-data"); //$NON-NLS-1$
        command.add(getPerformer().getWorkspaceLocation().toString());
    }

    command.add("-vmargs"); //$NON-NLS-1$
    command.add("-D" + PROP_SETUP_CONFIRM_SKIP + "=true"); //$NON-NLS-1$ //$NON-NLS-2$
    command.add("-D" + PROP_SETUP_OFFLINE_STARTUP + "=" + false); //$NON-NLS-1$ //$NON-NLS-2$
    command.add("-D" + PROP_SETUP_MIRRORS_STARTUP + "=" + true); //$NON-NLS-1$ //$NON-NLS-2$
    if (debug) {
        command.add("-Xdebug"); //$NON-NLS-1$
        command.add("-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8123"); //$NON-NLS-1$
    }

    ProcessBuilder builder = new ProcessBuilder(command);
    Process process;
    try {
        process = builder.start();
    } catch (IOException e) {
        throw new DiesOn(DeathType.FATAL).duedTo(e).ready();
    }

    // output both stdout and stderr data from proc to stdout of this
    // process
    StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
    StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
    new Thread(errorGobbler).start();
    new Thread(outputGobbler).start();

    int returnValue;
    try {
        returnValue = process.waitFor();
    } catch (InterruptedException e) {
        throw new DiesOn(DeathType.FATAL).duedTo(e).ready();
    }

    return Returns.valueOf(returnValue).code();
}

From source file:org.eclipse.emf.compare.git.pgm.internal.cmd.LogicalMergeToolCommand.java

License:Open Source License

/**
 * {@inheritDoc}//from w ww.ja v  a2 s .  c o m
 * 
 * @see org.eclipse.emf.compare.git.pgm.internal.cmd.AbstractLogicalCommand#internalRun()
 */
@Override
protected Integer internalRun() throws Die {

    // Checks that the repository is in conflict state
    if (getRepository().getRepositoryState() != RepositoryState.MERGING) {
        throw new DiesOn(DeathType.FATAL).displaying("No conflict to merge").ready();
    }

    OS os = getPerformer().getOS();

    if (!os.isCurrent()) {
        return Returns.ERROR.code();
    }

    try {
        out().println("Launching the installed product...");
    } catch (IOException e) {
        throw new DiesOn(DeathType.FATAL).duedTo(e).ready();
    }

    String eclipseDir = os.getEclipseDir();
    String eclipseExecutable = os.getEclipseExecutable();
    String eclipsePath = new File(getPerformer().getInstallationLocation(),
            eclipseDir + SEP + eclipseExecutable).getAbsolutePath();

    List<String> command = new ArrayList<String>();
    command.add(eclipsePath);

    if (getPerformer().getWorkspaceLocation() != null) {
        command.add("-data"); //$NON-NLS-1$
        command.add(getPerformer().getWorkspaceLocation().toString());
    }

    command.add("-vmargs"); //$NON-NLS-1$
    command.add("-D" + PROP_SETUP_CONFIRM_SKIP + "=true"); //$NON-NLS-1$ //$NON-NLS-2$
    command.add("-D" + PROP_SETUP_OFFLINE_STARTUP + "=" + false); //$NON-NLS-1$ //$NON-NLS-2$
    command.add("-D" + PROP_SETUP_MIRRORS_STARTUP + "=" + true); //$NON-NLS-1$ //$NON-NLS-2$

    ProcessBuilder builder = new ProcessBuilder(command);
    Process process;
    try {
        process = builder.start();
    } catch (IOException e) {
        throw new DiesOn(DeathType.FATAL).duedTo(e).ready();
    }

    // output both stdout and stderr data from proc to stdout of this
    // process
    StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
    StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
    new Thread(errorGobbler).start();
    new Thread(outputGobbler).start();

    int returnValue;
    try {
        returnValue = process.waitFor();
    } catch (InterruptedException e) {
        throw new DiesOn(DeathType.FATAL).duedTo(e).ready();
    }

    return Returns.valueOf(returnValue).code();
}

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

License:Open Source License

/**
 * Find and parse each merge-conflicted file, storing local, remote, and ancestor versions of each file in a cache.
 *
 * @param monitor/*from   w  ww . j  a  v  a  2 s. c om*/
 *
 * @return whether any merge conflicts were found
 * @throws GitAPIException
 *          on JGit-specific problems
 * @throws IOException
 *          on file system problems
 */
public boolean readMergeConflictFiles(IProgressMonitor monitor) throws GitAPIException, IOException {
    RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 100);

    String repoPath = git.getRepository().getWorkTree().getAbsolutePath();
    if (!repoPath.endsWith(java.io.File.separator)) { // The documentation does not say if the separator is added...
        repoPath += java.io.File.separator;
    }

    fileToMergePartsMap.clear();
    mergeMapInitialized = true;

    RevWalk walk = null;
    try {
        if (!git.getRepository().getRepositoryState().equals(RepositoryState.MERGING))
            return false;

        subMon.subTask(Messages.JGitRepo_9);
        StatusCommand statusCommand = git.status();
        Status status = statusCommand.call();
        if (status.getConflicting().isEmpty()) {
            return false;
        }
        subMon.worked(30);

        subMon.subTask(Messages.JGitRepo_10);
        walk = new RevWalk(git.getRepository());
        // Get the head, merge head, and merge base commits
        walk.setRevFilter(RevFilter.MERGE_BASE);
        ObjectId headSHA = git.getRepository().resolve("HEAD"); //$NON-NLS-1$
        ObjectId mergeHeadSHA = git.getRepository().resolve("MERGE_HEAD"); //$NON-NLS-1$
        RevCommit head = walk.parseCommit(headSHA);
        RevCommit mergeHead = walk.parseCommit(mergeHeadSHA);
        walk.markStart(head);
        walk.markStart(mergeHead);
        RevCommit mergeBase = walk.next();
        subMon.worked(30);

        // For each merge-conflicted file, pull out and store its contents for each of the three commits
        // Would be much faster to use a treewalk and check whether entry is conflicting instead of using
        // status (which uses a treewalk) and then searching for those status found.
        subMon.subTask(Messages.JGitRepo_11);
        for (String s : status.getConflicting()) {
            String localContents = ""; //$NON-NLS-1$
            TreeWalk localTreeWalk = TreeWalk.forPath(git.getRepository(), s, head.getTree());
            if (localTreeWalk != null) {
                ObjectId localId = localTreeWalk.getObjectId(0);
                localContents = new String(git.getRepository().open(localId).getBytes());
            }

            String remoteContents = ""; //$NON-NLS-1$
            TreeWalk remoteTreeWalk = TreeWalk.forPath(git.getRepository(), s, mergeHead.getTree());
            if (remoteTreeWalk != null) {
                ObjectId remoteId = remoteTreeWalk.getObjectId(0);
                remoteContents = new String(git.getRepository().open(remoteId).getBytes());
            }

            String ancestorContents = ""; //$NON-NLS-1$
            if (mergeBase != null) {
                TreeWalk ancestorTreeWalk = TreeWalk.forPath(git.getRepository(), s, mergeBase.getTree());
                if (ancestorTreeWalk != null) {
                    ObjectId ancestorId = ancestorTreeWalk.getObjectId(0);
                    ancestorContents = new String(git.getRepository().open(ancestorId).getBytes());
                }
            }

            String[] mergeParts = { localContents, remoteContents, ancestorContents };
            fileToMergePartsMap.put(new Path(s), mergeParts);
        }
        subMon.worked(40);
    } finally {
        if (walk != null) {
            walk.dispose();
        }
        if (monitor != null) {
            monitor.done();
        }
    }
    return fileToMergePartsMap.isEmpty();
}

From source file:org.jfrog.bamboo.release.scm.git.ResetCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Reset} command. 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 Ref after reset//from  w  ww.j  a va2  s  .c  o m
 */
@Override
public Ref call() throws GitAPIException {
    checkCallable();

    Ref r;
    RevCommit commit;

    try {
        boolean merging = false;
        if (repo.getRepositoryState().equals(RepositoryState.MERGING)
                || repo.getRepositoryState().equals(RepositoryState.MERGING_RESOLVED)) {
            merging = true;
        }

        // resolve the ref to a commit
        final ObjectId commitId;
        try {
            commitId = repo.resolve(ref);
        } catch (IOException e) {
            throw new JGitInternalException(MessageFormat.format(JGitText.get().cannotRead, ref), e);
        }
        RevWalk rw = new RevWalk(repo);
        try {
            commit = rw.parseCommit(commitId);
        } catch (IOException e) {
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().cannotReadCommit, commitId.toString()), e);
        } finally {
            rw.release();
        }

        // write the ref
        final RefUpdate ru = repo.updateRef(Constants.HEAD);
        ru.setNewObjectId(commitId);

        String refName = Repository.shortenRefName(ref);
        String message = "reset --" //$NON-NLS-1$
                + mode.toString().toLowerCase() + " " + refName; //$NON-NLS-1$
        ru.setRefLogMessage(message, false);
        if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
            throw new JGitInternalException(MessageFormat.format(JGitText.get().cannotLock, ru.getName()));
        }

        switch (mode) {
        case HARD:
            checkoutIndex(commit);
            break;
        case MIXED:
            resetIndex(commit);
            break;
        case SOFT: // do nothing, only the ref was changed
            break;
        }

        if (mode != ResetType.SOFT && merging) {
            resetMerge();
        }

        setCallable(false);
        r = ru.getRef();
    } catch (IOException e) {
        throw new JGitInternalException("Error while executing reset command");
    }

    return r;
}