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.fabric8.collector.git.GitBuildConfigProcessor.java

License:Apache License

public static void cloneRepo(File projectFolder, String cloneUrl, CredentialsProvider credentialsProvider,
        final File sshPrivateKey, final File sshPublicKey, String remote) {
    // clone the repo!
    boolean cloneAll = false;
    LOG.info("Cloning git repo " + cloneUrl + " into directory " + projectFolder.getAbsolutePath());
    CloneCommand command = Git.cloneRepository();
    GitHelpers.configureCommand(command, credentialsProvider, sshPrivateKey, sshPublicKey);
    command = command.setCredentialsProvider(credentialsProvider).setCloneAllBranches(cloneAll).setURI(cloneUrl)
            .setDirectory(projectFolder).setRemote(remote);

    try {//from w  w  w  .  j  av  a  2 s  .c  o m
        command.call();
    } catch (Throwable e) {
        LOG.error("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage(), e);
        throw new RuntimeException("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage());
    }
}

From source file:io.fabric8.forge.generator.git.GitProvider.java

License:Apache License

public Git cloneRepo(CloneRepoAttributes attributes) throws GitAPIException {
    CloneCommand command = Git.cloneRepository();
    String gitUri = attributes.getUri();

    UserDetails userDetails = attributes.getUserDetails();
    CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider();
    GitUtils.configureCommand(command, credentialsProvider, userDetails.getSshPrivateKey(),
            userDetails.getSshPublicKey());

    command = command.setCredentialsProvider(credentialsProvider).setCloneAllBranches(attributes.isCloneAll())
            .setURI(gitUri).setDirectory(attributes.getDirectory()).setRemote(attributes.getRemote());

    return command.call();
}

From source file:io.fabric8.forge.generator.pipeline.JenkinsPipelineLibrary.java

License:Apache License

public static void cloneRepo(File projectFolder, String cloneUrl, CredentialsProvider credentialsProvider,
        final File sshPrivateKey, final File sshPublicKey, String remote, String tag) {
    StopWatch watch = new StopWatch();

    // clone the repo!
    boolean cloneAll = true;
    LOG.info("Cloning git repo " + cloneUrl + " into directory " + projectFolder.getAbsolutePath()
            + " cloneAllBranches: " + cloneAll);
    CloneCommand command = Git.cloneRepository();
    GitUtils.configureCommand(command, credentialsProvider, sshPrivateKey, sshPublicKey);
    command = command.setCredentialsProvider(credentialsProvider).setCloneAllBranches(cloneAll).setURI(cloneUrl)
            .setDirectory(projectFolder).setRemote(remote);

    try {/*from  w ww  .j  av a  2 s  .com*/
        Git git = command.call();
        if (tag != null) {
            git.checkout().setName(tag).call();
        }
    } catch (Throwable e) {
        LOG.error("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage(), e);
        throw new RuntimeException("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage());
    } finally {
        LOG.debug("cloneRepo took " + watch.taken());
    }
}

From source file:io.fabric8.forge.rest.client.ForgeClientAsserts.java

License:Apache License

/**
 * Asserts that we can git clone the given repository
 *//*w  w  w  . j  a v  a 2  s. c o  m*/
public static Git assertGitCloneRepo(String cloneUrl, File outputFolder) throws GitAPIException, IOException {
    LOG.info("Cloning git repo: " + cloneUrl + " to folder: " + outputFolder);

    Files.recursiveDelete(outputFolder);
    outputFolder.mkdirs();

    CloneCommand command = Git.cloneRepository();
    command = command.setCloneAllBranches(false).setURI(cloneUrl).setDirectory(outputFolder)
            .setRemote("origin");

    Git git;
    try {
        git = command.call();
    } catch (Exception e) {
        LOG.error("Failed to git clone remote repo " + cloneUrl + " due: " + e.getMessage(), e);
        throw e;
    }
    return git;
}

From source file:io.fabric8.forge.rest.main.ProjectFileSystem.java

License:Apache License

public File cloneOrPullProjetFolder(String user, String repositoryName, UserDetails userDetails) {
    File projectFolder = getUserProjectFolder(user, repositoryName);
    File gitFolder = new File(projectFolder, ".git");
    CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider();
    if (!Files.isDirectory(gitFolder) || !Files.isDirectory(projectFolder)) {
        GitRepoClient repoClient = userDetails.createRepoClient();

        // lets clone the git repository!
        RepositoryDTO dto = repositoryCache.getOrFindUserRepository(user, repositoryName, repoClient);
        if (dto == null) {
            throw new NotFoundException(
                    "No repository defined for user: " + user + " and name: " + repositoryName);
        }/*from  w w w .  j  a  va  2 s  . co m*/
        String cloneUrl = dto.getCloneUrl();
        if (Strings.isNullOrBlank(cloneUrl)) {
            throw new NotFoundException(
                    "No cloneUrl defined for user repository: " + user + "/" + repositoryName);
        }

        // clone the repo!
        boolean cloneAll = true;
        LOG.info("Cloning git repo " + cloneUrl + " into directory " + projectFolder.getAbsolutePath()
                + " cloneAllBranches: " + cloneAll);
        CloneCommand command = Git.cloneRepository().setCredentialsProvider(credentialsProvider)
                .setCloneAllBranches(cloneAll).setURI(cloneUrl).setDirectory(projectFolder).setRemote(remote);
        try {
            Git git = command.call();
        } catch (Throwable e) {
            LOG.error("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage(), e);
            throw new RuntimeException("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage());
        }
    } else {
        doPull(gitFolder, credentialsProvider, userDetails.getBranch());
    }
    return projectFolder;
}

From source file:io.fabric8.git.http.GitHttpServerRegistrationHandler.java

License:Apache License

private void registerServlet(Path dataPath, String realm, String role) throws Exception {
    synchronized (gitRemoteUrl) {
        basePath = dataPath.resolve(Paths.get("git", "servlet"));
        Path fabricRepoPath = basePath.resolve("fabric");
        String servletBase = basePath.toFile().getAbsolutePath();

        // Init and clone the local repo.
        File fabricRoot = fabricRepoPath.toFile();
        if (!fabricRoot.exists()) {
            File localRepo = gitDataStore.get().getGit().getRepository().getDirectory();
            git = Git.cloneRepository().setTimeout(10).setBare(true).setNoCheckout(true)
                    .setCloneAllBranches(true).setDirectory(fabricRoot).setURI(localRepo.toURI().toString())
                    .call();/* w ww .j  ava2  s .c  o  m*/
        } else {
            git = Git.open(fabricRoot);
        }

        HttpContext base = httpService.get().createDefaultHttpContext();
        HttpContext secure = new GitSecureHttpContext(base, curator.get(), realm, role);

        Dictionary<String, Object> initParams = new Hashtable<String, Object>();
        initParams.put("base-path", servletBase);
        initParams.put("repository-root", servletBase);
        initParams.put("export-all", "true");
        httpService.get().registerServlet("/git", new FabricGitServlet(git, curator.get()), initParams, secure);
    }
}

From source file:io.fabric8.itests.basic.git.ExternalGitTest.java

License:Apache License

@Test
public void testCreateProfilesMixedWithVersion() throws Exception {
    String testZkProfilebase = "zkprofile";
    String testGitProfilebase = "gitprofile";
    System.out.println(executeCommand("fabric:create -n"));
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext,
            FabricService.class);
    try {/*ww w.  j  ava2  s. c o m*/
        FabricService fabricService = fabricProxy.getService();
        CuratorFramework curator = fabricService.adapt(CuratorFramework.class);

        String gitRepoUrl = GitUtils.getMasterUrl(bundleContext, curator);
        assertNotNull(gitRepoUrl);
        GitUtils.waitForBranchUpdate(curator, "1.0");

        Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo)
                .setCredentialsProvider(getCredentialsProvider()).call();
        Git git = Git.open(testrepo);
        GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0");
        git.fetch().setCredentialsProvider(getCredentialsProvider());
        GitUtils.checkoutBranch(git, "origin", "1.0");

        //Check that the default profile exists
        assertTrue(new File(testrepo, "fabric/profiles/default.profile").exists());

        for (int v = 0; v < 2; v++) {
            //Create test profile
            for (int i = 1; i < 2; i++) {
                String gitProfile = testGitProfilebase + v + "p" + i;
                String zkProfile = testZkProfilebase + v + "p" + i;
                createAndTestProfileInGit(fabricService, curator, git, "1." + v, gitProfile);
                createAndTestProfileInDataStore(fabricService, curator, git, "1." + v, zkProfile);
            }
        }
    } finally {
        fabricProxy.close();
    }
}

From source file:io.fabric8.itests.smoke.embedded.RemoteGitRepositoryTest.java

License:Apache License

@BeforeClass
public static void beforeClass() throws Exception {
    ServiceLocator.awaitService(BootstrapComplete.class);
    Builder<?> builder = CreateEnsembleOptions.builder().agentEnabled(false).clean(true)
            .waitForProvision(false);//from w  w  w.  ja  v a  2  s  .  c o  m
    ServiceLocator.getRequiredService(ZooKeeperClusterBootstrap.class).create(builder.build());

    Path dataPath = ServiceLocator.getRequiredService(RuntimeProperties.class).getDataPath();
    Path localRepoPath = dataPath.resolve(Paths.get("git", "local", "fabric"));
    Path remoteRepoPath = dataPath.resolve(Paths.get("git", "remote", "fabric"));
    remoteRoot = remoteRepoPath.toFile();
    recursiveDelete(remoteRoot.toPath());
    remoteRoot.mkdirs();

    URL remoteUrl = remoteRepoPath.toFile().toURI().toURL();
    git = Git.cloneRepository().setURI(localRepoPath.toFile().toURI().toString()).setDirectory(remoteRoot)
            .setCloneAllBranches(true).setNoCheckout(true).call();

    // Checkout all remote branches
    for (Ref ref : git.branchList().setListMode(ListMode.REMOTE).call()) {
        String refName = ref.getName();
        String startPoint = refName.substring(refName.indexOf("origin"));
        String branchName = refName.substring(refName.lastIndexOf('/') + 1);
        git.checkout().setCreateBranch(true).setName(branchName).setStartPoint(startPoint).call();
    }

    // Verify that we have these branches
    checkoutRequiredBranch("master");
    checkoutRequiredBranch("1.0");

    ConfigurationAdmin configAdmin = ServiceLocator.getRequiredService(ConfigurationAdmin.class);
    Configuration config = configAdmin.getConfiguration(Constants.DATASTORE_PID);
    Dictionary<String, Object> properties = config.getProperties();
    properties.put(Constants.GIT_REMOTE_URL, remoteUrl.toExternalForm());
    config.update(properties);

    // Wait for the configuredUrl to show up the {@link ProfileRegistry}
    ProfileRegistry profileRegistry = ServiceLocator.awaitService(ProfileRegistry.class);
    Map<String, String> dsprops = profileRegistry.getDataStoreProperties();
    while (!dsprops.containsKey(Constants.GIT_REMOTE_URL)) {
        Thread.sleep(200);
        profileRegistry = ServiceLocator.awaitService(ProfileRegistry.class);
        dsprops = profileRegistry.getDataStoreProperties();
    }
}

From source file:io.fabric8.maven.CreateBranchMojo.java

License:Apache License

protected void initGitRepo() throws MojoExecutionException, IOException, GitAPIException {
    buildDir.mkdirs();/*w  w  w.  j a  v a 2s  .c o m*/
    File gitDir = new File(buildDir, ".git");
    if (!gitDir.exists()) {
        String repo = gitUrl;
        if (Strings.isNotBlank(repo)) {
            getLog().info("Cloning git repo " + repo + " into directory " + getGitBuildPathDescription()
                    + " cloneAllBranches: " + cloneAll);
            CloneCommand command = Git.cloneRepository().setCloneAllBranches(cloneAll).setURI(repo)
                    .setDirectory(buildDir).setRemote(remoteName);
            // .setCredentialsProvider(getCredentials()).
            try {
                git = command.call();
                return;
            } catch (Throwable e) {
                getLog().error("Failed to command remote repo " + repo + " due: " + e.getMessage(), e);
                // lets just use an empty repo instead
            }
        } else {
            InitCommand initCommand = Git.init();
            initCommand.setDirectory(buildDir);
            git = initCommand.call();
            getLog().info("Initialised an empty git configuration repo at " + getGitBuildPathDescription());

            // lets add a dummy file
            File readMe = new File(buildDir, "ReadMe.md");
            getLog().info("Generating " + readMe);
            Files.writeToFile(readMe, "fabric8 git repository created by fabric8-maven-plugin at " + new Date(),
                    Charset.forName("UTF-8"));
            git.add().addFilepattern("ReadMe.md").call();
            commit("Initial commit");
        }
        String branch = git.getRepository().getBranch();
        configureBranch(branch);
    } else {
        getLog().info("Reusing existing git repository at " + getGitBuildPathDescription());

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

        git = new Git(repository);
        if (pullOnStartup) {
            doPull();
        } else {
            getLog().info("git pull from remote config repo on startup is disabled");
        }
    }
}

From source file:io.fabric8.maven.HelmMojo.java

License:Apache License

protected void cloneGitRepository(File outputFolder, String gitUrl) {
    File gitFolder = new File(outputFolder, ".git");
    if (Files.isDirectory(gitFolder)) {
        // we could do a pull here but then we'd be doing a pull per maven module
        // so maybe its better to just use maven clean as a way to force a clean updated pull?
    } else {/*from  w w  w.j a v a 2  s.c  o  m*/
        CloneCommand command = Git.cloneRepository();
        command = command.setURI(gitUrl).setDirectory(outputFolder).setRemote(remoteRepoName);

        setupCredentials(command);

        try {
            Git git = command.call();
        } catch (Throwable e) {
            throw new RuntimeException("Failed to clone chart repo " + gitUrl + " due: ", e);
        }
    }
}