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:org.jboss.tools.openshift.ui.bot.test.common.OpenShiftUtils.java

License:Open Source License

public static void cloneGitRepository(String gitRepoDirectory, String gitRepoUrl, String gitRepoName) {
    TestUtils.cleanupGitFolder(new File(gitRepoDirectory), gitRepoName);
    try {//w  w w  .j  a va2s . c  o m
        Git.cloneRepository().setURI(gitRepoUrl).setDirectory(new File(gitRepoDirectory)).call();
    } catch (GitAPIException e) {
        throw new RuntimeException("Unable to clone git repository from " + gitRepoUrl);
    }

}

From source file:org.jdamico.jgitbkp.components.ManagerComponent.java

License:Open Source License

public void cloneRepos(List<RepoImpl> reposLst, Config config) throws JGitBackupException {

    for (int i = 0; i < reposLst.size(); i++) {

        File f = new File(reposLst.get(i).getClonedPath());

        if (f.mkdir()) {

            try {
                Git.cloneRepository().setCloneAllBranches(true).setCloneSubmodules(true).setNoCheckout(false)
                        .setURI(config.getProtocol() + "://" + config.getHostPath() + "/"
                                + reposLst.get(i).getName())
                        .setCredentialsProvider(
                                new UsernamePasswordCredentialsProvider(config.getUser(), config.getPasswd()))
                        .setDirectory(new File(reposLst.get(i).getClonedPath()))
                        .setProgressMonitor(new TextProgressMonitor()).call();

            } catch (InvalidRemoteException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            } catch (TransportException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            } catch (GitAPIException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            }//from w  w  w. ja  v  a  2s . c om

        } else {
            try {
                Git git = Git.open(f);
                git.pull();
                LoggerManager.getInstance().logAtDebugTime(this.getClass().getName(),
                        "Updating data from repository.");
            } catch (IOException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            }
            String err = "Unable to create directory for clone [" + reposLst.get(i).getName()
                    + "]. Check the path and permissions.";
            if (!f.exists()) {
                if (!Starter.silent)
                    System.out.println(err);
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err);
            }

        }
    }

}

From source file:org.jdamico.jgitbkp.tests.JGitTester.java

License:Open Source License

@Test
public void test() throws IOException, GitAPIException {

    String user = "";
    String passwd = "";
    String hostPath = "/git";
    String backupRoot = "/tmp/test";
    String gitRoot = "/mnt";
    String bundlePath = "/tmp";
    boolean keepOld = false;

    List<org.jdamico.jgitbkp.entities.RepoImpl> repos = new ArrayList<org.jdamico.jgitbkp.entities.RepoImpl>();

    File fGitRoot = new File(gitRoot);
    String[] fRepos = fGitRoot.list();
    for (String itemRepo : fRepos) {
        File fItemRepo = new File(gitRoot + "/" + itemRepo);
        if (fItemRepo.isDirectory() && itemRepo.contains(".git") && !itemRepo.equals(".git")) {
            repos.add(new org.jdamico.jgitbkp.entities.RepoImpl(itemRepo, null, backupRoot + "/" + itemRepo));
        }/*from w w w .  j  a v a  2  s.c  om*/
    }

    for (int i = 0; i < repos.size(); i++) {

        File f = new File(repos.get(i).getClonedPath());

        if (f.mkdir()) {

            Git.cloneRepository().setCloneAllBranches(true)
                    .setURI("http://" + hostPath + "/" + repos.get(i).getName())
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, passwd))
                    .setDirectory(new File(repos.get(i).getClonedPath()))
                    .setProgressMonitor(new TextProgressMonitor()).call();

        }

        File gitWorkDir = new File(repos.get(i).getClonedPath());
        Git git = Git.open(gitWorkDir);
        git.pull();
        Repository localRepoGit = git.getRepository();
        BundleWriter bundleWriter = new BundleWriter(localRepoGit);
        ProgressMonitor pMonitor = new TextProgressMonitor();
        OutputStream oStream = new FileOutputStream(bundlePath + "/" + repos.get(i).getName() + ".bundle");

        Map<String, Ref> allRefs = localRepoGit.getAllRefs();
        Collection<Ref> values = allRefs.values();
        Iterator<Ref> iter = values.iterator();
        while (iter.hasNext()) {
            Ref element = iter.next();
            try {

                bundleWriter.include(element);
                System.out.println("Added: " + element.getName());
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        bundleWriter.writeBundle(pMonitor, oStream);

    }

}

