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.phoenicis.repository.types.GitRepository.java

License:Open Source License

private void cloneOrUpdate() throws RepositoryException {
    final boolean folderExists = this.localFolder.exists();

    // check that the repository folder exists
    if (!folderExists) {
        LOGGER.info("Creating local folder for " + this);

        if (!this.localFolder.mkdirs()) {
            throw new RepositoryException("Couldn't create local folder for " + this);
        }//ww w. j av a2s.co m
    }
    Git gitRepository = null;

    /*
     * if the repository folder previously didn't exist, clone the
     * repository now and checkout the correct branch
     */
    if (!folderExists) {
        LOGGER.info("Cloning " + this);

        try {
            gitRepository = Git.cloneRepository().setURI(this.repositoryUri.toString())
                    .setDirectory(this.localFolder).setBranch(this.branch).call();
        } catch (GitAPIException e) {
            throw new RepositoryException(
                    String.format("Folder '%s' is no git-repository", this.localFolder.getAbsolutePath()), e);
        } finally {
            // close repository to free resources
            if (gitRepository != null) {
                gitRepository.close();
            }
        }
    }
    /*
     * otherwise open the folder and pull the newest updates from the
     * repository
     */
    else {
        // if anything doesn't work here, we still have our local checkout
        // e.g. could be that the git repository cannot be accessed, there is not Internet connection etc.
        // TODO: it might make sense to ensure that our local checkout is not empty / a valid git repository
        try {
            LOGGER.info("Opening " + this);

            gitRepository = Git.open(localFolder);

            LOGGER.info("Pulling new commits from " + this);

            gitRepository.pull().call();
        } catch (Exception e) {
            LOGGER.warn("Could not update {0}. Local checkout will be used.", e);
        } finally {
            // close repository to free resources
            if (gitRepository != null) {
                gitRepository.close();
            }
        }
    }
}

From source file:org.seedstack.hub.infra.vcs.GitFetchService.java

License:Mozilla Public License

protected void doFetch(URL remote, File target) {
    logger.debug("Cloning Git remote {} into directory {}", remote.toExternalForm(), target.getAbsolutePath());

    try (Git localRepository = Git.cloneRepository().setURI(stripBranchName(remote)).setDirectory(target)
            .call()) {//  ww  w.j av a2 s. c om
        String branchName = getBranchName(remote);

        logger.debug("Checking out {} branch in directory {}", branchName, target.getAbsolutePath());

        if (localRepository.getRepository().getRef(branchName) == null) {
            localRepository.branchCreate().setName(branchName)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                    .setStartPoint("origin/" + branchName).call();
        }

        localRepository.checkout().setName(branchName).call();
    } catch (Exception e) {
        throw new FetchException("Unable to fetch Git remote " + remote.toExternalForm(), e);
    }
}

From source file:org.spdx.tools.LicenseListPublisher.java

License:Apache License

/**
 * Publish a license list to the license data git repository
 * @param release license list release name (must be associatd with a tag in the license-list-xml repo)
 * @param gitUserName github username to be used - must have commit access to the license-xml-data repo
 * @param gitPassword github password/*from  w ww. j  av a  2  s  .co m*/
 * @throws LicensePublisherException 
 * @throws LicenseGeneratorException 
 */
