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.eclipse.winery.repository.TestWithGitBackedRepository.java

License:Open Source License

/**
 * Initializes the git repository from https://github.com/winery/test-repository into %TEMP%/test-repository
 *
 * @throws RuntimeException wraps an Exception
 *//*from   w w  w  . j ava 2  s  .  com*/
public TestWithGitBackedRepository() {
    try {
        Path repositoryPath = Paths.get(System.getProperty("java.io.tmpdir")).resolve("test-repository");
        LOGGER.debug("Testing with repository directory {}", repositoryPath);

        if (!Files.exists(repositoryPath)) {
            Files.createDirectory(repositoryPath);
        }

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        if (!Files.exists(repositoryPath.resolve(".git"))) {
            this.git = Git.cloneRepository().setURI("https://github.com/winery/test-repository.git")
                    .setBare(false).setCloneAllBranches(true).setDirectory(repositoryPath.toFile()).call();
        } else {
            Repository gitRepo = builder.setWorkTree(repositoryPath.toFile()).setMustExist(false).build();
            this.git = new Git(gitRepo);
            try {
                this.git.fetch().call();
            } catch (TransportException e) {
                // we ignore it to enable offline testing
                LOGGER.debug("Working in offline mode", e);
            }
        }

        // inject the current path to the repository factory
        FileBasedRepositoryConfiguration fileBasedRepositoryConfiguration = new FileBasedRepositoryConfiguration(
                repositoryPath);
        GitBasedRepositoryConfiguration gitBasedRepositoryConfiguration = new GitBasedRepositoryConfiguration(
                false, fileBasedRepositoryConfiguration);
        RepositoryFactory.reconfigure(gitBasedRepositoryConfiguration);

        this.repository = RepositoryFactory.getRepository();
        LOGGER.debug("Initialized test repository");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.wst.jsdt.bower.core.api.InstallCommand.java

License:Open Source License

/**
 * Downloads the package with the given packageId matching the given range.
 *
 * @param packageId/*w  w  w . j av a 2s  .c  om*/
 *            The package id
 * @param rangeExpression
 *            The range
 * @return The dependencies of the downloaded package
 */
private Map<String, String> download(String packageId, String rangeExpression) {
    Map<String, String> dependencies = new HashMap<String, String>();

    Optional<String> packageUrl = this.getGitUrlFromPackageId(packageId);
    String packageName = this.getNameFromPackageId(packageId);

    if (packageUrl.isPresent() && this.monitor.isPresent() && !this.monitor.get().isCancelled()) {
        if (this.monitor.isPresent()) {
            this.monitor.get().beginTask(I18n.getString(I18nKeys.DOWNLOADING_LABEL, packageName), 10);
        }

        try {
            File tempFile = new File("/tmp"); //$NON-NLS-1$
            final Repository db = FileRepositoryBuilder.create(tempFile);
            Collection<Ref> refs = new Git(db).lsRemote().setRemote(packageUrl.get()).setTags(true).call();

            Optional<Ref> bestMatch = this.findBestMatch(refs, rangeExpression);
            if (bestMatch.isPresent() && outputDirectory.isPresent()) {
                File downloadedDependencyFolder = new File(outputDirectory.get(), packageName);
                if (!downloadedDependencyFolder.exists()) {
                    Git git = Git.cloneRepository().setProgressMonitor(monitor.get()).setURI(packageUrl.get())
                            .setDirectory(downloadedDependencyFolder).setBranch(bestMatch.get().getName())
                            .setBare(false).setNoCheckout(false).call();
                    git.close();

                    File gitFolder = new File(downloadedDependencyFolder, IBowerConstants.GIT_EXTENSION);
                    this.delete(gitFolder);

                    File bowerJsonFile = new File(downloadedDependencyFolder, IBowerConstants.BOWER_JSON);
                    Optional<BowerJson> dependencyBowerJson = this.getBowerJson(bowerJsonFile);
                    if (dependencyBowerJson.isPresent()) {
                        dependencies.putAll(dependencyBowerJson.get().getDependencies());
                    }
                }
            }

            db.close();
        } catch (GitAPIException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (this.monitor.isPresent()) {
            this.monitor.get().endTask();
        }
    }
    return dependencies;
}

From source file:org.exist.git.xquery.Clone.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//from w w w. j  a v  a  2  s. c om
        Git repo = Git.cloneRepository().setFS(FS).setURI(args[0].getStringValue()).setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(args[2].getStringValue(), args[3].getStringValue()))
                .setDirectory(new Resource(args[1].getStringValue())).call();

        if (repo != null)
            return BooleanValue.TRUE;
        else
            return BooleanValue.FALSE;

    } catch (Throwable e) {
        e.printStackTrace();
        throw new XPathException(this, Module.EXGIT001, e);
    }
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public boolean cloneRepository(final ServiceInvocationContext context, List<PathFragment> selectedPath,
        String repositoryUrl, final List<String> selectedBranches, final String remoteName,
        final boolean cloneAllBranches) {
    tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand());

    final URIish uri;
    try {/*from w  w w  .j a va 2 s .  co  m*/
        uri = new URIish(repositoryUrl.trim());
    } catch (URISyntaxException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    }

    @SuppressWarnings("unchecked")
    final Pair<File, Object> node = (Pair<File, Object>) GenericTreeStatefulService
            .getNodeByPathFor(selectedPath, null);

    File gitReposFile = GitPlugin.getInstance().getUtils().getGitRepositoriesFile(node.a);
    final File mainRepo = GitPlugin.getInstance().getUtils()
            .getMainRepositoryFile(new File(gitReposFile, uri.getHumanishName()), true);

    final ProgressMonitor monitor = ProgressMonitor.create(
            GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri),
            context.getCommunicationChannel());
    monitor.beginTask(GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri), 2);

    Job job = new Job(
            MessageFormat.format(GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri), uri)) {
        @Override
        protected IStatus run(IProgressMonitor m) {
            Repository repository = null;
            try {
                CloneCommand cloneRepository = Git.cloneRepository();

                cloneRepository.setNoCheckout(true);
                cloneRepository.setDirectory(mainRepo);
                cloneRepository.setProgressMonitor(new GitProgressMonitor(new SubProgressMonitor(monitor, 1)));
                cloneRepository.setRemote(remoteName);
                cloneRepository.setURI(uri.toString());
                cloneRepository.setTimeout(30);
                cloneRepository.setCloneAllBranches(cloneAllBranches);
                cloneRepository.setCloneSubmodules(false);
                if (selectedBranches.size() > 0) {
                    cloneRepository.setBranchesToClone(selectedBranches);
                }

                Git git = cloneRepository.call();
                repository = git.getRepository();

                // notify clients about changes
                dispatchContentUpdate(node);

                monitor.worked(1);
            } catch (Exception e) {
                if (repository != null)
                    repository.close();
                GitPlugin.getInstance().getUtils().delete(mainRepo.getParentFile());

                if (monitor.isCanceled()) {
                    return Status.OK_STATUS;
                }
                if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) {
                    openLoginWindow();
                    return Status.OK_STATUS;
                }
                logger.debug(GitPlugin.getInstance().getMessage("git.cloneWizard.error",
                        new Object[] { mainRepo.getName() }), e);
                context.getCommunicationChannel()
                        .appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                                CommonPlugin.getInstance().getMessage("error"),
                                GitPlugin.getInstance().getMessage("git.cloneWizard.error",
                                        new Object[] { mainRepo.getName() }),
                                DisplaySimpleMessageClientCommand.ICON_ERROR));

                return Status.CANCEL_STATUS;
            } finally {
                monitor.done();
                if (repository != null) {
                    repository.close();
                }
            }
            return Status.OK_STATUS;
        }
    };
    job.schedule();
    return true;
}

