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.searchcode.app.jobs.IndexGitRepoJob.java

private RepositoryChanged cloneGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean successful = false;
    Singleton.getLogger().info("Attempting to clone " + repoRemoteLocation);

    try {/* www .jav  a  2  s .  com*/
        CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI(repoRemoteLocation);
        cloneCommand.setDirectory(new File(repoLocations + "/" + repoName + "/"));
        cloneCommand.setCloneAllBranches(true);
        cloneCommand.setBranch(branch);

        if (useCredentials) {
            cloneCommand.setCredentialsProvider(
                    new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        cloneCommand.call();

        successful = true;

    } catch (GitAPIException | InvalidPathException ex) {
        successful = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    RepositoryChanged repositoryChanged = new RepositoryChanged(successful);
    repositoryChanged.setClone(true);

    return repositoryChanged;
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

License:Open Source License

/**
 * Clones the repository from scratch//from  w  w w. j  a  v a  2 s  .com
 */
public RepositoryChanged cloneGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean successful = false;
    Singleton.getLogger().info("Attempting to clone " + repoRemoteLocation);

    Git call = null;

    try {
        CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI(repoRemoteLocation);
        cloneCommand.setDirectory(new File(repoLocations + "/" + repoName + "/"));
        cloneCommand.setCloneAllBranches(true);
        cloneCommand.setBranch(branch);

        if (useCredentials) {
            cloneCommand.setCredentialsProvider(
                    new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        call = cloneCommand.call();
        successful = true;
    } catch (GitAPIException | InvalidPathException ex) {
        successful = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + " cloneGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(call);
    }

    RepositoryChanged repositoryChanged = new RepositoryChanged(successful);
    repositoryChanged.setClone(true);

    return repositoryChanged;
}

From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractor.java

License:Apache License

@PostConstruct
public void openGit() {
    try {//w  w  w. j a  v  a 2s  . co  m
        git = Git.cloneRepository().setDirectory(Files.createTempDirectory("blog-git").toFile())
                .setURI(gitDirectory.getAbsolutePath()).call();
    } catch (IOException | GitAPIException e) {
        throw new IllegalStateException("Could not open Git repository.", e);
    }
}

From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java

License:Apache License

private void initGitAndClone() throws GitAPIException {
    Git.init().setDirectory(cut.gitDirectory).setBare(true).call().close();
    Git.cloneRepository().setURI(cut.gitDirectory.getAbsolutePath()).setDirectory(gitCloneDirectory).call()
            .close();//from w  w  w . j av a 2s. com
}

From source file:com.sillelien.dollar.plugins.pipe.GithubModuleResolver.java

License:Apache License

@NotNull
@Override/* w  ww . j  a  v a  2  s  . co m*/
public <T> Pipeable resolve(@NotNull String uriWithoutScheme, @NotNull T scope) throws Exception {
    logger.debug(uriWithoutScheme);
    String[] githubRepo = uriWithoutScheme.split(":");
    GitHub github = GitHub.connect();
    final String githubUser = githubRepo[0];
    GHRepository repository = github.getUser(githubUser).getRepository(githubRepo[1]);
    final String branch = githubRepo[2].length() > 0 ? githubRepo[2] : "master";
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File dir = new File(BASE_PATH + "/" + githubUser + "/" + githubRepo[1] + "/" + branch);
    dir.mkdirs();

    final File gitDir = new File(dir, ".git");
    if (gitDir.exists()) {
        Repository localRepo = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        PullCommand pull = git.pull();
        pull.call();
    } else {
        Repository localRepo = builder.setGitDir(dir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        CloneCommand clone = Git.cloneRepository();
        clone.setBranch(branch);
        clone.setBare(false);
        clone.setCloneAllBranches(false);
        clone.setDirectory(dir).setURI(repository.getGitTransportUrl());
        //        UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(login, password);
        //        clone.setCredentialsProvider(user);
        clone.call();
    }
    final ClassLoader classLoader;
    String content;
    File mainFile;
    if (githubRepo.length == 4) {
        classLoader = getClass().getClassLoader();
        mainFile = new File(dir, githubRepo[3]);
        content = new String(Files.readAllBytes(mainFile.toPath()));
    } else {
        final File moduleFile = new File(dir, "module.json");
        var module = DollarStatic.$(new String(Files.readAllBytes(moduleFile.toPath())));
        mainFile = new File(dir, module.$("main").$S());
        content = new String(Files.readAllBytes(mainFile.toPath()));
        classLoader = DependencyRetriever.retrieve(
                module.$("dependencies").$list().stream().map(var::toString).collect(Collectors.toList()));
    }
    return (params) -> ((Scope) scope).getDollarParser().inScope(false, "github-module", ((Scope) scope),
            newScope -> {

                final ImmutableMap<var, var> paramMap = params[0].$map();
                for (Map.Entry<var, var> entry : paramMap.entrySet()) {
                    newScope.set(entry.getKey().$S(), entry.getValue(), true, null, null, false, false, false);
                }
                return new DollarParserImpl(((Scope) scope).getDollarParser().options(), classLoader, dir)
                        .parse(newScope, content);
            });
}

From source file:com.smartbear.readyapi.plugin.git.ReadyApiGitIntegrationTest.java

License:EUPL

@Before
public void setUp() throws Exception {
    originalDialogs = UISupport.getDialogs();
    StubbedDialogs dialog = new StubbedDialogs(null);
    UISupport.setDialogs(dialog);/*from   w  w w.  j  a v a 2  s. co m*/

    gitIntegration = new ReadyApiGitIntegration();
    localPath = File.createTempFile("TestGitPlugin", "");
    localPath.delete();
    String remoteUrl = "git@github.com:SmartBear/git-plugin-test-repo.git";
    git = Git.cloneRepository().setURI(remoteUrl).setDirectory(localPath).call();
    dummyProject = mock(WsdlProjectPro.class);
    when(dummyProject.getPath()).thenReturn(localPath.getAbsolutePath());
    ReadyTools.deleteDirectoryOnExit(localPath);
}

From source file:com.smartbear.readyapi.plugin.git.ReadyApiGitIntegrationTest.java

License:EUPL

private WsdlProjectPro cloneNewRepo(File path) throws Exception {
    String remoteUrl = "git@github.com:SmartBear/git-plugin-test-repo.git";
    path.delete();//from  w  w w  .  j  a va  2  s.c  o  m
    Git.cloneRepository().setURI(remoteUrl).setDirectory(path).call();
    WsdlProjectPro dummyProject = mock(WsdlProjectPro.class);
    when(dummyProject.getPath()).thenReturn(path.getAbsolutePath());
    return dummyProject;
}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public String cloneRemoteRepository(String uri) throws GitManagerException {

    SshSessionFactory.setInstance(new JschConfigSessionFactory() {

        @Override/*from  ww w .  ja v a2  s.  com*/
        protected void configure(Host hc, Session session) {

            try {

                session.setConfig("StrictHostKeyChecking", "no");

                String keyLocation = RemoteUser.get().getSetting(UserSettings.SSH_HOME) + "/"
                        + RemoteUser.get().getUserName();
                String knownHosts = RemoteUser.get().getSetting(UserSettings.SSH_HOME) + "/known_hosts";

                LOG.debug("KeyLoacation " + keyLocation);
                LOG.debug("KnownHosts " + knownHosts);

                JSch jsch = getJSch(hc, FS.DETECTED);
                jsch.addIdentity(keyLocation);
                jsch.setKnownHosts(knownHosts);

            } catch (JSchException e) {
                LOG.error(e);
            }
        }
    });

    CloneCommand cloneCommand = Git.cloneRepository();

    int start = uri.lastIndexOf("/");

    if (start == -1) {
        start = uri.lastIndexOf(":");
    }

    String folder = uri.substring(start + 1, uri.length());

    LOG.info("Cloning : " + uri + " into " + folder);

    cloneCommand
            .setDirectory(new File(RemoteUser.get().getSetting(UserSettings.PROJECT_FOLDER) + "/" + folder));
    cloneCommand.setURI(uri);

    try {

        cloneCommand.call();

    } catch (GitAPIException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }

    return "0";
}

From source file:com.tactfactory.harmony.utils.GitUtils.java

License:Open Source License

/**
 * Clone a git repository./*from  w w  w .j  a v a2  s . c  o m*/
 * @param path Path where the repository will be clone
 * @param url Url of the repository
 * @param branch Branch/Tag to checkout after clone, can be null
 * @throws GitException
 */
public static void cloneRepository(String path, String url, String branch) throws GitException {
    CloneCommand command = Git.cloneRepository().setProgressMonitor(new GitMonitor()).setURI(url)
            .setDirectory(new File(path));

    if (!Strings.isNullOrEmpty(branch)) {
        command.setBranch(branch);
    }

    try {
        command.call().close();
    } catch (InvalidRemoteException e) {
        throw new GitException(e);
    } catch (TransportException e) {
        throw new GitException(e);
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}

From source file:com.tasktop.c2c.server.internal.profile.service.template.GitServiceCloner.java

License:Open Source License

private void copyRepo(ScmRepository scmRepo, CloneContext context)
        throws IOException, JGitInternalException, GitAPIException {

    File workDirectory = null;//  ww w.j av a2 s .co  m
    try {
        Project templateProject = context.getTemplateService().getProjectServiceProfile().getProject();
        String cloneUrl = jgitProvider.computeRepositoryUrl(templateProject.getIdentifier(), scmRepo.getName());

        AuthUtils.assumeSystemIdentity(templateProject.getIdentifier());
        tenancyManager.establishTenancyContext(context.getTemplateService());

        workDirectory = createTempDirectory();
        Git git = Git.cloneRepository().setDirectory(workDirectory)
                .setBranch(Constants.R_HEADS + Constants.MASTER).setURI(cloneUrl).call();

        AuthUtils.assumeSystemIdentity(
                context.getTargetService().getProjectServiceProfile().getProject().getIdentifier());
        tenancyManager.establishTenancyContext(context.getTargetService());

        FileUtils.deleteDirectory(git.getRepository().getDirectory());

        git = Git.init().setDirectory(git.getRepository().getDirectory().getParentFile()).call();

        maybeRewriteRepo(workDirectory, context);

        String pushUrl = jgitProvider.computeRepositoryUrl(
                context.getTargetService().getProjectServiceProfile().getProject().getIdentifier(),
                scmRepo.getName());

        // FIXME: User's locale is not defined here
        String commitMessage = messageSource.getMessage("project.template.git.commitMessage",
                new Object[] { templateProject.getName() }, null);

        git.add().addFilepattern(".").call();
        git.commit().setCommitter(committerName, committerEmail).setMessage(commitMessage).call();
        git.getRepository().getConfig().setString("remote", "target", "url", pushUrl);
        git.push().setRemote("target").setPushAll().call();
    } finally {
        if (workDirectory != null) {
            FileUtils.deleteDirectory(workDirectory);
        }
    }
}