private static void publishLicenseList(String release, String gitUserName, String gitPassword,
        boolean ignoreWarnings) throws LicensePublisherException, LicenseGeneratorException {
    CredentialsProvider githubCredentials = new UsernamePasswordCredentialsProvider(gitUserName, gitPassword);
    File licenseXmlDir = null;
    File licenseDataDir = null;
    Git licenseXmlGit = null;
    Git licenseDataGit = null;
    try {
        licenseXmlDir = Files.createTempDirectory("LicenseXML").toFile();
        System.out.println("Cloning the license XML repository - this could take a while...");
        licenseXmlGit = Git.cloneRepository().setCredentialsProvider(githubCredentials)
                .setDirectory(licenseXmlDir).setURI(LICENSE_XML_URI).call();
        Ref releaseTag = licenseXmlGit.getRepository().getTags().get(release);
        if (releaseTag == null) {
            throw new LicensePublisherException(
                    "Release " + release + " not found as a tag in the License List XML repository");
        }
        licenseXmlGit.checkout().setName(releaseTag.getName()).call();
        licenseDataDir = Files.createTempDirectory("LicenseData").toFile();
        System.out.println("Cloning the license data repository - this could take a while...");
        licenseDataGit = Git.cloneRepository().setCredentialsProvider(githubCredentials)
                .setDirectory(licenseDataDir).setURI(LICENSE_DATA_URI).call();
        Ref dataReleaseTag = licenseDataGit.getRepository().getTags().get(release);
        boolean dataReleaseTagExists = false;
        if (dataReleaseTag != null) {
            dataReleaseTagExists = true;
            licenseDataGit.checkout().setName(releaseTag.getName()).call();
        }
        cleanLicenseDataDir(licenseDataDir);
        String todayDate = new SimpleDateFormat("dd-MMM-yyyy").format(Calendar.getInstance().getTime());
        List<String> warnings = LicenseRDFAGenerator.generateLicenseData(
                new File(licenseXmlDir.getPath() + File.separator + "src"), licenseDataDir, release, todayDate);
        if (warnings.size() > 0 && !ignoreWarnings) {
            throw new LicensePublisherException(
                    "There are some skipped or invalid license input data.  Publishing aborted.  To ignore, add the --ignore option as the first parameter");
        }
        licenseDataGit.add().addFilepattern(".").call();
        licenseDataGit.commit().setAll(true)
                .setCommitter("SPDX License List Publisher", "spdx-tech@lists.spdx.org")
                .setMessage("License List Publisher for " + gitUserName + ".  License list version " + release)
                .call();
        if (!dataReleaseTagExists) {
            licenseDataGit.tag().setName(release).setMessage("SPDX License List release " + release).call();
        }
        licenseDataGit.push().setCredentialsProvider(githubCredentials).setPushTags().call();
    } catch (IOException e) {
        throw new LicensePublisherException("I/O Error publishing license list", e);
    } catch (InvalidRemoteException e) {
        throw new LicensePublisherException("Invalid remote error trying to access the git repositories", e);
    } catch (TransportException e) {
        throw new LicensePublisherException("Transport error trying to access the git repositories", e);
    } catch (GitAPIException e) {
        throw new LicensePublisherException("GIT API error trying to access the git repositories", e);
    } finally {
        if (licenseXmlGit != null) {
            licenseXmlGit.close();
        }
        if (licenseDataGit != null) {
            licenseDataGit.close();
        }
        if (licenseXmlDir != null) {
            deleteDir(licenseXmlDir);
        }
        if (licenseDataDir != null) {
            deleteDir(licenseDataDir);
        }
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitConfigServerTestData.java

License:Apache License

public static JGitConfigServerTestData prepareClonedGitRepository(Object... sources) throws Exception {
    //setup remote repository
    String remoteUri = ConfigServerTestUtils.prepareLocalRepo();
    File remoteRepoDir = ResourceUtils.getFile(remoteUri);
    Git remoteGit = Git.open(remoteRepoDir.getAbsoluteFile());
    remoteGit.checkout().setName("master").call();

    //setup local repository
    File clonedRepoDir = new File("target/repos/cloned");
    if (clonedRepoDir.exists()) {
        FileSystemUtils.deleteRecursively(clonedRepoDir);
    } else {//from  www . j a va 2 s .com
        clonedRepoDir.mkdirs();
    }
    Git clonedGit = Git.cloneRepository().setURI("file://" + remoteRepoDir.getAbsolutePath())
            .setDirectory(clonedRepoDir).setBranch("master").setCloneAllBranches(true).call();

    //setup our test spring application pointing to the local repo
    ConfigurableApplicationContext context = new SpringApplicationBuilder(sources).web(false)
            .properties("spring.cloud.config.server.git.uri:" + "file://" + clonedRepoDir.getAbsolutePath())
            .run();
    JGitEnvironmentRepository repository = context.getBean(JGitEnvironmentRepository.class);

    return new JGitConfigServerTestData(new JGitConfigServerTestData.LocalGit(remoteGit, remoteRepoDir),
            new JGitConfigServerTestData.LocalGit(clonedGit, clonedRepoDir), repository, context);
}

From source file:org.srcdeps.core.impl.scm.JGitScm.java

License:Apache License

void cloneAndCheckout(BuildRequest request) throws ScmException {
    final Path dir = request.getProjectRootDirectory();

    final SrcVersion srcVersion = request.getSrcVersion();
    ScmException lastException = null;//from w  ww .j  a va  2  s.com

    /* Try the urls one after another and exit on the first success */
    for (String url : request.getScmUrls()) {
        String useUrl = stripUriPrefix(url);
        log.info("Srcdeps attempting to clone version {} from SCM URL {}", request.getSrcVersion(), useUrl);

        CloneCommand cmd = Git.cloneRepository().setURI(useUrl).setDirectory(dir.toFile());

        switch (srcVersion.getWellKnownType()) {
        case branch:
        case tag:
            cmd.setBranch(srcVersion.getScmVersion());
            break;
        case revision:
            cmd.setCloneAllBranches(true);
            break;
        default:
            throw new IllegalStateException("Unexpected " + WellKnownType.class.getName() + " value '"
                    + srcVersion.getWellKnownType() + "'.");
        }

        try (Git git = cmd.call()) {
            git.checkout().setName(srcVersion.getScmVersion()).call();

            /*
             * workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=474093
             */
            git.getRepository().close();

            /* return on the first success */
            return;
        } catch (Exception e) {
            log.warn("Srcdeps could not checkout version {} from SCM URL {}: {}: {}", request.getSrcVersion(),
                    useUrl, e.getClass().getName(), e.getMessage());
            lastException = new ScmException(String.format("Could not checkout from URL [%s]", useUrl), e);
        }
    }
    throw lastException;
}

From source file:org.uberfire.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static Git cloneRepository(final File repoFolder, final String fromURI, final boolean bare,
        final CredentialsProvider credentialsProvider) {

    if (!repoFolder.getName().endsWith(DOT_GIT_EXT)) {
        throw new RuntimeException("Invalid name");
    }/*  w ww  .  j  a  v a 2s  . c  o  m*/

    try {
        final File gitDir = RepositoryCache.FileKey.resolve(repoFolder, DETECTED);
        final Repository repository;
        final Git git;
        if (gitDir != null && gitDir.exists()) {
            repository = new FileRepository(gitDir);
            git = new Git(repository);
        } else {
            git = Git.cloneRepository().setBare(bare).setCloneAllBranches(true).setURI(fromURI)
                    .setDirectory(repoFolder).setCredentialsProvider(credentialsProvider).call();
            repository = git.getRepository();
        }

        fetchRepository(git, credentialsProvider);

        repository.close();

        return git;
    } catch (final Exception ex) {
        try {
            forceDelete(repoFolder);
        } catch (final java.io.IOException e) {
            throw new RuntimeException(e);
        }
        throw new RuntimeException(ex);
    }
}

From source file:org.virtualAsylum.spriggan.data.Addon.java

public State doDownload() {
    log("Downloading %s (%s)", getDisplayName(), getID());
    setState(State.DOWNLOADING);/*from   w w  w .  j  av a2 s. co m*/
    State result = State.IDLE;
    setStateProgress(-1);
    Database.getCurrent().getRepository().add(this);
    File repositoryDirectory = getRepositoryDirectory(this);
    if (repositoryDirectory.exists()) {
        recursiveDelete(repositoryDirectory);
    }
    try {
        git = Git.cloneRepository().setURI(getRemoteRepository()).setBranch(getBranch())
                .setDirectory(repositoryDirectory).setProgressMonitor(monitor).call();
        Database.save();
    } catch (Exception ex) {
        handleException(ex);
        result = State.ERROR;
    }

    log("Downloading %s (%s): %s", getDisplayName(), getID(), result);
    setState(result);
    setStateProgress(0);
    return result;
}

From source file:org.wandora.application.tools.git.Clone.java

License:Open Source License

@Override
public void execute(Wandora wandora, Context context) {
    if (cloneUI == null) {
        cloneUI = new CloneUI();
    }//from  w  ww . j av  a  2 s.com

    cloneUI.setUsername(getUsername());
    cloneUI.setPassword(getPassword());
    cloneUI.openInDialog();

    if (cloneUI.wasAccepted()) {
        setDefaultLogger();
        setLogTitle("Git clone");

        String cloneUrl = cloneUI.getCloneUrl();
        String destinationDirectory = cloneUI.getDestinationDirectory();
        String username = cloneUI.getUsername();
        String password = cloneUI.getPassword();

        setUsername(username);
        setPassword(password);

        log("Cloning git repository from " + cloneUrl);

        try {
            CloneCommand clone = Git.cloneRepository();
            clone.setURI(cloneUrl);
            clone.setDirectory(new File(destinationDirectory));

            if (isNotEmpty(username)) {
                CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username,
                        password);
                clone.setCredentialsProvider(credentialsProvider);
            }

            clone.call();

            if (cloneUI.getOpenProject()) {
                log("Opening project.");
                LoadWandoraProject loadProject = new LoadWandoraProject(destinationDirectory);
                loadProject.setToolLogger(this);
                loadProject.execute(wandora, context);
            }
            log("Ready.");
        } catch (GitAPIException ex) {
            log(ex.toString());
        } catch (Exception e) {
            log(e);
        }
        setState(WAIT);
    }
}

From source file:org.wso2.carbon.appfactory.repository.mgt.git.JGitAgent.java

License:Apache License

/**
 * Clone a repository into {@code cloneDirectory}
 *
 * @param remoteRepoUrl  remote repository url
 * @param noCheckout     checkout or not
 * @param cloneDirectory Directory to clone
 * @return newly created {@code Git} object with associated repository
 * @throws RepositoryMgtException if error while cloning
 *///from ww w  . j a va  2s .  c o  m
public Git clone(String remoteRepoUrl, boolean noCheckout, File cloneDirectory) throws RepositoryMgtException {
    try {
        return Git.cloneRepository().setURI(remoteRepoUrl).setDirectory(cloneDirectory)
                .setNoCheckout(noCheckout).setCredentialsProvider(getCredentialsProvider()).call();
    } catch (GitAPIException e) {
        String msg = "Error while cloning the repository from : " + remoteRepoUrl + " due to " + e.getMessage()
                + " from GitAPIException";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    }
}

From source file:org.wso2.carbon.deployment.synchronizer.git.GitBasedArtifactRepository.java

License:Open Source License

/**
 * Clones the remote repository to the local repository path
 *
 * @param gitRepoCtx TenantGitRepositoryContext for the tenant
 * @return true if clone is success, else false
 *///  w  w w  . j a va2  s .  c o  m
private boolean cloneRepository(TenantGitRepositoryContext gitRepoCtx) { //should happen only at the beginning

    boolean cloneSuccess = false;

    File gitRepoDir = new File(gitRepoCtx.getLocalRepoPath());
    /*if (gitRepoDir.exists()) {
    if(GitUtilities.isValidGitRepo(gitRepoCtx.getLocalRepo())) { //check if a this is a valid git repo
        log.info("Existing git repository detected for tenant " + gitRepoCtx.getTenantId() +
                ", no clone required");
        gitRepoCtx.setCloneExists(true);
        return true;
    }
    else {
        if(log.isDebugEnabled()) {
            log.debug("Repository for tenant " + gitRepoCtx.getTenantId() + " is not a valid git repo, will try to delete");
        }
        FileUtilities.deleteFolderStructure(gitRepoDir); //if not a valid git repo but non-empty, delete it (else the clone will not work)
    }
    }*/

    CloneCommand cloneCmd = Git.cloneRepository().setURI(gitRepoCtx.getRemoteRepoUrl()).setDirectory(gitRepoDir)
            .setBranch(GitDeploymentSynchronizerConstants.GIT_REFS_HEADS_MASTER);

    UsernamePasswordCredentialsProvider credentialsProvider = GitUtilities
            .createCredentialsProvider(repositoryManager, gitRepoCtx.getTenantId());

    if (credentialsProvider == null) {
        log.warn("Remote repository credentials not available for tenant " + gitRepoCtx.getTenantId()
                + ", aborting clone");
        return false;
    }
    cloneCmd.setCredentialsProvider(credentialsProvider);

    try {
        cloneCmd.call();
        log.info("Git clone operation for tenant " + gitRepoCtx.getTenantId() + " successful");
        gitRepoCtx.setCloneExists(true);
        cloneSuccess = true;

    } catch (TransportException e) {
        log.error("Accessing remote git repository failed for tenant " + gitRepoCtx.getTenantId(), e);

    } catch (GitAPIException e) {
        log.error("Git clone operation for tenant " + gitRepoCtx.getTenantId() + " failed", e);
    }

    return cloneSuccess;
}