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:io.fabric8.openshift.agent.CartridgeGitRepository.java

License:Apache License

/**
 * Clones or pulls the remote repository and returns the directory with the checkout
 *//*from w w w.j a va 2 s . com*/
public void cloneOrPull(final String repo, final CredentialsProvider credentials) throws Exception {
    if (!localRepo.exists() && !localRepo.mkdirs()) {
        throw new IOException("Failed to create local repository");
    }
    File gitDir = new File(localRepo, ".git");
    if (!gitDir.exists()) {
        LOG.info("Cloning remote repo " + repo);
        CloneCommand command = Git.cloneRepository().setCredentialsProvider(credentials).setURI(repo)
                .setDirectory(localRepo).setRemote(remoteName);
        git = command.call();
    } else {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        git = new Git(repository);

        // update the remote repo just in case
        StoredConfig config = repository.getConfig();
        config.setString("remote", remoteName, "url", repo);
        config.setString("remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*");

        String branch = "master";
        config.setString("branch", branch, "remote", remoteName);
        config.setString("branch", branch, "merge", "refs/heads/" + branch);

        try {
            config.save();
        } catch (IOException e) {
            LOG.error("Failed to save the git configuration to " + localRepo + " with remote repo: " + repo
                    + ". " + e, e);
        }

        // now pull
        LOG.info("Pulling from remote repo " + repo);
        git.pull().setCredentialsProvider(credentials).setRebase(true).call();
    }
}

From source file:io.fabric8.profiles.containers.GitRemoteProcessor.java

License:Apache License

@Override
public void process(String name, Properties config, Path containerDir) throws IOException {
    // get or create remote repo URL
    String remoteUri = config.getProperty(GIT_REMOTE_URI_PROPERTY);
    if (remoteUri == null || remoteUri.isEmpty()) {
        remoteUri = getRemoteUri(config, name);
    }//from w  ww .j  a  v  a2s .  co  m

    // try to clone remote repo in temp dir
    String remote = config.getProperty(GIT_REMOTE_NAME_PROPERTY, Constants.DEFAULT_REMOTE_NAME);
    Path tempDirectory = null;
    try {
        tempDirectory = Files.createTempDirectory(containerDir, "cloned-remote-");
    } catch (IOException e) {
        throwException("Error creating temp directory while cloning ", remoteUri, e);
    }

    final String userName = config.getProperty("gogsUsername");
    final String password = config.getProperty("gogsPassword");
    final UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
            userName, password);

    Git clonedRepo = null;
    try {
        try {
            clonedRepo = Git.cloneRepository().setDirectory(tempDirectory.toFile()).setBranch(currentVersion)
                    .setRemote(remote).setURI(remoteUri).setCredentialsProvider(credentialsProvider).call();
        } catch (InvalidRemoteException e) {
            // TODO handle creating new remote repo in github, gogs, etc. using fabric8 devops connector
            if (e.getCause() instanceof NoRemoteRepositoryException) {
                final String address = "http://" + config.getProperty("gogsServiceHost", "gogs.vagrant.f8");

                GitRepoClient client = new GitRepoClient(address, userName, password);

                CreateRepositoryDTO request = new CreateRepositoryDTO();
                request.setName(name);
                request.setDescription("Fabric8 Profiles generated project for container " + name);
                RepositoryDTO repository = client.createRepository(request);

                // create new repo with Gogs clone URL
                clonedRepo = Git.init().setDirectory(tempDirectory.toFile()).call();
                final RemoteAddCommand remoteAddCommand = clonedRepo.remoteAdd();
                remoteAddCommand.setName(remote);
                try {
                    remoteAddCommand.setUri(new URIish(repository.getCloneUrl()));
                } catch (URISyntaxException e1) {
                    throwException("Error creating remote repo ", repository.getCloneUrl(), e1);
                }
                remoteAddCommand.call();

                // add currentVersion branch
                clonedRepo.add().addFilepattern(".").call();
                clonedRepo.commit().setMessage("Adding version " + currentVersion).call();
                try {
                    clonedRepo.branchRename().setNewName(currentVersion).call();
                } catch (RefAlreadyExistsException ignore) {
                    // ignore
                }

            } else {
                throwException("Error cloning ", remoteUri, e);
            }
        }

        // handle missing remote branch
        if (!clonedRepo.getRepository().getBranch().equals(currentVersion)) {
            clonedRepo.branchCreate().setName(currentVersion)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
        }

        // move .git dir to parent and drop old source altogether
        // TODO things like .gitignore, etc. need to be handled, perhaps through Profiles??
        Files.move(tempDirectory.resolve(".git"), containerDir.resolve(".git"));

    } catch (GitAPIException e) {
        throwException("Error cloning ", remoteUri, e);
    } catch (IOException e) {
        throwException("Error copying files from ", remoteUri, e);
    } finally {
        // close clonedRepo
        if (clonedRepo != null) {
            try {
                clonedRepo.close();
            } catch (Exception ignored) {
            }
        }
        // cleanup tempDirectory
        try {
            ProfilesHelpers.deleteDirectory(tempDirectory);
        } catch (IOException e) {
            // ignore
        }
    }

    try (Git containerRepo = Git.open(containerDir.toFile())) {

        // diff with remote
        List<DiffEntry> diffEntries = containerRepo.diff().call();
        if (!diffEntries.isEmpty()) {

            // add all changes
            containerRepo.add().addFilepattern(".").call();

            // with latest Profile repo commit ID in message
            // TODO provide other identity properties
            containerRepo.commit().setMessage("Container updated for commit " + currentCommitId).call();

            // push to remote
            containerRepo.push().setRemote(remote).setCredentialsProvider(credentialsProvider).call();
        } else {
            LOG.debug("No changes to container" + name);
        }

    } catch (GitAPIException e) {
        throwException("Error processing container Git repo ", containerDir, e);
    } catch (IOException e) {
        throwException("Error reading container Git repo ", containerDir, e);
    }
}

