Example usage for org.eclipse.jgit.api CloneCommand setRemote

List of usage examples for org.eclipse.jgit.api CloneCommand setRemote

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CloneCommand setRemote.

Prototype

public CloneCommand setRemote(String remote) 

Source Link

Document

The remote name used to keep track of the upstream repository for the clone operation.

Usage

From source file:com.microsoft.tfs.client.eclipse.ui.egit.importwizard.CloneGitRepositoryCommand.java

License:Open Source License

private boolean cloneRepository(final IProgressMonitor progressMonitor) {
    final CloneCommand cloneRepository = Git.cloneRepository();

    cloneRepository.setCredentialsProvider(credentialsProvider);
    cloneRepository.setProgressMonitor(new CloneProgress(progressMonitor));

    final File workFolder = new File(workingDirectory);
    if (!workFolder.exists()) {
        if (!workFolder.mkdirs()) {
            if (!workFolder.isDirectory()) {
                final String errorMessageFormat = "Cannot create {0} directory"; //$NON-NLS-1$
                throw new RuntimeException(MessageFormat.format(errorMessageFormat, workingDirectory));
            }/*from  w  ww . j a  va 2 s  .c om*/
        }
    }
    cloneRepository.setDirectory(new File(workingDirectory));

    cloneRepository.setRemote(remoteName);
    cloneRepository.setURI(URIUtils.encodeQueryIgnoringPercentCharacters(repositoryUrl.toString()));

    cloneRepository.setCloneAllBranches(true);
    cloneRepository.setBranchesToClone(Arrays.asList(refs));
    cloneRepository.setBranch(defaultRef);

    cloneRepository.setNoCheckout(false);
    cloneRepository.setTimeout(timeout);
    cloneRepository.setCloneSubmodules(cloneSubmodules);

    try {
        cloneRepository.call();
        if (progressMonitor.isCanceled()) {
            throw new CanceledException();
        }

        registerClonedRepository(workingDirectory);
    } catch (final CanceledException e) {
        throw e;
    } catch (final Exception e) {
        logger.error("Error cloning repository:", e); //$NON-NLS-1$
        errorMessage = e.getLocalizedMessage();
        return false;
    }

    return true;
}

From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java

License:Open Source License

/**
 * /*from w w  w .ja  v  a 2  s.  c o  m*/
 * Clones secured git remote repository to the file system.
 * 
 * @param gitDirectory
 *            where the remote repository will be cloned
 * @param repositoryURI
 *            repository's URI example: https://qwerty.com/xyz/abc.git
 * @param username
 *            the username used for authentication
 * @param password
 *            the password used for authentication
 * 
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 */
public static void cloneRepository(File gitDirectory, String repositoryURI, String username, String password)
        throws InvalidRemoteException, TransportException, GitAPIException {
    try {
        CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI(repositoryURI);
        if (!StringUtils.isEmptyOrNull(username) && !StringUtils.isEmptyOrNull(password)) {
            cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
        }
        cloneCommand.setRemote(Constants.DEFAULT_REMOTE_NAME);
        cloneCommand.setDirectory(gitDirectory);
        cloneCommand.call();
    } catch (NullPointerException e) {
        throw new TransportException(INVALID_USERNAME_AND_PASSWORD);
    }
}

From source file:net.mobid.codetraq.runnables.GitChecker.java

License:Open Source License

private void clone(String path) {
    LogService.writeMessage("GitChecker is trying to do a clone from " + _server.getServerAddress());
    System.out.printf("GitChecker is trying to do a clone from %s%n", _server.getServerAddress());
    try {// w  ww . j a v  a  2 s .  c o  m
        File gitDir = new File(path);
        CloneCommand cloner = new CloneCommand();
        cloner.setBare(false);
        cloner.setDirectory(gitDir);
        cloner.setProgressMonitor(new TextProgressMonitor());
        cloner.setRemote("origin");
        cloner.setURI(_server.getServerAddress());
        mGit = cloner.call();
        // for some reason, repository cloned with jgit always has HEAD detached.
        // we need to create a "temporary" branch, then create a "master" branch.
        // we then merge the two...
        if (!isMasterBranchDefined(mGit.getRepository())) {
            // save the remote and merge config values
            mGit.getRepository().getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
                    _server.getServerBranch(), ConfigConstants.CONFIG_KEY_REMOTE, "origin");
            mGit.getRepository().getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
                    _server.getServerBranch(), ConfigConstants.CONFIG_KEY_MERGE, _server.getServerBranch());
            mGit.getRepository().getConfig().save();
        }
        if (mGit.getRepository().getFullBranch() == null
                || Utilities.isHexString(mGit.getRepository().getFullBranch())) {
            // HEAD is detached and we need to reattach it
            attachHead(mGit, _server.getServerBranch());
        }
    } catch (Exception ex) {
        LogService.getLogger(GitChecker.class.getName()).log(Level.SEVERE, null, ex);
        LogService.writeLog(Level.SEVERE, ex);
    }
}

From source file:org.ajoberstar.gradle.git.tasks.GitClone.java

License:Apache License

/**
 * Clones a Git repository as configured.
 *//*from w  w w. j  a v  a  2 s .  com*/
