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.tasktop.c2c.server.scm.service.GitServiceTestBase.java

License:Open Source License

protected Git createAndCloneRepo(String name)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    ScmRepository repository = new ScmRepository();
    repository.setName(name);/*from w w w.j ava2s  .c  om*/
    repository.setDescription(description);
    gitService.createEmptyRepository(repository);

    File gitDir = new File(gitRoot + "/" + projId + "/" + GitConstants.HOSTED_GIT_DIR + "/" + name);
    Git git = Git.cloneRepository().setURI(gitDir.getAbsolutePath()).setDirectory(new File(tempDir)).call();
    return git;
}

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.services.impl.GitCloneServiceImpl.java

License:Apache License

public void download(String url, String moduleName) throws ModuleDownloaderException {
    // prepare a new folder for the cloned repository
    File localPath = new File(modulesCodeDownloadPath + moduleName);
    localPath.delete();//from www .  ja  va2s  .com

    try {
        FileUtils.deleteDirectory(localPath);
    } catch (IOException e) {
        throw new ModuleDownloaderException(e);
    }

    // then clone
    logger.debug("Cloning from " + url + " to " + localPath);
    try {
        Git.cloneRepository().setURI(url).setDirectory(localPath).call();
    } catch (InvalidRemoteException e) {
        throw new ModuleDownloaderException(e);
    } catch (TransportException e) {
        throw new ModuleDownloaderException(e);
    } catch (GitAPIException e) {
        throw new ModuleDownloaderException(e);
    }

    // now open the created repository
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository;
    try {
        repository = builder.setGitDir(localPath).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();
    } catch (IOException e) {
        throw new ModuleDownloaderException(e);
    }

    logger.debug("Having repository: " + repository.getDirectory());

    repository.close();
}

From source file:com.tenxdev.ovcs.command.InitCommand.java

License:Open Source License

private void initGitRepo(final Path workingDir, final String remoteUri, final String connectionString)
        throws OvcsException {
    try {//from   w w w . jav a2s.c  o  m
        System.out.println("Cloning git repo");
        Git.cloneRepository().setDirectory(workingDir.toFile()).setCloneAllBranches(true).setRemote("origin")
                .setURI(remoteUri).setProgressMonitor(new TextProgressMonitor()).call();
        final Git git = Git.open(workingDir.toFile());
        final StoredConfig config = git.getRepository().getConfig();
        config.setString("database", null, "connectionString", connectionString);
        config.save();
        git.checkout().setName("master").setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    } catch (GitAPIException | IOException e) {
        throw new OvcsException("Unable to initialize Git repo: " + e.getMessage(), e);
    }
}

From source file:com.ttech.cordovabuild.infrastructure.git.GitUtils.java

License:Apache License

public static Path clone(String uri) {
    Path path = null;/*from   w  w w  .  j  ava2s  .c o  m*/
    try {
        path = getClonePath();
    } catch (IOException e) {
        throw new GitException(e);
    }
    try {
        Git.cloneRepository().setURI(uri).setDirectory(path.toFile()).call();
        removePattern(path, ".git");
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
    return path;
}

From source file:com.ttech.cordovabuild.infrastructure.git.GitUtils.java

License:Apache License

public static Path clone(String uri, String username, String password) {
    Path path = null;//from   w w  w. j a  va 2  s .  co m
    try {
        path = getClonePath();
    } catch (IOException e) {
        throw new GitException(e);
    }
    LOGGER.info("starting to clone git repo {} to {}", uri, path);
    try {
        Git.cloneRepository().setURI(uri).setDirectory(path.toFile())
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)).call();
        LOGGER.info("purging .git files");
        removePattern(path, ".git");
        LOGGER.info("purging .git files finished");
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
    return path;
}

From source file:com.uber.stream.kafka.mirrormaker.controller.core.GitBackUpHandler.java

License:Apache License

