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:ezbake.deployer.publishers.openShift.RhcApplication.java

License:Apache License

/**
 * This will make sure that a directory is on disk for the git repository.  It will clone the git repo to the directory
 * if needed, or git pull the new contents if required.
 *
 * @return git repository created/retrieved from OpenShift with the remote pointing to OpenShift
 * @throws DeploymentException - on any exception getting it from git
 *///from   w  w  w  . j  ava 2s.c o  m
public Git getOrCreateGitRepo() throws DeploymentException {
    String gitUrl = applicationInstance.getGitUrl();

    Files.createDirectories(appTmpDir);
    File gitDir = new File(appTmpDir, ".git");
    if (gitRepo != null || gitDir.exists() && gitDir.isDirectory()) {
        try {
            Git git = gitRepo != null ? gitRepo : Git.open(appTmpDir);
            // stash to get to a clean state of git dir so that we can pull without conflicts
            git.stashCreate();
            git.stashDrop();
            PullCommand pullCommand = git.pull();
            if (gitCredentialsProvider != null)
                pullCommand.setCredentialsProvider(gitCredentialsProvider);
            PullResult result = pullCommand.call();
            if (!result.isSuccessful())
                throw new DeploymentException("Git pull was not successful: " + result.toString());
            setGitRepo(git);
            return git;
        } catch (IOException | GitAPIException e) {
            log.error("Error opening existing cached git repo", e);
            throw new DeploymentException("Error opening existing cached git repo: " + e.getMessage());
        }
    } else {
        try {
            log.info("Cloning to " + appTmpDir.toString());
            CloneCommand cloneCommand = Git.cloneRepository().setURI(gitUrl).setTimeout(10000)
                    .setDirectory(appTmpDir);
            if (gitCredentialsProvider != null)
                cloneCommand.setCredentialsProvider(gitCredentialsProvider);
            gitRepo = cloneCommand.call();
            log.info("Cloned to directory: "
                    + gitRepo.getRepository().getDirectory().getParentFile().getAbsolutePath());
            return gitRepo;
        } catch (GitAPIException | JGitInternalException e) {
            log.error("Error cloning repository from OpenShift", e);
            throw new DeploymentException("Error cloning repository from OpenShift: " + e.getMessage());
        }
    }
}

From source file:facade.GitFacade.java

public static Set<String> cloneRepo(String url) throws Exception {
    String name = url.substring(url.lastIndexOf("/") + 1);
    CloneCommand clone = Git.cloneRepository().setURI(url)
            .setDirectory(new File(selectedDirectory.getAbsolutePath() + "/" + name));
    Git git = clone.call();/*from ww  w.  j  ava2s. co m*/
    repos.put(getRepoName(git), git);
    return repos.keySet();
}

From source file:fr.duminy.tools.jgit.JGitToolboxTest.java

License:Open Source License

private Git cloneRepository(Git sourceGit) throws GitAPIException, IOException {
    final String sourceURL = sourceGit.getRepository().getDirectory().getParentFile().toURI().toString();
    return Git.cloneRepository().setURI(sourceURL).setDirectory(folder.newFolder("target")).call();
}

From source file:fr.treeptik.cloudunit.utils.GitUtils.java

License:Open Source License

/**
 * this method is associate with listGitTagsOfApplication() method
 * which list all tags with index, this is this index which must pass as parammeter of this method
 *
 * @param application/*from   w ww.j  a v a 2 s  .  c  om*/
 * @param indexChosen
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> resetOnChosenGitTag(Application application, int indexChosen,
        String dockerManagerAddress, String containerGitAddress)
        throws InvalidRemoteException, TransportException, GitAPIException, IOException {
    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;
    File gitworkDir = Files.createTempDirectory("clone").toFile();
    CloneCommand clone = Git.cloneRepository();
    clone.setDirectory(gitworkDir);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);
    clone.setCredentialsProvider(credentialsProvider);
    clone.setURI(remoteRepository);
    Git git = clone.call();

    ListTagCommand listTagCommand = git.tagList();
    List<Ref> listRefs = listTagCommand.call();

    Ref ref = listRefs.get(indexChosen);

    ResetCommand resetCommand = git.reset();
    resetCommand.setMode(ResetType.HARD);
    resetCommand.setRef(ref.getName());
    resetCommand.call();

    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(credentialsProvider);
    pushCommand.setForce(true);

    List<PushResult> listPushResults = (List<PushResult>) pushCommand.call();
    List<String> listPushResultsMessages = new ArrayList<>();
    for (PushResult pushResult : listPushResults) {
        listPushResultsMessages.add(pushResult.getMessages());
    }
    FilesUtils.deleteDirectory(gitworkDir);
    return listPushResultsMessages;
}

