Example usage for org.eclipse.jgit.api CheckoutCommand setStartPoint

List of usage examples for org.eclipse.jgit.api CheckoutCommand setStartPoint

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CheckoutCommand setStartPoint.

Prototype

public CheckoutCommand setStartPoint(RevCommit startCommit) 

Source Link

Document

Set the commit that should be checked out.

Usage

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

License:Open Source License

/**
 * Returns the conflicting files of the given scenario.
 * /*from  w w  w . j  a  v  a2  s. com*/
 * @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  w w .j a  va  2  s.  c om
    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:ch.sbb.releasetrain.git.GitRepoImpl.java

License:Apache License

private Git checkoutOrCreateBranch(final Git git) {
    try {/*from  w w w  . j a  v  a  2  s .  c  o  m*/
        if (!branch.equals(git.getRepository().getBranch())) {
            CheckoutCommand checkoutCommand = git.checkout().setCreateBranch(true).setName(branch)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);

            if (remoteBranchExists(git)) {
                checkoutCommand.setStartPoint("origin/" + branch);
            }
            checkoutCommand.call();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return git;
}

From source file:com.ejwa.gitdepmavenplugin.DownloaderMojo.java

License:Open Source License

private void checkout(Git git, Pom pom, GitDependency dependency) throws MojoExecutionException {
    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);

    try {//from ww  w.ja v  a 2s  .com
        final Repository repository = git.getRepository();
        final ObjectId rev = repository.resolve(version);
        final RevCommit rc = new RevWalk(repository).parseCommit(rev);
        final CheckoutCommand checkout = git.checkout();

        checkout.setName("maven-gitdep-branch-" + rc.getCommitTime());
        checkout.setStartPoint(rc);
        checkout.setCreateBranch(true);
        checkout.call();

        final Status status = checkout.getResult().getStatus();

        if (status != Status.OK) {
            throw new MojoExecutionException(
                    String.format("Invalid checkout state (%s) of dependency.", status));
        }
    } catch (IOException | InvalidRefNameException | RefAlreadyExistsException | RefNotFoundException ex) {
        throw new MojoExecutionException(String.format("Failed to check out dependency for %s.%s",
                dependency.getGroupId(), dependency.getArtifactId()), ex);
    }
}

From source file:com.ejwa.mavengitdepplugin.DownloaderMojo.java

License:Open Source License

private void checkout(Git git, POM pom, GitDependency dependency) {
    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);

    try {/*  w  w  w . j  av a2 s .co  m*/
        final ObjectId rev = git.getRepository().resolve(version);
        final RevCommit rc = new RevWalk(git.getRepository()).parseCommit(rev);
        final CheckoutCommand checkout = git.checkout();

        checkout.setName("maven-gitdep-branch-" + rc.getCommitTime());
        checkout.setStartPoint(rc);
        checkout.setCreateBranch(true);
        checkout.call();

        final Status status = checkout.getResult().getStatus();

        if (!status.equals(Status.OK)) {
            getLog().error("Status of checkout: " + status);
            throw new IllegalStateException("Invalid checkout state of dependency.");
        }
    } catch (Exception ex) {
        getLog().error(ex);
        throw new IllegalStateException("Failed to check out dependency.");
    }
}

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

License:Apache License

@Override
protected void doExecute() throws BuildException {
    try {//from www.  jav a2  s .c om
        CheckoutCommand checkoutCommand = git.checkout();

        if (createBranch) {
            checkoutCommand.setCreateBranch(true);

            if (trackBranchOnCreate) {
                checkoutCommand.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
            }
        }

        if (!GitTaskUtils.isNullOrBlankString(branchName)) {
            checkoutCommand.setName(branchName);
        }

        if (!GitTaskUtils.isNullOrBlankString(startPoint)) {
            checkoutCommand.setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + startPoint);
        }

        checkoutCommand.call();

        CheckoutResult checkoutResult = checkoutCommand.getResult();

        if (checkoutResult.getStatus().equals(CheckoutResult.Status.CONFLICTS)) {
            String conflicts = checkoutResult.getConflictList().toString();

            throw new GitBuildException(String.format("Conflicts were found:%s.", conflicts));
        } else if (checkoutResult.getStatus().equals(CheckoutResult.Status.NONDELETED)) {
            String undeleted = checkoutResult.getUndeletedList().toString();

            throw new GitBuildException(String.format("Some files could not be deleted:%s.", undeleted));
        }
    } catch (RefAlreadyExistsException e) {
        throw new GitBuildException(
                String.format("Cannot create branch '%s', as it already exists!", branchName), e);
    } catch (RefNotFoundException e) {
        throw new GitBuildException(String.format("The branch '%s' was not found.", branchName), e);
    } catch (InvalidRefNameException e) {
        throw new GitBuildException("An invalid branch name was specified.", e);
    } catch (CheckoutConflictException e) {
        throw new GitBuildException("Some checkout conflicts were found.", e);
    } catch (GitAPIException e) {
        throw new GitBuildException(String.format("Could not checkout branch '%s'.", branchName), e);
    }
}

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