@TaskAction
public void cloneRepo() {
    CloneCommand cmd = Git.cloneRepository();
    TransportAuthUtil.configure(cmd, this);
    cmd.setURI(getUri().toString());
    cmd.setRemote(getRemote());
    cmd.setBare(getBare());
    cmd.setNoCheckout(!getCheckout());
    cmd.setBranch(getRef());
    cmd.setBranchesToClone(getBranchesToClone());
    cmd.setCloneAllBranches(getCloneAllBranches());
    cmd.setDirectory(getDestinationDir());
    try {
        cmd.call();
    } catch (InvalidRemoteException e) {
        throw new GradleException("Invalid remote specified: " + getRemote(), e);
    } catch (TransportException e) {
        throw new GradleException("Problem with transport.", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem with clone.", e);
    }
    //TODO add progress monitor to log progress to Gradle status bar
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static Git cloneRepository(SetupTaskContext context, File workDir, String checkoutBranch,
        String remoteName, String remoteURI, boolean recursive, IProgressMonitor monitor) throws Exception {
    context.log("Cloning Git repo " + remoteURI + " to " + workDir);

    CloneCommand command = Git.cloneRepository();
    command.setNoCheckout(true);/*from w  ww  . j ava2 s.co  m*/
    command.setURI(remoteURI);
    command.setRemote(remoteName);
    command.setBranchesToClone(Collections.singleton(checkoutBranch));
    command.setDirectory(workDir);
    command.setTimeout(60);
    command.setProgressMonitor(new EclipseGitProgressTransformer(monitor));
    return command.call();
}

From source file:org.eclipse.orion.server.git.jobs.CloneJob.java

License:Open Source License

private IStatus doClone() {
    try {// w  w  w .j ava  2  s. c  om
        File cloneFolder = new File(clone.getContentLocation().getPath());
        if (!cloneFolder.exists()) {
            cloneFolder.mkdir();
        }
        CloneCommand cc = Git.cloneRepository();
        cc.setBare(false);
        cc.setCredentialsProvider(credentials);
        cc.setDirectory(cloneFolder);
        cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
        cc.setURI(clone.getUrl());
        Git git = cc.call();

        // Configure the clone, see Bug 337820
        GitCloneHandlerV1.doConfigureClone(git, user);
        git.getRepository().close();
    } catch (IOException e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
        return e.getStatus();
    } catch (GitAPIException e) {
        return getGitAPIExceptionStatus(e, "Error cloning git repository");
    } catch (JGitInternalException e) {
        return getJGitInternalExceptionStatus(e, "Error cloning git repository");
    } catch (Exception e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    JSONObject jsonData = new JSONObject();
    try {
        jsonData.put(ProtocolConstants.KEY_LOCATION, URI.create(this.cloneLocation));
    } catch (JSONException e) {
        // Should not happen
    }
    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, jsonData);
}

From source file:org.eclipse.orion.server.git.servlets.CloneJob.java

License:Open Source License

private IStatus doClone() {
    try {/* w  ww  . j  av  a2s .com*/
        File cloneFolder = new File(clone.getContentLocation().getPath());
        if (!cloneFolder.exists()) {
            cloneFolder.mkdir();
        }
        CloneCommand cc = Git.cloneRepository();
        cc.setBare(false);
        cc.setCredentialsProvider(credentials);
        cc.setDirectory(cloneFolder);
        cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
        cc.setURI(clone.getUrl());
        Git git = cc.call();

        // Configure the clone, see Bug 337820
        task.setMessage(NLS.bind("Configuring {0}...", clone.getUrl()));
        updateTask(task);
        GitCloneHandlerV1.doConfigureClone(git, user);
        git.getRepository().close();
    } catch (IOException e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
        return e.getStatus();
    } catch (JGitInternalException e) {
        return getJGitInternalExceptionStatus(e, "An internal git error cloning git repository");
    } catch (Exception e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    return Status.OK_STATUS;
}

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 {// www.java 2  s  .  c om
        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.mule.module.git.GitConnector.java

License:Open Source License

/**
 * Clone a repository into a new directory
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:clone}
 *
 * @param uri The (possibly remote) repository to clone from.
 * @param bare True if you want a bare Git repository, false otherwise.
 * @param remote Name of the remote to keep track of the upstream repository.
 * @param branch Name of the local branch into which the remote will be cloned.
 * @param overrideDirectory Name of the directory to use for git repository
 *//* w  ww .  ja  v a  2s. c o m*/
@Processor
public void cloneRepository(String uri, @Optional @Default("false") boolean bare,
        @Optional @Default("origin") String remote, @Optional @Default("HEAD") String branch,
        @Optional String overrideDirectory) {
    File dir = resolveDirectory(overrideDirectory);

    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new RuntimeException("Directory " + dir.getAbsolutePath() + " cannot be created");
        }
    }

    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setBare(bare);
    cloneCommand.setDirectory(dir);
    cloneCommand.setRemote(remote);
    cloneCommand.setBranch(branch);
    cloneCommand.setURI(uri);

    try {
        Git git = cloneCommand.call();
    } catch (Exception e) {
        throw new RuntimeException("Cannot clone repository", e);
    }
}

From source file:org.zend.sdkcli.internal.commands.CreateProjectCommand.java

License:Open Source License

public boolean cloneRepository(String repo, File dir) {
    CloneCommand clone = new CloneCommand();
    clone.setURI(repo);//from  w ww  .java  2  s  .c  o m
    clone.setRemote(GitHelper.getRemote(repo));
    clone.setDirectory(dir);
    clone.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)));
    getLogger().info(MessageFormat.format("Cloning into {0}...", dir.getName()));
    try {
        clone.call();
    } catch (JGitInternalException e) {
        delete(dir);
        getLogger().error(e);
        return false;
    } catch (InvalidRemoteException e) {
        delete(dir);
        getLogger().error(e);
        return false;
    } catch (TransportException e) {
        delete(dir);
        getLogger().error(e);
        return false;
    } catch (GitAPIException e) {
        delete(dir);
        getLogger().error(e);
        return false;
    }
    return true;
}