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:io.macgyver.plugin.git.GitResourceProvider.java

License:Apache License

public synchronized void ensureLocalClone() throws IOException {
    GitRepository gitRepository = getGitRepository();
    try {/*from  w w w  .  j a v a 2  s . c om*/
        if (git != null) {
            return;
        }
        File dir = Files.createTempDir();

        logger.info("cloning {} into {}", gitRepository.getUrl(), dir);

        CloneCommand cc = Git.cloneRepository().setURI(gitRepository.getUrl()).setBare(true).setDirectory(dir)
                .setCloneAllBranches(true);

        if ((!Strings.isNullOrEmpty(gitRepository.getUsername()))
                || (!Strings.isNullOrEmpty(gitRepository.getPassword()))) {
            cc = cc.setCredentialsProvider(
                    new UsernamePasswordCredentialsProvider(Strings.nullToEmpty(gitRepository.getUsername()),
                            Strings.nullToEmpty(gitRepository.getPassword())));
        }
        git = cc.call();
        repo = git.getRepository();

    } catch (GitAPIException e) {
        throw new IOException(e);
    }

}

From source file:io.openshift.launchpad.catalog.BoosterCatalogService.java

License:Open Source License

/**
 * Clones the catalog git repository and reads the obsidian metadata on each quickstart repository
 *///from ww  w  .j  a va2  s  . c o  m
private void index() {
    WriteLock lock = reentrantLock.writeLock();
    try {
        lock.lock();
        String catalogRepositoryURI = getEnvVarOrSysProp(CATALOG_GIT_REPOSITORY_PROPERTY_NAME,
                DEFAULT_GIT_REPOSITORY_URL);
        String catalogRef = getEnvVarOrSysProp(CATALOG_GIT_REF_PROPERTY_NAME, DEFAULT_GIT_REF);
        logger.log(Level.INFO, "Indexing contents from {0} using {1} ref",
                new Object[] { catalogRepositoryURI, catalogRef });
        Path catalogPath = Files.createTempDirectory("booster-catalog");
        // Remove this directory on JVM termination
        catalogPath.toFile().deleteOnExit();
        logger.info(() -> "Created " + catalogPath);
        // Clone repository
        Git.cloneRepository().setURI(catalogRepositoryURI).setBranch(catalogRef).setCloneSubmodules(true)
                .setDirectory(catalogPath.toFile()).call().close();
        this.boosters = indexBoosters(catalogPath);
    } catch (GitAPIException e) {
        logger.log(Level.SEVERE, "Error while performing Git operation", e);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while indexing", e);
    } finally {
        logger.info(() -> "Finished content indexing");
        lock.unlock();
    }
}

From source file:io.openshift.launchpad.catalog.BoosterCatalogService.java

License:Open Source License

/**
 * Takes a YAML file from the repository and indexes it
 * /* ww w  .j av  a 2 s.  c o m*/
 * @param file A YAML file from the booster-catalog repository
 * @return an {@link Optional} containing a {@link Booster}
 */
@SuppressWarnings("unchecked")
private Optional<Booster> indexBooster(String id, Path file, Path moduleDir, Map<String, Mission> missions,
        Map<String, Runtime> runtimes) {
    logger.info(() -> "Indexing " + file + " ...");

    Booster booster = null;
    try (BufferedReader reader = Files.newBufferedReader(file)) {
        // Read YAML entry
        booster = yaml.loadAs(reader, Booster.class);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Error while reading " + file, e);
    }
    if (booster != null) {
        try {
            // Booster ID = filename without extension
            booster.setId(id);

            String runtimeId = file.getParent().toFile().getName();
            String missionId = file.getParent().getParent().toFile().getName();

            booster.setMission(missions.computeIfAbsent(missionId, (key) -> {
                ResourceBundle bundle = ResourceBundle.getBundle("missions", Locale.getDefault(),
                        getClass().getClassLoader());
                String name;
                try {
                    name = bundle.getString(key);
                } catch (MissingResourceException mre) {
                    name = key;
                }
                return new Mission(key, name);
            }));

            booster.setRuntime(runtimes.computeIfAbsent(runtimeId, (key) -> {
                ResourceBundle bundle = ResourceBundle.getBundle("runtimes", Locale.getDefault(),
                        getClass().getClassLoader());
                String name;
                try {
                    name = bundle.getString(key);
                } catch (MissingResourceException mre) {
                    name = key;
                }
                return new Runtime(key, name);
            }));

            booster.setContentPath(moduleDir);
            // Module does not exist. Clone it
            if (Files.notExists(moduleDir)) {
                try (Git git = Git.cloneRepository().setDirectory(moduleDir.toFile())
                        .setURI(GITHUB_URL + booster.getGithubRepo()).setCloneSubmodules(true)
                        .setBranch(booster.getGitRef()).call()) {
                    // Checkout on specified start point
                    git.checkout().setName(booster.getGitRef()).setStartPoint(booster.getGitRef()).call();
                }
            }
            Path metadataPath = moduleDir.resolve(booster.getBoosterDescriptorPath());
            try (BufferedReader metadataReader = Files.newBufferedReader(metadataPath)) {
                Map<String, Object> metadata = yaml.loadAs(metadataReader, Map.class);
                booster.setMetadata(metadata);
            }

            Path descriptionPath = moduleDir.resolve(booster.getBoosterDescriptionPath());
            if (Files.exists(descriptionPath)) {
                byte[] descriptionContent = Files.readAllBytes(descriptionPath);
                booster.setDescription(new String(descriptionContent));
            }
        } catch (GitAPIException gitException) {
            logger.log(Level.SEVERE, "Error while reading git repository", gitException);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error while reading metadata from " + file, e);
        }
    }
    return Optional.ofNullable(booster);
}