From source file:org.jenkinsci.git.CloneOperation.java

License:Open Source License

public Repository invoke(File file, VirtualChannel channel) throws IOException {
    String directory = repo.getDirectory();
    File gitDir;/*from   w  ww. j a  v  a2  s. c om*/
    if (directory == null || directory.length() == 0 || ".".equals(directory))
        gitDir = file;
    else
        gitDir = new File(file, directory);

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(repo.getUri());
    clone.setCloneAllBranches(false);
    clone.setBranchesToClone(Collections.singletonList(repo.getBranch()));
    clone.setDirectory(gitDir);
    clone.setNoCheckout(true);
    return clone.call().getRepository();
}

From source file:org.jenkinsci.plugins.os_ci.utils.GitClient.java

License:Apache License

public GitClient(String gitFolderName, String puppetRepoUrl, String branch, String fullName,
        BuildListener listener) throws IOException {
    this.listener = listener;
    this.branch = branch;
    final File gitFolder = new File(Joiner.on(File.separator).join(gitFolderName, fullName));
    if (gitFolder == null)
        throw new IOException("gitFolder is null");
    try {//www. jav a  2 s . c  o  m
        gitFolder.mkdir();
        git = Git.cloneRepository().setURI(puppetRepoUrl).setDirectory(gitFolder).call();
        if (git == null)
            throw new IOException("git is null");
        if (branch == null || branch.isEmpty())
            throw new IOException("branch is not defined");
        if (!branch.equalsIgnoreCase(MASTER_BRANCH))
            git.checkout().setName("origin/" + branch).call();
    } catch (InvalidRemoteException e) {
        throw new IOException(e.getMessage());
    } catch (TransportException e) {
        throw new IOException(e.getMessage());
    } catch (GitAPIException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatabilityTestIT.java

/**
 * Git Plugin// w ww  .j  av  a2s . co m
 *
 * Test that show that a ready/feature_1 branch get integrated into master
 * using a Matrix job type.
 *
 * Pretested integration:
 *  - 'Integration branch' : master (default)
 *  - 'Repository name' : origin (default) 
 *  - 'Strategy' : Squash Commit
 *
 * GitSCM:
 *  - 'Name' : (empty)
 *
 * Workflow
 *  - Create a repository containing a 'ready' branch.
 *  - The build is triggered. 
 *
 * Results
 *  - We expect that the plugin triggers, and that the commits on ready branch
 *    is merged into our integration branch master and build result becomes SUCCESS.
 *
 * @throws Exception
 */
@Test
public void oneBuildBasicSmokeTest() throws Exception {
    repository = TestUtilsFactory.createValidRepository("test-repo");

    File workDir = new File("test-repo");

    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();

    Git git = Git.open(workDir);

    System.out.println("Opening git repository in: " + workDir.getAbsolutePath());

    String readmeFromIntegration = FileUtils.readFileToString(new File("test-repo/readme"));

    git.checkout().setName(FEATURE_BRANCH_NAME).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
            .setCreateBranch(true).call();
    final int COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION = TestUtilsFactory.countCommits(git);
    git.checkout().setName("master").setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();

    GitProjectBuilder builder = new GitProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(GitProjectBuilder.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);

    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);

    jenkinsRule.waitUntilNoActivityUpTo(60000);

    assertEquals("2 runs for this particular matrix build", 2, project.getLastBuild().getRuns().size());

    String readmeFileContents = FileUtils.readFileToString(new File("test-repo/readme"));
    assertEquals(readmeFromIntegration, readmeFileContents);

    git.pull().call();

    final int COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION = TestUtilsFactory.countCommits(git);

    git.close();

    //We assert that 2 commits from branch gets merged + 1 combined merge commit since we do --no-ff
    assertEquals(COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION + 3, COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION);
}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatabilityTestIT.java

/**
 * //from   w  w  w.j  ava  2s. c  o  m
 * TODO: How do we solve this one.
 * 
 * We need to test and make our plugin not spawn 2 failed runs if the parent job fails with a merge conflict
 * @throws Exception 
 */
@Test
@Ignore
public void oneBuildBasicMergeFailure() throws Exception {
    repository = TestUtilsFactory.createRepositoryWithMergeConflict("test-repo");

    File workDir = new File("test-repo");

    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();

    GitProjectBuilder builder = new GitProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(GitProjectBuilder.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);

    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);

    jenkinsRule.waitUntilNoActivityUpTo(60000);

    assertEquals("Since merge failed...we should get no child jobs to spawn", 0,
            project.getLastBuild().getRuns().size());
}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatibilityTestIT.java

