Example usage for org.eclipse.jgit.api Git checkout

List of usage examples for org.eclipse.jgit.api Git checkout

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git checkout.

Prototype

public CheckoutCommand checkout() 

Source Link

Document

Return a command object to execute a checkout command

Usage

From source file:com.github.rwhogg.git_vcr.App.java

License:Open Source License

/**
 * Clean up the Git repo/*from w ww.ja v  a  2s .c  o  m*/
 * @param git Git to use
 * @param oldCommit Hash of the commit to return to
 */
private static void cleanupGit(Git git, String oldCommit) {
    try {
        git.reset().setMode(ResetType.HARD).call();
        git.checkout().setName(oldCommit).call();
    } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
        Util.error("there was an checkout conflict!");
    } catch (GitAPIException e) {
        Util.error("there was an unspecified Git API error!");
    }
    git.close();
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloneFunction.java

License:Open Source License

@Nullable
@Override//from w w  w  .  ja  v a2  s. c  o  m
public SkyValue compute(SkyKey skyKey, Environment env) throws RepositoryFunctionException {
    GitRepositoryDescriptor descriptor = (GitRepositoryDescriptor) skyKey.argument();

    Git git = null;
    try {
        if (descriptor.directory.exists()) {
            if (isUpToDate(descriptor)) {
                return new HttpDownloadValue(descriptor.directory);
            }
            try {
                FileSystemUtils.deleteTree(descriptor.directory);
            } catch (IOException e) {
                throw new RepositoryFunctionException(e, Transience.TRANSIENT);
            }
        }
        git = Git.cloneRepository().setURI(descriptor.remote)
                .setCredentialsProvider(new NetRCCredentialsProvider())
                .setDirectory(descriptor.directory.getPathFile()).setCloneSubmodules(false).setNoCheckout(true)
                .setProgressMonitor(new GitProgressMonitor("Cloning " + descriptor.remote, reporter)).call();
        git.checkout().setCreateBranch(true).setName("bazel-checkout").setStartPoint(descriptor.checkout)
                .call();

        // Using CloneCommand.setCloneSubmodules() results in SubmoduleInitCommand and
        // SubmoduleUpdateCommand to be called recursively for all submodules. This is not
        // desirable for repositories, such as github.com/rust-lang/rust-installer, which
        // recursively includes itself as a submodule, which would result in an infinite
        // loop if submodules are cloned recursively. For now, limit submodules to only
        // the first level.
        if (descriptor.initSubmodules && !git.submoduleInit().call().isEmpty()) {
            git.submoduleUpdate()
                    .setProgressMonitor(
                            new GitProgressMonitor("Cloning submodules for " + descriptor.remote, reporter))
                    .call();
        }
    } catch (InvalidRemoteException e) {
        throw new RepositoryFunctionException(new IOException("Invalid Git repository URI: " + e.getMessage()),
                Transience.PERSISTENT);
    } catch (RefNotFoundException | InvalidRefNameException e) {
        throw new RepositoryFunctionException(
                new IOException("Invalid branch, tag, or commit: " + e.getMessage()), Transience.PERSISTENT);
    } catch (GitAPIException e) {
        throw new RepositoryFunctionException(new IOException(e.getMessage()), Transience.TRANSIENT);
    } finally {
        if (git != null) {
            git.close();
        }
    }
    return new HttpDownloadValue(descriptor.directory);
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloner.java

License:Open Source License

public static SkyValue clone(Rule rule, Path outputDirectory, EventHandler eventHandler,
        Map<String, String> clientEnvironment) throws RepositoryFunctionException {
    WorkspaceAttributeMapper mapper = WorkspaceAttributeMapper.of(rule);
    if (mapper.isAttributeValueExplicitlySpecified("commit") == mapper
            .isAttributeValueExplicitlySpecified("tag")) {
        throw new RepositoryFunctionException(
                new EvalException(rule.getLocation(), "One of either commit or tag must be defined"),
                Transience.PERSISTENT);/*  ww w .ja  v a  2s . co  m*/
    }

    GitRepositoryDescriptor descriptor;
    String startingPoint;
    try {
        if (mapper.isAttributeValueExplicitlySpecified("commit")) {
            startingPoint = mapper.get("commit", Type.STRING);
        } else {
            startingPoint = "tags/" + mapper.get("tag", Type.STRING);
        }

        descriptor = new GitRepositoryDescriptor(mapper.get("remote", Type.STRING), startingPoint,
                mapper.get("init_submodules", Type.BOOLEAN), outputDirectory);
    } catch (EvalException e) {
        throw new RepositoryFunctionException(e, Transience.PERSISTENT);
    }

    // Setup proxy if remote is http or https
    if (descriptor.remote != null && Ascii.toLowerCase(descriptor.remote).startsWith("http")) {
        try {
            new ProxyHelper(clientEnvironment).createProxyIfNeeded(new URL(descriptor.remote));
        } catch (IOException ie) {
            throw new RepositoryFunctionException(ie, Transience.TRANSIENT);
        }
    }

    Git git = null;
    try {
        if (descriptor.directory.exists()) {
            if (isUpToDate(descriptor)) {
                return new HttpDownloadValue(descriptor.directory);
            }
            try {
                FileSystemUtils.deleteTree(descriptor.directory);
            } catch (IOException e) {
                throw new RepositoryFunctionException(e, Transience.TRANSIENT);
            }
        }
        git = Git.cloneRepository().setURI(descriptor.remote)
                .setCredentialsProvider(new NetRCCredentialsProvider())
                .setDirectory(descriptor.directory.getPathFile()).setCloneSubmodules(false).setNoCheckout(true)
                .setProgressMonitor(new GitProgressMonitor("Cloning " + descriptor.remote, eventHandler))
                .call();
        git.checkout().setCreateBranch(true).setName("bazel-checkout").setStartPoint(descriptor.checkout)
                .call();

        // Using CloneCommand.setCloneSubmodules() results in SubmoduleInitCommand and
        // SubmoduleUpdateCommand to be called recursively for all submodules. This is not
        // desirable for repositories, such as github.com/rust-lang/rust-installer, which
        // recursively includes itself as a submodule, which would result in an infinite
        // loop if submodules are cloned recursively. For now, limit submodules to only
        // the first level.
        if (descriptor.initSubmodules && !git.submoduleInit().call().isEmpty()) {
            git.submoduleUpdate()
                    .setProgressMonitor(
                            new GitProgressMonitor("Cloning submodules for " + descriptor.remote, eventHandler))
                    .call();
        }
    } catch (InvalidRemoteException e) {
        throw new RepositoryFunctionException(new IOException("Invalid Git repository URI: " + e.getMessage()),
                Transience.PERSISTENT);
    } catch (RefNotFoundException | InvalidRefNameException e) {
        throw new RepositoryFunctionException(
                new IOException("Invalid branch, tag, or commit: " + e.getMessage()), Transience.PERSISTENT);
    } catch (GitAPIException e) {
        // This is a sad attempt to actually get a useful error message out of jGit, which will bury
        // the actual (useful) cause of the exception under several throws.
        StringBuilder errmsg = new StringBuilder();
        errmsg.append(e.getMessage());
        Throwable throwable = e;
        while (throwable.getCause() != null) {
            throwable = throwable.getCause();
            errmsg.append(" caused by " + throwable.getMessage());
        }
        throw new RepositoryFunctionException(new IOException("Error cloning repository: " + errmsg),
                Transience.PERSISTENT);
    } catch (JGitInternalException e) {
        // This is a lame catch-all for jgit throwing RuntimeExceptions all over the place because,
        // as the docs put it, "a lot of exceptions are so low-level that is is unlikely that the
        // caller of the command can handle them effectively." Thanks, jgit.
        throw new RepositoryFunctionException(new IOException(e.getMessage()), Transience.PERSISTENT);
    } finally {
        if (git != null) {
            git.close();
        }
    }
    return new HttpDownloadValue(descriptor.directory);
}

From source file:com.google.gerrit.acceptance.git.GitUtil.java

License:Apache License

public static void checkout(Git git, String name) throws GitAPIException {
    CheckoutCommand checkout = git.checkout();
    checkout.setName(name);//from w w w. j a  v  a 2 s . co m
    checkout.call();
}

From source file:com.googlecode.ounit.GitQuestion.java

License:Open Source License

@Override
protected void fetchQuestion() {
    File cacheDir = new File(WORKDIR, REPO_DIR);
    srcDir = new File(cacheDir, id + "-" + revision);

    if (srcDir.exists()) {
        getLog().debug("Question found in {}", srcDir);
        return;/*  w w w . j  av  a  2 s .  co m*/
    }

    try {
        getLog().debug("Checking out revision {} from {} to {}", new Object[] { revision, cloneDir, srcDir });

        Git git = Git.wrap(new RepositoryBuilder().setMustExist(true)
                .setIndexFile(new File(srcDir, ".gitindex")).setGitDir(cloneDir).setWorkTree(srcDir).build());

        git.checkout().setName(revision).call();
    } catch (Exception e) {
        getLog().error("Error checking out revision " + revision + " from " + cloneDir, e);
        throw new RuntimeException("Failed to fetch question", e);
    }

}

From source file:com.hazelcast.simulator.utils.jars.GitSupport.java

License:Open Source License

private String checkoutRevision(Git git, String revision) throws GitAPIException, IOException {
    resetHard(git);/*from   w ww  .j  a va2 s  .c o  m*/
    git.checkout().setForce(true).setName(revision).setStartPoint(revision).call();
    return git.getRepository().resolve(revision).toObjectId().name();
}

From source file:com.hazelcast.utils.GitUtils.java

License:Open Source License

public static void cleanupBranch(String branchName, Git git) throws GitAPIException {
    git.checkout().setName("master").call();

    if (branchName != null) {
        git.branchDelete().setBranchNames(branchName).setForce(true).call();
    }//from   w  w w .j ava 2 s .com
}

From source file:com.hazelcast.utils.GitUtils.java

License:Open Source License

public static void createBranch(String branchName, Git git, RevCommit commit) throws GitAPIException {
    git.checkout().setCreateBranch(true).setName(branchName).setStartPoint(commit).call();
}

From source file:com.maiereni.sling.sources.git.GitProjectDownloader.java

License:Apache License

@Override
public void doDownloadProject(final Repository repository) throws Exception {
    logger.debug("Download repository: " + repository.getUrl());
    String branchName = "master";
    Git git = getProjectRepository(repository, branchName);
    //Repository repo = git.getRepository();
    List<Ref> branches = git.branchList().call();
    Ref localBranch = null;/*from  w w  w.j  ava  2  s.  c o  m*/
    for (Ref branch : branches) {
        String bn = branch.getName();
        if (bn.equals("refs/heads/" + branchName)) {
            localBranch = branch;
            break;
        }
    }
    if (localBranch == null) {
        listener.notify(repository, "create", "Create branch");
        localBranch = git.checkout().setCreateBranch(true).setName("refs/heads/" + branchName)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + branchName).call();
        logger.debug("Created a local clone of the project repository ");
    } else {
        listener.notify(repository, "update", "Update existing local sources");
        update(git);
    }
}