From source file:io.syndesis.git.GitWorkflow.java

License:Apache License

/**
 * Updates an existing git repository with the current version of project files.
 *
 * @param remoteGitRepoHttpUrl- the HTML (not ssh) url to a git repository
 * @param repoName              - the name of the git repository
 * @param author                author/*w  w w  .j  a v  a 2 s.c  om*/
 * @param message-              commit message
 * @param files-                map of file paths along with their content
 * @param credentials-          Git credentials, for example username/password, authToken, personal access token
 */
public void updateFiles(String remoteGitRepoHttpUrl, String repoName, User author, String message,
        Map<String, byte[]> files, UsernamePasswordCredentialsProvider credentials) {

    // create temporary directory
    try {
        Path workingDir = Files.createTempDirectory(Paths.get(gitProperties.getLocalGitRepoPath()), repoName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created temporary directory {}", workingDir.toString());
        }

        // git clone
        Git git = Git.cloneRepository().setDirectory(workingDir.toFile()).setURI(remoteGitRepoHttpUrl).call();
        writeFiles(workingDir, files);

        commitAndPush(git, authorName(author), author.getEmail(), message, credentials);
        removeWorkingDir(workingDir);
    } catch (IOException | GitAPIException e) {
        throw SyndesisServerException.launderThrowable(e);
    }
}

From source file:io.syndesis.github.GitHubServiceITCase.java

License:Apache License

@Test
public void testProjectCommit() throws IOException, IllegalStateException, GitAPIException, URISyntaxException {
    URL url = this.getClass().getResource(PROJECT_DIR);
    System.out.println("Reading sample project from " + url);
    //Read from classpath sample-github-project into map
    Map<String, byte[]> files = new HashMap<>();
    Files.find(Paths.get(url.getPath()), Integer.MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile())
            .forEach(filePath -> {// w  w  w .j  ava 2  s  .  c  o m
                if (!filePath.startsWith(".git")) {
                    byte[] content;
                    try {
                        content = Files.readAllBytes(filePath);
                        String file = filePath.toString()
                                .substring(filePath.toString().indexOf(PROJECT_DIR) + PROJECT_DIR.length() + 1);
                        files.put(file, content);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

    User user = githubService.getApiUser();
    String cloneURL = githubService.createOrUpdateProjectFiles(REPO_NAME, user,
            "my itcase initial message" + UUID.randomUUID().toString(), files, null);
    Assertions.assertThat(cloneURL).isNotNull().isNotBlank();

    File tmpDir = Files.createTempDirectory(testName.getMethodName()).toFile();
    tmpDir.deleteOnExit();
    Git clone = Git.cloneRepository().setDirectory(tmpDir).setURI(cloneURL).call();
    PersonIdent author = clone.log().call().iterator().next().getAuthorIdent();
    Assertions.assertThat(author).isNotNull();
    Assertions.assertThat(author.getName()).isNotNull().isNotBlank();
}

From source file:io.verticle.apex.commons.oss.repository.GitRepositoryService.java

License:Apache License

private Git cloneToLocalDir() throws GitAPIException {
    CloneCommand cloneCommand = Git.cloneRepository().setURI(remoteRepositoryUri)
            .setDirectory(localRepositoryPath.toFile());

    if (remoteRepositoryUsername != null) {
        cloneCommand.setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(remoteRepositoryUsername, remoteRepositoryPassword));
    }//from w  w  w .  j a  v  a  2 s .  c  om
    this.setTimeout(cloneCommand);

    return cloneCommand.call();
}

From source file:io.vertx.config.git.GitConfigStore.java

License:Apache License

private Git initializeGit() throws IOException, GitAPIException {
    if (path.isDirectory()) {
        Git git = Git.open(path);//from  w  w  w . j av a 2 s  .  c  om
        String current = git.getRepository().getBranch();
        if (branch.equalsIgnoreCase(current)) {
            PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider)
                    .setTransportConfigCallback(transportConfigCallback).call();
            if (!pull.isSuccessful()) {
                LOGGER.warn("Unable to pull the branch + '" + branch + "' from the remote repository '" + remote
                        + "'");
            }
            return git;
        } else {
            git.checkout().setName(branch).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                    .setStartPoint(remote + "/" + branch).call();
            return git;
        }
    } else {
        return Git.cloneRepository().setURI(url).setBranch(branch).setRemote(remote).setDirectory(path)
                .setCredentialsProvider(credentialProvider).setTransportConfigCallback(transportConfigCallback)
                .call();
    }
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

License:Apache License

private Git connect(File bareRoot, File root) throws MalformedURLException, GitAPIException {
    return Git.cloneRepository().setURI(bareRoot.getAbsolutePath()).setRemote(remote).setDirectory(root).call();
}

From source file:io.vertx.config.git.GitConfigStoreWithGithubTest.java

License:Apache License

private Git connect(File root) throws MalformedURLException, GitAPIException {
    return Git.cloneRepository().setURI(REPO).setRemote(remote).setDirectory(root).call();
}

From source file:main.Repositories.java

/**
 * Get the files from a given repository on github
 * @param localPath The folder on disk where the files will be placed
 * @param location The username/repository identification. We'd
 * expect something like triplecheck/reporter
 *///  w  ww.  j a  va2  s.  c  om
public void download(final File localPath, final String location) {
    // we can't have any older files
    files.deleteDir(localPath);
    final String REMOTE_URL = "https://github.com/" + location + ".git";
    try {

        Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call();

        // now open the created repository
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(localPath).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        System.out.println("Downloaded repository: " + repository.getDirectory());

        repository.close();

    } catch (IOException ex) {
        Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex);
    } catch (GitAPIException ex) {
        Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("--> " + location);
}