From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java

License:Apache License

protected void generateArchetypeFromGitRepo(File outputDir, List<String> dirs, File cloneParentDir,
        String repoName, String repoURL, String tag) throws IOException {
    String archetypeFolderName = repoName + "-archetype";
    File projectDir = new File(outputDir, archetypeFolderName);
    File destDir = new File(projectDir, ARCHETYPE_RESOURCES_PATH);
    //File cloneDir = new File(projectDir, ARCHETYPE_RESOURCES_PATH);
    File cloneDir = new File(cloneParentDir, archetypeFolderName);
    cloneDir.mkdirs();/*w  w w . ja v  a2s . co m*/

    System.out.println("Cloning repo " + repoURL + " to " + cloneDir);
    cloneDir.getParentFile().mkdirs();
    if (cloneDir.exists()) {
        Files.recursiveDelete(cloneDir);
    }

    CloneCommand command = Git.cloneRepository().setCloneAllBranches(false).setURI(repoURL)
            .setDirectory(cloneDir);

    try {
        command.call();
    } catch (Throwable e) {
        LOG.error("Failed to command remote repo " + repoURL + " due: " + e.getMessage(), e);
        throw new IOException("Failed to command remote repo " + repoURL + " due: " + e.getMessage(), e);
    }

    // Try to checkout a specific tag.
    if (tag == null) {
        tag = System.getProperty("repo.tag", "").trim();
    }
    if (!tag.isEmpty()) {
        try {
            Git.open(cloneDir).checkout().setName(tag).call();
        } catch (Throwable e) {
            LOG.error("Failed checkout " + tag + " due: " + e.getMessage(), e);
            throw new IOException("Failed checkout " + tag + " due: " + e.getMessage(), e);
        }
    }

    File gitFolder = new File(cloneDir, ".git");
    Files.recursiveDelete(gitFolder);

    File pom = new File(cloneDir, "pom.xml");
    if (pom.exists()) {
        generateArchetype(cloneDir, pom, projectDir, false, dirs);
    } else {
        File from = cloneDir.getCanonicalFile();
        File to = destDir.getCanonicalFile();
        LOG.info("Copying git checkout from " + from + " to " + to);
        Files.copy(from, to);
    }

    String description = repoName.replace('-', ' ');

    dirs.add(repoName);
    File outputGitIgnoreFile = new File(projectDir, ".gitignore");
    if (!outputGitIgnoreFile.exists()) {
        ArchetypeUtils.writeGitIgnore(outputGitIgnoreFile);
    }
}