From source file:org.fusesource.fabric.git.http.GitHttpServerRegistrationHandler.java

License:Apache License

private synchronized void registerServlet() {
    try {//from w  w  w  .java2  s .  c om
        HttpContext base = httpService.get().createDefaultHttpContext();
        HttpContext secure = new SecureHttpContext(base, realm, role);
        String basePath = System.getProperty("karaf.data") + File.separator + "git" + File.separator + "servlet"
                + File.separator;
        String fabricGitPath = basePath + "fabric";
        File fabricRoot = new File(fabricGitPath);

        //Only need to clone once. If repo already exists, just skip.
        if (!fabricRoot.exists()) {
            Git localGit = gitService.get().get();
            Git.cloneRepository().setBare(true).setNoCheckout(true).setCloneAllBranches(true)
                    .setDirectory(fabricRoot).setURI(localGit.getRepository().getDirectory().toURI().toString())
                    .call();
        }

        Dictionary<String, Object> initParams = new Hashtable<String, Object>();
        initParams.put("base-path", basePath);
        initParams.put("repository-root", basePath);
        initParams.put("export-all", "true");
        httpService.get().registerServlet("/git", gitServlet, initParams, secure);
        activateComponent();
    } catch (Exception e) {
        FabricException.launderThrowable(e);
    }
}

