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

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

Introduction

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

Prototype

public CloneCommand setBranch(String branch) 

Source Link

Document

Set the initial branch

Usage

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public void cloneRepo(String branch) throws Exception {
    CloneCommand cloneCommand = Git.cloneRepository().setURI(repositoryUrl)
            .setDirectory(localRepo.getDirectory().getParentFile());
    if (branch != null)
        cloneCommand.setBranch(branch);
    if (credentialsProvider != null)
        cloneCommand.setCredentialsProvider(credentialsProvider);
    cloneCommand.call();/*from  w w w  . j a  v  a  2s. c om*/
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

private Git clone(Application application, File dirLocation) {
    Git git = null;//from  ww w  .ja  va  2s.  c  om
    try {
        CloneCommand clone = Git.cloneRepository();

        clone.setURI(application.getRepositoryUrl()).setDirectory(dirLocation)
                .setCredentialsProvider(getApplicationCredentials(application));

        if (application.getRepositoryBranch() != null && !application.getRepositoryBranch().isEmpty()) {
            clone.setBranch(application.getRepositoryBranch());
        }

        // clone git repo
        git = clone.call();

        // checkout specific revision
        if (application.getRepositoryRevision() != null && !application.getRepositoryRevision().isEmpty()) {
            git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision())
                    .setName(application.getRepositoryRevision()).call();
        }

    } catch (WrongRepositoryStateException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (InvalidConfigurationException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (DetachedHeadException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (InvalidRemoteException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (CanceledException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (RefNotFoundException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (NoHeadException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (RefAlreadyExistsException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (CheckoutConflictException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (InvalidRefNameException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (TransportException e) {
        log.error(EXCEPTION_MESSAGE, e);
    } catch (GitAPIException e) {
        log.error(EXCEPTION_MESSAGE, e);
    }

    return git;
}

From source file:com.fanniemae.ezpie.common.GitOperations.java

License:Open Source License

public String cloneHTTP(String repo_url, String destination, String userID, String password, String branch)
        throws InvalidRemoteException, TransportException, GitAPIException, URISyntaxException {

    _repositoryHost = getHost(repo_url);
    setupProxy();//  w  w  w .  j ava  2s.  c o  m

    File localDir = new File(destination);
    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(repo_url);
    cloneCommand.setDirectory(localDir);

    if (StringUtilities.isNotNullOrEmpty(branch))
        cloneCommand.setBranch(branch);

    if (StringUtilities.isNotNullOrEmpty(userID))
        cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userID, password));

    try (Writer writer = new StringWriter()) {
        TextProgressMonitor tpm = new TextProgressMonitor(writer);
        cloneCommand.setProgressMonitor(tpm);
        try (Git result = cloneCommand.call()) {
        }
        clearProxyAuthenticatorCache();
        writer.flush();
        return writer.toString();
    } catch (IOException e) {
        throw new PieException("Error while trying to clone the git repository. " + e.getMessage(), e);
    }
}

From source file:com.fanniemae.ezpie.common.GitOperations.java

License:Open Source License

public String cloneSSH(String repo_url, String destination, String privateKey, String password, String branch) {
    if (_useProxy) {
        throw new PieException(
                "Network proxies do not support SSH, please use an http url to clone this repository.");
    }// w  w  w .jav  a2 s.  c  o m

    final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
        @Override
        protected void configure(Host host, Session session) {
            // This still checks existing host keys and will disable "unsafe"
            // authentication mechanisms if the host key doesn't match.
            session.setConfig("StrictHostKeyChecking", "no");
        }

        @Override
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            JSch defaultJSch = super.createDefaultJSch(fs);
            defaultJSch.addIdentity(privateKey, password);
            return defaultJSch;
        }
    };

    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(repo_url);
    File dir = new File(destination);
    cloneCommand.setDirectory(dir);

    if (StringUtilities.isNotNullOrEmpty(branch))
        cloneCommand.setBranch(branch);

    cloneCommand.setTransportConfigCallback(new TransportConfigCallback() {
        public void configure(Transport transport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        }
    });

    try (Writer writer = new StringWriter()) {
        TextProgressMonitor tpm = new TextProgressMonitor(writer);
        cloneCommand.setProgressMonitor(tpm);
        try (Git result = cloneCommand.call()) {
        }
        writer.flush();
        return writer.toString();
    } catch (IOException | GitAPIException e) {
        throw new PieException("Error while trying to clone the git repository. " + e.getMessage(), e);
    }
}

From source file:com.gitblit.tests.TicketReferenceTest.java

License:Apache License

@BeforeClass
public static void configure() throws Exception {
    File repositoryName = new File("TicketReferenceTest.git");
    ;//  w w w .java  2 s. com

    GitBlitSuite.close(repositoryName);
    if (repositoryName.exists()) {
        FileUtils.delete(repositoryName, FileUtils.RECURSIVE | FileUtils.RETRY);
    }
    repo = new RepositoryModel("TicketReferenceTest.git", null, null, null);

    if (gitblit().hasRepository(repo.name)) {
        gitblit().deleteRepositoryModel(repo);
    }

    gitblit().updateRepositoryModel(repo.name, repo, true);

    user = new UserModel(account);
    user.displayName = account;
    user.emailAddress = account + "@example.com";
    user.password = password;

    cp = new UsernamePasswordCredentialsProvider(user.username, user.password);

    if (gitblit().getUserModel(user.username) != null) {
        gitblit().deleteUser(user.username);
    }

    repo.authorizationControl = AuthorizationControl.NAMED;
    repo.accessRestriction = AccessRestrictionType.PUSH;
    gitblit().updateRepositoryModel(repo.name, repo, false);

    // grant user push permission
    user.setRepositoryPermission(repo.name, AccessPermission.REWIND);
    gitblit().updateUserModel(user);

    ticketService = gitblit().getTicketService();
    assertTrue(ticketService.deleteAll(repo));

    GitBlitSuite.close(workingCopy);
    if (workingCopy.exists()) {
        FileUtils.delete(workingCopy, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/{1}", url, repo.name));
    clone.setDirectory(workingCopy);
    clone.setBare(false);
    clone.setBranch("master");
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    git = Git.open(workingCopy);
    git.getRepository().getConfig().setString("user", null, "name", user.displayName);
    git.getRepository().getConfig().setString("user", null, "email", user.emailAddress);
    git.getRepository().getConfig().save();

    final RevCommit revCommit1 = makeCommit("initial commit");
    final String initialSha = revCommit1.name();
    Iterable<PushResult> results = git.push().setPushAll().setCredentialsProvider(cp).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
            assertEquals(initialSha, update.getNewObjectId().name());
        }
    }
}

From source file:com.maiereni.sling.sources.git.GitProjectDownloader.java

License:Apache License

private Git cloneRepository(final File directory, final String url, final String branchName) throws Exception {
    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(url);/*from  www. j  av  a  2  s. c  o  m*/
    /*
    if (StringUtils.isNoneBlank(user, password)) {
       cloneCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider(user, password));
    }*/
    cloneCommand.setDirectory(directory);
    cloneCommand.setBranch(branchName);
    logger.debug("Clone the repository");
    return cloneCommand.call();
}

From source file:com.maiereni.synchronizer.git.utils.GitDownloaderImpl.java

License:Apache License

private Git createRepository(final File fRepo, final GitProperties properties) throws Exception {
    if (StringUtils.isEmpty(properties.getRemote())) {
        throw new Exception("The remote URL of Git cannot be null");
    }/*from  w  w w.ja v  a 2s  .  c o  m*/
    logger.debug("Create repository at " + fRepo.getPath());
    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(properties.getRemote());
    if (StringUtils.isNotBlank(properties.getUserName()) && StringUtils.isNotBlank(properties.getPassword())) {
        logger.debug("Set credentials");
        cloneCommand.setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(properties.getUserName(), properties.getPassword()));
    }
    cloneCommand.setDirectory(fRepo);
    cloneCommand.setBranch(properties.getBranchName());
    logger.debug("Clone the repository");
    return cloneCommand.call();
}

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 av a2  s. c  o m*/
        }
    }
    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.rimerosolutions.ant.git.tasks.CloneTask.java

License:Apache License

@Override
public void execute() {
    try {//w w w.j a  va2s  .  com
        CloneCommand cloneCommand = new CloneCommand();

        if (branchToTrack != null) {
            cloneCommand.setBranch(branchToTrack);
        }

        if (!branchNames.isEmpty()) {
            cloneCommand.setBranchesToClone(branchNames);
        }

        cloneCommand.setURI(getUri()).setBare(bare).setCloneAllBranches(cloneAllBranches)
                .setCloneSubmodules(cloneSubModules).setNoCheckout(noCheckout).setDirectory(getDirectory());

        setupCredentials(cloneCommand);

        if (getProgressMonitor() != null) {
            cloneCommand.setProgressMonitor(getProgressMonitor());
        }

        cloneCommand.call();
    } catch (Exception e) {
        throw new GitBuildException(String.format(MESSAGE_CLONE_FAILED, getUri()), e);
    }
}

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 {//from   w w  w.ja v a2s. c  o m
        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;
}