License:Apache License

@Override
public String checkout(String branchName, boolean useBranchNameAsStartPoint, boolean createBranch,
        boolean useForce) {

    CheckoutCommand command = _git.checkout();
    command.setCreateBranch(createBranch);
    command.setForce(useForce);//from   w  w w  .j  a v  a 2s .  c  om
    command.setName(branchName);
    if (useBranchNameAsStartPoint) {
        command.setStartPoint(REFS_REMOTES + branchName);
    }
    Ref ref = null;
    try {
        ref = command.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format("Failed to checkout branch [%s]", branchName), e);
    }

    return ref.getName();
}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java

License:Open Source License

private @Nonnull Git getActiveRepository(Repository repository) throws IOException {
    try {/* w  w w  .  j  a  va 2s .co m*/
        // Clone the bare repository
        File cloneDir = File.createTempFile("clone", "");

        if (cloneDir.exists()) {
            if (cloneDir.isDirectory()) {
                FileUtils.deleteDirectory(cloneDir);
            } else {
                if (!cloneDir.delete()) {
                    throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
                }
            }
        }
        if (!cloneDir.mkdirs()) {
            throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
        }

        String url = repository.getConfig().getString("remote", "origin", "url");
        Git gitClient = Git.cloneRepository().setCloneAllBranches(false)
                .setProgressMonitor(new CloneProgressMonitor(url))
                .setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();

        RemoteRemoveCommand remove = gitClient.remoteRemove();
        remove.setName("origin");
        remove.call();

        RemoteAddCommand add = gitClient.remoteAdd();
        add.setName("origin");
        add.setUri(new URIish(gitSource.getRemote()));
        add.call();

        if (GitUtils.isSshUrl(gitSource.getRemote())) {
            // Get committer info and credentials
            User user = User.current();
            if (user == null) {
                throw new ServiceException.UnauthorizedException("Not authenticated");
            }
            BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);

            // Make sure up-to-date and credentials work
            GitUtils.fetch(repository, privateKey);
        } else {
            FetchCommand fetch = gitClient.fetch();
            fetch.call();
        }

        if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + sourceBranch);
            checkout.setName(sourceBranch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();

            checkout = gitClient.checkout();
            checkout.setName(branch);
            checkout.setCreateBranch(true); // this *should* be a new branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        } else {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + branch);
            checkout.setName(branch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        }

        return gitClient;
    } catch (GitAPIException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
    }
}

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

License:Apache License

@TaskAction
void checkout() {
    final CheckoutCommand cmd = getGit().checkout();
    cmd.setStartPoint(startPoint);
    cmd.setName(branchName);/* w w w.j  a va2s. co  m*/
    cmd.setCreateBranch(createBranch);

    if (!patternSet.getExcludes().isEmpty() || !patternSet.getIncludes().isEmpty()) {
        getSource().visit(new FileVisitor() {
            public void visitDir(FileVisitDetails arg0) {
                visitFile(arg0);
            }

            public void visitFile(FileVisitDetails arg0) {
                cmd.addPath(arg0.getPath());
            }
        });
    }

    try {
        cmd.call();
    } catch (Exception e) {
        throw new GradleException("Problem checking out from repository", e);
    }
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

private boolean checkoutFromRemoteHead(RepositoryContext gitRepoCtx, List<String> paths) {

    boolean checkoutSuccess = false;

    CheckoutCommand checkoutCmd = gitRepoCtx.getGit().checkout();
    for (String path : paths) {
        checkoutCmd.addPath(path);/*from ww  w .j a  v a2s.  c o  m*/
        if (log.isDebugEnabled()) {
            log.debug("Added the file path " + path + " to checkout from the remote repository");
        }
    }
    // specify the start point as the HEAD of remote repository
    checkoutCmd.setStartPoint(GitDeploymentSynchronizerConstants.REMOTES_ORIGIN_MASTER);

    try {
        checkoutCmd.call();
        checkoutSuccess = true;
        log.info("Checked out the conflicting files from the remote repository successfully");

    } catch (GitAPIException e) {
        log.error("Checking out artifacts from index failed", e);
    }

    return checkoutSuccess;
}