From source file:org.fusesource.fabric.itests.basic.git.ExternalGitTest.java

License:Apache License

@Test
public void testCreateProfilesMixedWithVersion() throws Exception {
    String testZkProfilebase = "zkprofile";
    String testGitProfilebase = "gitprofile";
    System.err.println(executeCommand("fabric:create -n"));
    //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build();
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());
    assertNotNull(gitRepoUrl);/*ww  w . j  a  v a 2 s  .c  o m*/
    GitUtils.waitForBranchUpdate(getCurator(), "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());

    FabricService fabricService = getFabricService();
    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(git, "1." + v, gitProfile);
            createAndTestProfileInDataStore(git, "1." + v, zkProfile);
        }
    }
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

@Ignore
@Test//from  ww  w. j ava 2s  .  c o  m
public void testCreateProfileInGit() throws Exception {
    String testProfileNameBase = "mytestprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    System.err.println(executeCommand("features:install fabric-git"));
    //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build();
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());
    assertNotNull(gitRepoUrl);
    GitUtils.waitForBranchUpdate(getCurator(), "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, "default").exists());

    //Create test profile
    for (int i = 1; i <= 5; i++) {
        String testProfileName = testProfileNameBase + i;
        createAndTestProfileInGit(git, "1.0", testProfileName);
    }
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

@Ignore
@Test/*from  w w w  . j  a v  a  2  s .  c  o  m*/
public void testCreateProfileInZk() throws Exception {
    String testProfileNameBase = "mytestprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    System.err.println(executeCommand("features:install fabric-git"));
    //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build();
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());
    assertNotNull(gitRepoUrl);
    GitUtils.waitForBranchUpdate(getCurator(), "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, "default").exists());

    FabricService fabricService = getFabricService();
    //Create test profile
    for (int i = 1; i <= 5; i++) {
        String testProfileName = testProfileNameBase + i;
        createAndTestProfileInZooKeeper(git, "1.0", testProfileName);
    }
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

@Ignore
@Test//from   ww  w  . j a va 2 s.  c om
public void testCreateProfilesMixed() throws Exception {
    String testZkProfilebase = "zkprofile-";
    String testGitProfilebase = "gitprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    System.err.println(executeCommand("features:install fabric-git"));
    //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build();
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());
    assertNotNull(gitRepoUrl);
    GitUtils.waitForBranchUpdate(getCurator(), "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, "default").exists());

    FabricService fabricService = getFabricService();
    //Create test profile
    for (int i = 1; i <= 5; i++) {
        String gitProfile = testGitProfilebase + i;
        String zkProfile = testZkProfilebase + i;
        createAndTestProfileInGit(git, "1.0", gitProfile);
        createAndTestProfileInZooKeeper(git, "1.0", zkProfile);
    }
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

@Test
public void testCreateProfilesMixedWithVersion() throws Exception {
    String testZkProfilebase = "zkprofile-";
    String testGitProfilebase = "gitprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    System.err.println(executeCommand("features:install fabric-git"));
    //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build();
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());
    assertNotNull(gitRepoUrl);//from   w  ww .j a  v  a2  s  .  com
    GitUtils.waitForBranchUpdate(getCurator(), "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, "default").exists());

    FabricService fabricService = getFabricService();
    for (int v = 0; v < 3; v++) {
        //Create test profile
        for (int i = 1; i <= 3; i++) {
            String gitProfile = testGitProfilebase + v + "-" + i;
            String zkProfile = testZkProfilebase + v + "-" + i;
            createAndTestProfileInGit(git, "1." + v, gitProfile);
            createAndTestProfileInZooKeeper(git, "1." + v, zkProfile);
        }
    }
}