/**
 * Git Plugin//from   w w  w .  j  av a  2 s.  c  o m
 *
 * Test that show that a ready/feature_1 branch get integrated into master
 * using a Matrix job type.
 *
 * Pretested integration:
 *  - 'Integration branch' : master (default)
 *  - 'Repository name' : origin (default)
 *  - 'Strategy' : Squash Commit
 *
 * GitSCM:
 *  - 'Name' : (empty)
 *
 * Workflow
 *  - Create a repository containing a 'ready' branch.
 *  - The build is triggered.
 *
 * Results
 *  - We expect that the plugin triggers, and that the commits on ready branch
 *    is merged into our integration branch master and build result becomes SUCCESS.
 *
 * @throws Exception
 */

@Test
public void oneBuildBasicSmokeTest() throws Exception {
    repository = TestUtilsFactory.createValidRepository("test-repo");
    File workDir = new File(TestUtilsFactory.WORKDIR, "test-repo");
    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();

    Git git = Git.open(workDir);

    System.out.println("Opening git repository in: " + workDir.getAbsolutePath());

    String readmeFromIntegration = FileUtils.readFileToString(new File(workDir, "readme"));

    git.checkout().setName(FEATURE_BRANCH_NAME).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
            .setCreateBranch(true).call();
    final int COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION = TestUtilsFactory.countCommits(git);
    git.checkout().setName("master").setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();

    MatrixProjectBuilder builder = new MatrixProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(TestUtilsFactory.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);

    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);

    jenkinsRule.waitUntilNoActivityUpTo(60000);

    String readmeFileContents = FileUtils.readFileToString(new File(workDir, "readme"));
    assertEquals(readmeFromIntegration, readmeFileContents);
    git.pull().call();

    assertEquals("3 runs for this particular matrix build", 3, project.getLastBuild().getRuns().size());

    final int COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION = TestUtilsFactory.countCommits(git);
    git.close();
    //We assert that 2 commits from branch gets merged + 1 combined merge commit since we do --no-ff
    assertEquals(COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION + 3, COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION);
}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatibilityTestIT.java

@Test
public void oneBuildBasicMergeFailure() throws Exception {
    repository = TestUtilsFactory.createRepositoryWithMergeConflict("test-repo");
    File workDir = new File(TestUtilsFactory.WORKDIR, "test-repo");
    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();
    MatrixProjectBuilder builder = new MatrixProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(TestUtilsFactory.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);
    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);
    jenkinsRule.waitUntilNoActivityUpTo(60000);
    jenkinsRule.assertBuildStatus(Result.FAILURE, project.getLastBuild());
    assertEquals("3 runs for this particular matrix build", 3, project.getLastBuild().getRuns().size());
}

From source file:org.kaazing.bower.dependency.maven.plugin.UnpackBowerDependencyMojo.java

License:Open Source License

/**
 * Checkouts a git repo//from  w w  w.ja  va  2s .  co m
 * @param outputDir
 * @param gitUrl
 * @return
 * @throws MojoExecutionException
 */
Git checkoutGitRepo(File outputDir, String gitUrl) throws MojoExecutionException {
    outputDir.mkdir();
    try {
        return Git.cloneRepository().setURI(gitUrl).setDirectory(outputDir).call();
    } catch (Exception e) {
        throw new MojoExecutionException("Could not fetch git repository", e);
    }
}