From source file:fr.xebia.workshop.git.GithubRepositoriesCreator.java

License:Apache License

private Git initGitLocalRepository(File tmpRepoDir) {
    Git git;/*from w w  w  .ja va  2  s  .c  o m*/
    if (sourceGitHubRepositoryUrl != null) {
        logger.info("Repository {} is cloning into {}",
                new Object[] { sourceGitHubRepositoryUrl, tmpRepoDir.getAbsolutePath() });
        git = Git.cloneRepository().setURI(sourceGitHubRepositoryUrl).setDirectory(tmpRepoDir).call();
    } else {
        logger.info("Repository is initiating into {}", tmpRepoDir);
        git = Git.init().setDirectory(tmpRepoDir).call();
    }
    return git;
}

From source file:getgitdata.TestJGit.java

public void testClone() throws IOException, GitAPIException {
    Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call();
}

From source file:gitadapter.CloneRemoteRepositoryWithAuthentication.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    // this is necessary when the remote host does not have a valid certificate, ideally we would install the certificate in the JVM
    // instead of this unsecure workaround!
    CredentialsProvider allowHosts = new CredentialsProvider() {

        @Override//ww w  .j a v a  2  s  .c om
        public boolean supports(CredentialItem... items) {
            for (CredentialItem item : items) {
                if ((item instanceof CredentialItem.YesNoType)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
            for (CredentialItem item : items) {
                if (item instanceof CredentialItem.YesNoType) {
                    ((CredentialItem.YesNoType) item).setValue(true);
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean isInteractive() {
            return false;
        }
    };

    // prepare a new folder for the cloned repository
    File localPath = File.createTempFile("TestGitRepository", "");
    if (!localPath.delete()) {
        throw new IOException("Could not delete temporary file " + localPath);
    }

    // then clone
    System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);
    try (Git result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath)
            .setCredentialsProvider(allowHosts).call()) {
        // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
        System.out.println("Having repository: " + result.getRepository().getDirectory());
    }
}

From source file:GitBackend.GitAPI.java

License:Apache License

private Git openOrCreate(File localDirectory, String remoteRepo) throws IOException, GitAPIException {
    Git git = null;/*w ww  .  j  ava2s . com*/
    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    repositoryBuilder.addCeilingDirectory(localDirectory);
    repositoryBuilder.findGitDir(localDirectory);
    if (repositoryBuilder.getGitDir() == null) {
        // git = Git.init().setDirectory( gitDirectory.getParentFile() ).call();
        try {

            Git.cloneRepository().setURI(remoteRepo).setDirectory(localDirectory).call();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
    } else {
        git = new Git(repositoryBuilder.build());
    }
    return git;
}

From source file:git_manager.tool.GitOperations.java

License:Open Source License

public void cloneRepo(File cloneFrom, File cloneTo) {
    try {/*  ww  w.  j  a  v a2  s . c o  m*/
        Git.cloneRepository().setURI(cloneFrom.getAbsolutePath()).setDirectory(cloneTo).setBranch("master")
                .setBare(false).setRemote("origin").setNoCheckout(false).call();
    } catch (InvalidRemoteException e) {
        e.printStackTrace();
    } catch (TransportException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
}

From source file:io.dpwspoon.github.utils.TravisCIUtils.java

public static void addTravisFileToRepo(final String uri, final String branchName, final String orgName,
        final String repoName, File workingDir)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    File directory = new File(workingDir, repoName);
    Git localRepo = null;//from w  w  w  .  j  av  a2s.  co m
    for (int trys = 0; true; trys++) {
        try {
            localRepo = Git.cloneRepository().setCredentialsProvider(credentialsProvider)
                    .setDirectory(directory).setURI(uri).call();
            break;
        } catch (TransportException e) {
            // sporadic failure
            FileUtils.deleteFolder(directory);
            if (trys > 3) {
                throw e;
            }
        }
    }
    localRepo.checkout().setCreateBranch(true).setName(branchName).call();
    addTravisFileTo(localRepo, directory, orgName, repoName);
    localRepo.commit().setAll(true).setMessage("Added .travis.yml and badge to README.md").call();
    localRepo.push().setCredentialsProvider(credentialsProvider).call();
}