From source file:io.github.gitfx.util.GitFXGsonUtil.java

License:Apache License

public static boolean cloneGitRepository(String repoURL, String localPath) {
    try {//from w  w w  . j  a  v a  2s .c  o  m
        Git result = Git.cloneRepository().setURI(repoURL).setDirectory(new File(localPath)).call();
        result.close();
        return true;
    } catch (GitAPIException e) {
        logger.debug("Error creating Git repository", e.getMessage());
        return false;
    }
}

From source file:io.github.thefishlive.updater.Updater.java

License:Open Source License

public void run() {
    System.out.println("-------------------------");
    System.out.println(gitDir.getAbsolutePath());
    File updateFile = new File(basedir, "UPDATE");
    Git git = null;/*from   w  w w. ja va  2 s. c  om*/

    try {
        if (!gitDir.exists()) {
            git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote)
                    .setProgressMonitor(buildProgressMonitor()).call();

            System.out.println("Repository cloned");
        } else {
            updateFile.createNewFile();

            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repo = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                    .findGitDir() // scan up the file system tree
                    .build();

            git = new Git(repo);

            PullResult result = git.pull().setProgressMonitor(buildProgressMonitor()).call();

            if (!result.isSuccessful() || result.getMergeResult().getMergeStatus().equals(MergeStatus.MERGED)) {
                System.out.println("Update Failed");
                FileUtils.deleteDirectory(basedir);
                basedir.mkdir();
                System.out.println("Re-cloning repository");

                git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote)
                        .setProgressMonitor(buildProgressMonitor()).call();

                System.out.println("Repository cloned");
            }

            System.out.println("State: " + result.getMergeResult().getMergeStatus());
        }

        File configdir = new File("config");

        if (configdir.exists()) {
            FileUtils.copyDirectory(configdir, new File(basedir, "config"));
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        git.getRepository().close();
    }

    updateFile.delete();
    System.out.println("-------------------------");
}

From source file:io.gravitee.fetcher.git.GitFetcher.java

License:Apache License

@Override
public Resource fetch() throws FetcherException {
    File localPath = null;//from w  w w .j  a va 2s .  c  o m
    try {
        localPath = File.createTempFile("Gravitee-io", "");
        localPath.delete();
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new FetcherException("Unable to create temporary directory to fetch git repository", e);
    }

    try (Git result = Git.cloneRepository().setURI(this.gitFetcherConfiguration.getRepository())
            .setDirectory(localPath).setBranch(this.gitFetcherConfiguration.getBranchOrTag()).call()) {
        LOGGER.debug("Having repository: {}", result.getRepository().getDirectory());
        File fileToFetch = new File(result.getRepository().getWorkTree().getAbsolutePath() + File.separatorChar
                + gitFetcherConfiguration.getPath());
        result.close();
        final Resource resource = new Resource();
        resource.setContent(new FileInputStream(fileToFetch));
        return resource;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new FetcherException("Unable to fetch git content (" + e.getMessage() + ")", e);
    }
}

From source file:io.hawkcd.agent.services.GitMaterialService.java

License:Apache License

