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

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

Introduction

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

Prototype

public static CloneCommand cloneRepository() 

Source Link

Document

Return a command object to execute a clone command

Usage

From source file:com.gmail.cjbooms.thesis.pythonappengine.server.git.GitCommandsServiceImpl.java

License:Open Source License

/** Clone a repository from a HTTP location
 * URL should be of the form:/*from ww  w. j  av a 2s . c o m*/
 * "http://github.com/schacon/grack.git"
 *
 * @param filePath
 * @param gitHttpURL
 */
public void cloneRepositoryOverHTTP(String filePath, String gitHttpURL) throws JGitInternalException {
    File directory = new File(filePath);
    CloneCommand command = Git.cloneRepository();
    command.setDirectory(directory);
    command.setURI(gitHttpURL);
    command.call();
}

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

License:Open Source License

@Nullable
@Override//from  w  w w  . j a  v a  2 s  .  c  om
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);//from  ww w .  ja v a  2  s .  c  o 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.gct.idea.appengine.synchronization.SampleSyncTask.java

License:Apache License

private Git cloneGithubRepo() {
    File localRepoDirectory = new File(LOCAL_REPO_PATH);
    if (localRepoDirectory.exists()) {
        try {/*from ww w  . java2s.c om*/
            FileUtils.forceDelete(localRepoDirectory);
        } catch (IOException e) {
            LOG.error("Error deleting " + LOCAL_REPO_PATH, e);
        }
    }

    try {
        Git localGitRepo = Git.cloneRepository().setURI(SAMPLE_LINK).setDirectory(new File(LOCAL_REPO_PATH))
                .call();
        return localGitRepo;
    } catch (GitAPIException e) {
        LOG.error("Error cloning github sample repository: " + SAMPLE_LINK, e);
    }

    return null;
}

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

License:Apache License

public static Git cloneProject(String url) throws GitAPIException, IOException {
    final File gitDir = TempFileUtil.createTempDirectory();
    final CloneCommand cloneCmd = Git.cloneRepository();
    cloneCmd.setURI(url);/*from  ww  w. j  a  v  a  2s .  c om*/
    cloneCmd.setDirectory(gitDir);
    return cloneCmd.call();
}

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

License:Apache License

public static Git cloneProject(String url) throws GitAPIException {
    final File gitDir = TempFileUtil.createTempDirectory();
    final CloneCommand cloneCmd = Git.cloneRepository();
    cloneCmd.setURI(url);//w  w w .j  a va2  s . c  om
    cloneCmd.setDirectory(gitDir);
    return cloneCmd.call();
}

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

License:Open Source License

private void cloneRepo() {
    String url = baseURL + "/" + id;

    getLog().debug("Cloning {} to {}", new Object[] { id, cloneDir });
    try {/*from w  ww . j av a  2s .c  o m*/
        Git.cloneRepository().setBare(true).setDirectory(cloneDir).setTimeout(SCM_TIMEOUT).setURI(url).call();
    } catch (Exception e) {
        getLog().error("Failed to clone question from {} to {}", new Object[] { url, cloneDir });
        deleteDirectory(cloneDir);
        throw new RuntimeException("Failed to clone question repository", e);
    }
    pullTimes.put(id, System.currentTimeMillis());
}

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

License:Open Source License

private Git cloneIfNecessary(File src) throws GitAPIException, IOException {
    Git git;// w  ww  .  java  2  s  .  c  om
    if (!isValidLocalRepository(src)) {
        LOGGER.info("Cloning Hazelcast Git repository to " + src.getAbsolutePath()
                + ". This might take a while...");
        git = Git.cloneRepository().setURI(HAZELCAST_MAIN_REPO_URL).setDirectory(src).call();
    } else {
        git = Git.open(src);
    }
    return git;
}

From source file:com.ibm.liberty.starter.GitHubConnector.java

License:Apache License

/**
 * Creates a repository on GitHub and in a local temporary directory. This is a one time operation as
 * once it is created on GitHub and locally it cannot be recreated.
 *///  ww  w  . j  a v a  2  s  . co  m
public File createGitRepository(String repositoryName) throws IOException {
    RepositoryService service = new RepositoryService();
    service.getClient().setOAuth2Token(oAuthToken);
    Repository repository = new Repository();
    repository.setName(repositoryName);
    repository = service.createRepository(repository);
    repositoryLocation = repository.getHtmlUrl();

    CloneCommand cloneCommand = Git.cloneRepository().setURI(repository.getCloneUrl())
            .setDirectory(localGitDirectory);
    addAuth(cloneCommand);
    try {
        localRepository = cloneCommand.call();
    } catch (GitAPIException e) {
        throw new IOException("Error cloning to local file system", e);
    }
    return localGitDirectory;
}

From source file:com.ivyis.pentaho.ivygs.manager.SettingsManager.java

public boolean setSettings(String gitURL, String gitUserName, String gitPassword,
        InputStream uploadedInputStream, FormDataContentDisposition fileDetail) {
    try {//from  w  w  w.  j  av  a 2  s.c o  m
        if (!"".equalsIgnoreCase(fileDetail.getFileName())) {
            final File etlRepoFile = new File(PentahoSystem.getApplicationContext().getSolutionRootPath()
                    + File.separator + SETTINGS_FOLDER + File.separator + fileDetail.getFileName());
            final File etlRepoFolder = new File(PentahoSystem.getApplicationContext().getSolutionRootPath()
                    + File.separator + SETTINGS_FOLDER + File.separator + "repo");
            rmdir(etlRepoFolder);
            etlRepoFolder.delete();
            if (!etlRepoFolder.exists()) {
                etlRepoFolder.mkdirs();
            }
            writeToFile(uploadedInputStream, etlRepoFile.getAbsolutePath());
            unZipIt(etlRepoFile.getAbsolutePath(), etlRepoFolder.getAbsolutePath());
            etlRepoFile.delete();

            this.settings.setEtlFolderPath(etlRepoFolder.getAbsolutePath());
        }

        // Set settings
        this.settings.setGitURL(gitURL);
        this.settings.setGitUserName(gitUserName);
        this.settings.setGitPassword(gitPassword);
        this.settings.setGitRepoFolderPath(new File(PentahoSystem.getApplicationContext().getSolutionRootPath()
                + File.separator + IVYGS_GIT_REPOS_FOLDER + File.separator + "repo").getAbsolutePath());
        this.settings.setPointCheckout("master");
        saveSettings(this.settings);

        final File gitRepoFolder = new File(this.settings.getGitRepoFolderPath());
        rmdir(gitRepoFolder);
        gitRepoFolder.delete();

        // Clone project
        Git.cloneRepository().setURI(this.settings.getGitURL())
                .setDirectory(new File(this.settings.getGitRepoFolderPath()))
                .setBranch(
                        this.settings.getPointCheckout() == null ? "master" : this.settings.getPointCheckout())
                .setCloneAllBranches(false).setCloneSubmodules(true)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(this.settings.getGitUserName(),
                        this.settings.getGitPassword()))
                .setBare(false).call();
        return true;
    } catch (Exception e) {
        return false;
    }
}