public void writeToFile(String fileName, String data) throws Exception {
    Repository backupRepo = null;/*w ww  .ja  v a  2 s . co  m*/
    BufferedWriter output = null;
    Git git = null;
    Git result = null;
    try {
        try {
            FileUtils.deleteDirectory(new File(localPath));
        } catch (IOException e) {
            LOGGER.error("Error deleting exisiting backup directory");
            throw e;
        }

        try {
            result = Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call();
        } catch (Exception e) {
            LOGGER.error("Error cloning backup git repo");
            throw e;
        }

        try {
            backupRepo = new FileRepository(localPath + "/.git");
        } catch (IOException e) {
            throw e;
        }

        git = new Git(backupRepo);
        File myfile = new File(localPath + "/" + fileName);

        try {
            output = new BufferedWriter(new FileWriter(myfile));
            output.write(data);
            output.flush();
        } catch (IOException e) {
            LOGGER.error("Error writing backup to the file with name " + fileName);
            throw e;
        }

        try {
            git.add().addFilepattern(".").call();
        } catch (GitAPIException e) {
            LOGGER.error("Error adding files to git");
            throw e;
        }

        try {
            git.commit().setMessage("Taking backup on " + new Date()).call();

        } catch (GitAPIException e) {
            LOGGER.error("Error commiting files to git");
            throw e;
        }

        try {
            git.push().call();
        } catch (GitAPIException e) {
            LOGGER.error("Error pushing files to git");
            throw e;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        output.close();
        git.close();
        if (result != null)
            result.getRepository().close();
        backupRepo.close();
    }
}

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
 * Clones the specified repository in the specified directory using the
 * provided credentials for authentication
 *
 * @param url       the URL of the git repository to be cloned
 * @param username  username to be used for cloning the repository
 * @param password  password matching with the provided username to be used for
 *                  authentication//from w  w w . j a v  a2  s  .c o  m
 * @param directory the path in which the git repository should be cloned
 * @throws GitAPIException if anything's going wrong while cloning the repository
 */
public static void clone(@NonNull String url, String username, String password, String directory)
        throws GitAPIException {
    log.info("Cloning from " + url + " to " + directory);
    try {
        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);
        Git.cloneRepository().setCredentialsProvider(userCredential).setURI(url)
                .setDirectory(new File(directory)).call();
        log.info("Repository sucessfully cloned");
    } catch (final InvalidRemoteException e) {
        log.error(e.getMessage(), e);
        throw e;
    } catch (final TransportException e) {
        log.error(e.getMessage(), e);
        throw e;
    } catch (final GitAPIException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

ILockedRepository createCentralRepository(boolean bare, User user) throws IOException, GitAPIException {
    if (centralRepoDir.isDirectory()) {
        throw new IllegalStateException("repository already exists: " + centralRepoDir.getAbsolutePath()); //$NON-NLS-1$
    }/* ww  w.  j av  a2s .  co m*/

    ILock lock = lockManager.lockAll();
    try {
        Repository repo = null;
        File gitDir = new File(centralRepoDir, ".git"); //$NON-NLS-1$
        try {
            RepositoryBuilder builder = new RepositoryBuilder().setGitDir(gitDir);
            if (bare) {
                builder.setBare();
            }
            repo = builder.build();
            repo.create();
        } finally {
            RepositoryUtil.closeQuietly(repo);
        }

        File tempGitDir = new File(new File(reposDir, CENTRAL_REPO_NAME + "_temp"), ".git"); //$NON-NLS-1$ //$NON-NLS-2$
        Repository tempRepo = null;
        try {
            tempRepo = Git.cloneRepository().setURI(gitDir.toURI().toString()).setDirectory(tempGitDir).call()
                    .getRepository();
            Git git = Git.wrap(tempRepo);
            PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
            git.commit().setAuthor(ident).setCommitter(ident).setMessage("init").call(); //$NON-NLS-1$
            git.push().call();
        } finally {
            RepositoryUtil.closeQuietly(tempRepo);
        }
        FileUtils.forceDelete(tempGitDir.getParentFile());
    } finally {
        lockManager.unlock(lock);
    }

    return getCentralRepository(bare);
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

ILockedRepository createBranchRepository(String branchName, String startingBranch)
        throws IOException, GitAPIException {
    Assert.hasLength(branchName);/*from w  w  w  . j  av a  2s .  c om*/
    if (startingBranch != null) {
        Assert.hasLength(startingBranch);
    }

    File repoDir = new File(reposDir, branchName);
    if (repoDir.isDirectory()) {
        throw new IllegalStateException("repository already exists: " + repoDir.getAbsolutePath()); //$NON-NLS-1$
    }

    List<String> branches = listBranches();
    if (branches.contains(branchName)) {
        throw new IllegalArgumentException("branch already exists: " + branchName); //$NON-NLS-1$
    }

    if ((startingBranch == null) && !branches.isEmpty()) {
        throw new IllegalArgumentException("must specify a starting branch"); //$NON-NLS-1$
    }

    ILock lock = lockManager.lockAll();
    try {
        Repository centralRepo = null;
        File centralRepoGitDir;
        try {
            centralRepo = getCentralRepositoryInternal(true);
            centralRepoGitDir = centralRepo.getDirectory();
        } finally {
            RepositoryUtil.closeQuietly(centralRepo);
            centralRepo = null;
        }

        Repository repo = null;
        try {
            repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString()).setDirectory(repoDir)
                    .call().getRepository();

            try {
                centralRepo = getCentralRepositoryInternal(true);
                if (!RepositoryUtils.getBranches(centralRepo).contains(branchName)) {
                    CreateBranchCommand createBranchCommand = Git.wrap(centralRepo).branchCreate();
                    if (startingBranch != null) {
                        createBranchCommand.setStartPoint(startingBranch);
                    }
                    createBranchCommand.setName(branchName).call();
                }
            } finally {
                RepositoryUtil.closeQuietly(centralRepo);
            }

            Git git = Git.wrap(repo);
            RefSpec refSpec = new RefSpec("refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$
            git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$
            git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$
            git.checkout().setName(branchName).call();
        } finally {
            RepositoryUtil.closeQuietly(repo);
        }
    } finally {
        lockManager.unlock(lock);
    }

    return getBranchRepository(branchName);
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

public void importSampleContents() throws IOException, GitAPIException {
    // TODO: synchronization is not quite correct here, but should be okay in this edge case
    if (listBranches().isEmpty()) {
        ILock lock = lockManager.lockAll();
        List<String> branches;
        try {/*  w  w w .  j a  va2 s. c om*/
            File gitDir = new File(centralRepoDir, ".git"); //$NON-NLS-1$
            FileUtils.forceDelete(gitDir);

            Git.cloneRepository().setURI(DocumentrConstants.SAMPLE_REPO_URL).setDirectory(gitDir).setBare(true)
                    .call();

            Repository centralRepo = null;
            File centralRepoGitDir;
            try {
                centralRepo = getCentralRepositoryInternal(true);
                centralRepoGitDir = centralRepo.getDirectory();
                StoredConfig config = centralRepo.getConfig();
                config.unsetSection("remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$
                config.unsetSection("branch", "master"); //$NON-NLS-1$ //$NON-NLS-2$
                config.save();
            } finally {
                RepositoryUtil.closeQuietly(centralRepo);
            }

            branches = listBranches();
            for (String branchName : branches) {
                File repoDir = new File(reposDir, branchName);
                Repository repo = null;
                try {
                    repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString())
                            .setDirectory(repoDir).call().getRepository();

                    Git git = Git.wrap(repo);
                    RefSpec refSpec = new RefSpec(
                            "refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$
                    git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$
                    git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$
                    git.checkout().setName(branchName).call();
                } finally {
                    RepositoryUtil.closeQuietly(repo);
                }
            }
        } finally {
            lockManager.unlock(lock);
        }

        for (String branch : branches) {
            eventBus.post(new BranchCreatedEvent(projectName, branch));
        }
    }
}