From source file:com.maiereni.synchronizer.git.utils.GitDownloaderImpl.java

License:Apache License

private GitResults downloadProject(final Git git, final GitProperties properties) throws Exception {
    GitResults ret = new GitResults();
    String refName = REF_HEADS + properties.getBranchName();
    if (StringUtils.isBlank(properties.getBranchName())) {
        refName = REF_HEADS_MASTER;//  w w  w .  j  av  a  2  s.co m
    }
    Ref tagRef = null;
    if (StringUtils.isNotBlank(properties.getTagName())) {
        String compTagName = "refs/tags/" + properties.getTagName();
        List<Ref> tags = git.tagList().call();
        for (Ref tag : tags) {
            String tn = tag.getName();
            if (tn.equals(compTagName)) {
                logger.debug("Download repository from: " + tag.getName());
                refName = tag.getName();
                tagRef = tag;
                break;
            }
        }
    }
    List<Ref> branches = git.branchList().call();
    Ref localBranch = null;
    for (Ref branch : branches) {
        String bn = branch.getName();
        if (bn.equals(REF_HEADS_LOCAL)) {
            localBranch = branch;
            break;
        }
    }
    if (localBranch == null) {
        localBranch = git.checkout().setCreateBranch(true).setName(LOCAL_BRANCH)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setStartPoint(refName).call();
        logger.debug("Created a local clone of the project repository ");
        ret.setCreated(true);
    } else {
        List<Change> updates = update(git, properties, localBranch, tagRef);
        ret.setChanges(updates);
    }
    return ret;
}