@Override
public String fetchMaterial(FetchMaterialTask task) {
    String errorMessage = null;/*  ww w  . j  a v a 2s.  c  o  m*/
    String materialPath = Paths.get(AgentConfiguration.getInstallInfo().getAgentPipelinesDir(),
            task.getPipelineName(), task.getDestination()).toString();
    GitMaterial definition = (GitMaterial) task.getMaterialDefinition();
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(definition.getRepositoryUrl());
    clone.setBranch(definition.getBranch());
    clone.setDirectory(new File(materialPath));
    clone.setCloneSubmodules(true);
    UsernamePasswordCredentialsProvider credentials = this.handleCredentials(definition);
    clone.setCredentialsProvider(credentials);
    try {
        Git git = clone.call();
        git.close();
    } catch (GitAPIException e) {
        errorMessage = e.getMessage();
    }

    return errorMessage;
}

From source file:io.hawkcd.materials.materialservices.GitService.java

License:Apache License

@Override
public GitMaterial cloneRepository(GitMaterial gitMaterial) {
    try {//  ww  w.j  a v a 2s  . c o m
        CredentialsProvider credentials = this.handleCredentials(gitMaterial);
        Git.cloneRepository().setURI(gitMaterial.getRepositoryUrl()).setCredentialsProvider(credentials)
                .setDirectory(new File(gitMaterial.getDestination())).setCloneSubmodules(true).call();

        gitMaterial.setErrorMessage("");

        return null;
    } catch (GitAPIException | JGitInternalException e) {
        gitMaterial.setErrorMessage(e.getMessage());
        return gitMaterial;
    }
}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java

License:Open Source License

private @Nonnull Git getActiveRepository(Repository repository) throws IOException {
    try {/* w  w w .  jav  a  2 s .c o m*/
        // Clone the bare repository
        File cloneDir = File.createTempFile("clone", "");

        if (cloneDir.exists()) {
            if (cloneDir.isDirectory()) {
                FileUtils.deleteDirectory(cloneDir);
            } else {
                if (!cloneDir.delete()) {
                    throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
                }
            }
        }
        if (!cloneDir.mkdirs()) {
            throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
        }

        String url = repository.getConfig().getString("remote", "origin", "url");
        Git gitClient = Git.cloneRepository().setCloneAllBranches(false)
                .setProgressMonitor(new CloneProgressMonitor(url))
                .setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();

        RemoteRemoveCommand remove = gitClient.remoteRemove();
        remove.setName("origin");
        remove.call();

        RemoteAddCommand add = gitClient.remoteAdd();
        add.setName("origin");
        add.setUri(new URIish(gitSource.getRemote()));
        add.call();

        if (GitUtils.isSshUrl(gitSource.getRemote())) {
            // Get committer info and credentials
            User user = User.current();
            if (user == null) {
                throw new ServiceException.UnauthorizedException("Not authenticated");
            }
            BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);

            // Make sure up-to-date and credentials work
            GitUtils.fetch(repository, privateKey);
        } else {
            FetchCommand fetch = gitClient.fetch();
            fetch.call();
        }

        if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + sourceBranch);
            checkout.setName(sourceBranch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();

            checkout = gitClient.checkout();
            checkout.setName(branch);
            checkout.setCreateBranch(true); // this *should* be a new branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        } else {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + branch);
            checkout.setName(branch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        }

        return gitClient;
    } catch (GitAPIException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
    }
}

From source file:io.macgyver.plugin.git.GitRepository.java

License:Apache License

public Git cloneInto(File dir, boolean isBare) throws GitAPIException {
    Preconditions.checkNotNull(dir);//from  ww w .  j a  v a  2  s  .  c  o m
    Preconditions.checkArgument(dir.exists(), "dir does not exist: " + dir.getAbsolutePath());

    CloneCommand cc = Git.cloneRepository().setURI(url).setBare(isBare).setDirectory(dir)
            .setCloneAllBranches(true);

    if ((!Strings.isNullOrEmpty(username)) || (!Strings.isNullOrEmpty(password))) {
        cc = cc.setCredentialsProvider(new UsernamePasswordCredentialsProvider(Strings.nullToEmpty(username),
                Strings.nullToEmpty(password)));
    }
    Git git = cc.call();
    return git;

}