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.cicomponents.git.impl.AbstractLocalGitMonitor.java

License:Mozilla Public License

@Override
void resume() {// w  w  w .  j a v  a 2s . co m
    if (!initialized) {
        initialized = true;
        executor.schedule(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                log.info("Cloning {}", repository);
                git = Git.cloneRepository().setURI(repository)
                        .setDirectory(new File(workingDirectory.getDirectory() + "/git")).call();
                git.getRepository().getListenerList()
                        .addRefsChangedListener(AbstractLocalGitMonitor.this::emitRevisionIfNecessary);

                onGitReady();

                resume(); // initialize pulls
            }
        }, 0, TimeUnit.SECONDS);
    }
    scheduledFuture = executor.scheduleWithFixedDelay(this::pull, 0, 10, TimeUnit.SECONDS);
}

From source file:org.cicomponents.git.impl.LatestRevisionGitBranchMonitor.java

License:Mozilla Public License

@SneakyThrows
protected void emitRevisionIfNecessary(RefsChangedEvent event) {
    synchronized (git) {
        ObjectId newHead = event.getRepository().findRef("refs/heads/" + branch).getObjectId();
        if (!newHead.equals(head)) {
            log.info("Detected refs change for {}, branch {}, old: {}, new: {}", git, branch, head, newHead);
            WorkingDirectory workingDirectory = getWorkingDirectory();
            String directory = workingDirectory.getDirectory() + "/git";
            Git clone = Git.cloneRepository()
                    .setURI("file://" + git.getRepository().getDirectory().getAbsolutePath())
                    .setDirectory(new File(directory)).call();
            Ref checkedOutRef = clone.checkout().setName(newHead.getName()).call();
            assert checkedOutRef == newHead;
            GitRevision resource = new LocalGitRevision(clone, newHead, workingDirectory);
            ResourceHolder<GitRevision> holder = new SimpleResourceHolder<>(resource);
            emit(holder);/*w  w w .j av a  2  s  . c o m*/
            head = newHead;
            persistentMap.put(head.getName(), head.getName());
        }
    }
}

From source file:org.cicomponents.github.impl.PullRequestMonitor.java

License:Mozilla Public License

@SneakyThrows
private void emit(GHPullRequest pr) {
    WorkingDirectory directory = environment.getWorkingDirectoryProvider().getDirectory();
    String path = directory.getDirectory() + "/git";
    String name = pr.getHead().getRepository().getFullName();
    log.info("Cloning fork {}#{}", name, pr.getHead().getSha());
    Git git = Git.cloneRepository().setURI("https://github.com/" + name).setDirectory(new File(path)).call();

    git.checkout().setName(pr.getHead().getSha()).call();
    log.info("Emitting fork {}#{}", name, pr.getHead().getSha());

    GithubPullRequest pullRequest = new GithubPullRequestResource(git, pr, directory);
    persistentMap.put(getIssueStatusKey(pr), new Date());
    emit(new SimpleResourceHolder<>(pullRequest));
}

From source file:org.commonjava.aprox.subsys.git.GitManager.java

License:Apache License

public GitManager(final GitConfig config) throws GitSubsystemException {
    this.config = config;
    rootDir = config.getContentDir();/*from   w  w  w. jav  a2  s.  c  o  m*/
    final String cloneUrl = config.getCloneFrom();

    boolean checkUpdate = false;
    if (cloneUrl != null) {
        logger.info("Cloning: {} into: {}", cloneUrl, rootDir);
        if (rootDir.isDirectory()) {
            checkUpdate = true;
        } else {
            final boolean mkdirs = rootDir.mkdirs();
            logger.info("git dir {} (mkdir result: {}; is directory? {}) contains:\n  {}", rootDir, mkdirs,
                    rootDir.isDirectory(), join(rootDir.listFiles(), "\n  "));
            try {
                Git.cloneRepository().setURI(cloneUrl).setDirectory(rootDir).setRemote("origin").call();
            } catch (final GitAPIException e) {
                throw new GitSubsystemException("Failed to clone remote URL: {} into: {}. Reason: {}", e,
                        cloneUrl, rootDir, e.getMessage());
            }
        }
    }

    final File dotGitDir = new File(rootDir, ".git");

    logger.info("Setting up git manager for: {}", dotGitDir);
    try {
        repo = new FileRepositoryBuilder().readEnvironment().setGitDir(dotGitDir).build();
    } catch (final IOException e) {
        throw new GitSubsystemException("Failed to create Repository instance for: {}. Reason: {}", e,
                dotGitDir, e.getMessage());
    }

    String[] preExistingFromCreate = null;
    if (!dotGitDir.isDirectory()) {
        preExistingFromCreate = rootDir.list();

        try {
            repo.create();
        } catch (final IOException e) {
            throw new GitSubsystemException("Failed to create git repo: {}. Reason: {}", e, rootDir,
                    e.getMessage());
        }
    }

    String originUrl = repo.getConfig().getString("remote", "origin", "url");
    if (originUrl == null) {
        originUrl = cloneUrl;
        logger.info("Setting origin URL: {}", originUrl);

        repo.getConfig().setString("remote", "origin", "url", originUrl);

        repo.getConfig().setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    }

    String email = repo.getConfig().getString("user", null, "email");

    if (email == null) {
        email = config.getUserEmail();
    }

    if (email == null) {
        try {
            email = "aprox@" + InetAddress.getLocalHost().getCanonicalHostName();

        } catch (final UnknownHostException e) {
            throw new GitSubsystemException("Failed to resolve 'localhost'. Reason: {}", e, e.getMessage());
        }
    }

    if (repo.getConfig().getString("user", null, "email") == null) {
        repo.getConfig().setString("user", null, "email", email);
    }

    this.email = email;

    git = new Git(repo);

    if (preExistingFromCreate != null && preExistingFromCreate.length > 0) {
        addAndCommitPaths(new ChangeSummary(ChangeSummary.SYSTEM_USER, "Committing pre-existing files."),
                preExistingFromCreate);
    }

    if (checkUpdate) {
        pullUpdates();
    }
}

From source file:org.commonjava.indy.subsys.git.GitManager.java

License:Apache License

public GitManager(final GitConfig config) throws GitSubsystemException {
    this.config = config;
    rootDir = config.getContentDir();//ww  w .j  a v  a  2s  .c om
    final String cloneUrl = config.getCloneFrom();

    boolean checkUpdate = false;
    if (cloneUrl != null) {
        logger.info("Cloning: {} into: {}", cloneUrl, rootDir);
        if (rootDir.isDirectory()) {
            checkUpdate = true;
        } else {
            final boolean mkdirs = rootDir.mkdirs();
            logger.info("git dir {} (mkdir result: {}; is directory? {}) contains:\n  {}", rootDir, mkdirs,
                    rootDir.isDirectory(), join(rootDir.listFiles(), "\n  "));
            try {
                Git.cloneRepository().setURI(cloneUrl).setDirectory(rootDir).setRemote("origin").call();
            } catch (final GitAPIException e) {
                throw new GitSubsystemException("Failed to clone remote URL: {} into: {}. Reason: {}", e,
                        cloneUrl, rootDir, e.getMessage());
            }
        }
    }

    final File dotGitDir = new File(rootDir, ".git");

    logger.info("Setting up git manager for: {}", dotGitDir);
    try {
        repo = new FileRepositoryBuilder().readEnvironment().setGitDir(dotGitDir).build();
    } catch (final IOException e) {
        throw new GitSubsystemException("Failed to create Repository instance for: {}. Reason: {}", e,
                dotGitDir, e.getMessage());
    }

    String[] preExistingFromCreate = null;
    if (!dotGitDir.isDirectory()) {
        preExistingFromCreate = rootDir.list();

        try {
            repo.create();
        } catch (final IOException e) {
            throw new GitSubsystemException("Failed to create git repo: {}. Reason: {}", e, rootDir,
                    e.getMessage());
        }
    }

    String originUrl = repo.getConfig().getString("remote", "origin", "url");
    if (originUrl == null) {
        originUrl = cloneUrl;
        logger.info("Setting origin URL: {}", originUrl);

        repo.getConfig().setString("remote", "origin", "url", originUrl);

        repo.getConfig().setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    }

    String email = repo.getConfig().getString("user", null, "email");

    if (email == null) {
        email = config.getUserEmail();
    }

    if (email == null) {
        try {
            email = "indy@" + InetAddress.getLocalHost().getCanonicalHostName();

        } catch (final UnknownHostException e) {
            throw new GitSubsystemException("Failed to resolve 'localhost'. Reason: {}", e, e.getMessage());
        }
    }

    if (repo.getConfig().getString("user", null, "email") == null) {
        repo.getConfig().setString("user", null, "email", email);
    }

    this.email = email;

    git = new Git(repo);

    if (preExistingFromCreate != null && preExistingFromCreate.length > 0) {
        addPaths(new ChangeSummary(SYSTEM_USER, "Committing pre-existing files."), preExistingFromCreate);
        commit();
    }

    if (checkUpdate) {
        pullUpdates();
    }
}

From source file:org.commonwl.view.git.GitService.java

License:Apache License

/**
 * Clones a Git repository//from   ww w . ja v a2s .c om
 * @param repoUrl the url of the Git repository
 * @param directory the directory to clone the repo into
 * @return a Git instance
 * @throws GitAPIException if any error occurs cloning the repo
 */
protected Git cloneRepo(String repoUrl, File directory) throws GitAPIException {
    return Git.cloneRepository().setCloneSubmodules(cloneSubmodules).setURI(repoUrl).setDirectory(directory)
            .setCloneAllBranches(true).call();
}

From source file:org.craftercms.commons.git.impl.GitRepositoryFactoryImpl.java

License:Open Source License

@Override
public GitRepository clone(String remoteUrl, File localDir) throws GitException {
    try {//w w  w.  j  a v a  2s  . c  o m
        Git git = Git.cloneRepository().setURI(remoteUrl).setDirectory(localDir).call();

        logger.info("Remote repository {} cloned into local dir {}", remoteUrl, localDir);

        return new GitRepositoryImpl(git);
    } catch (GitAPIException e) {
        throw new GitException("Error cloning remote repository " + remoteUrl + " into local dir " + localDir,
                e);
    }
}

From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testPush() throws Exception {
    File masterRepoDir = tmpDir.newFolder("master.git");
    File cloneRepoDir = tmpDir.newFolder("clone");

    Git masterGit = Git.init().setDirectory(masterRepoDir).setBare(true).call();
    Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir)
            .call();/*  ww  w  .j a v a  2s. co m*/
    GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit);

    File testFile = new File(cloneRepoDir, "test");
    testFile.createNewFile();

    cloneGit.add().addFilepattern("test").call();
    cloneGit.commit().setMessage("Test message").call();

    cloneRepo.push();

    List<RevCommit> commits = IterableUtils.toList(masterGit.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());

    List<String> committedFiles = getCommittedFiles(masterGit.getRepository(), commits.get(0));

    assertNotNull(committedFiles);
    assertEquals(1, committedFiles.size());
    assertEquals("test", committedFiles.get(0));
}

From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testPull() throws Exception {
    File masterRepoDir = tmpDir.newFolder("master");
    File cloneRepoDir = tmpDir.newFolder("clone");

    Git masterGit = Git.init().setDirectory(masterRepoDir).call();
    Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir)
            .call();//from w w  w  . j  a  v a 2 s.c om
    GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit);

    File testFile = new File(masterRepoDir, "test");
    testFile.createNewFile();

    masterGit.add().addFilepattern("test").call();
    masterGit.commit().setMessage("Test message").call();

    cloneRepo.pull();

    List<RevCommit> commits = IterableUtils.toList(cloneGit.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());

    List<String> committedFiles = getCommittedFiles(cloneGit.getRepository(), commits.get(0));

    assertNotNull(committedFiles);
    assertEquals(1, committedFiles.size());
    assertEquals("test", committedFiles.get(0));
}

From source file:org.craftercms.deployer.utils.GitUtils.java

License:Open Source License

public static Git cloneRemoteRepository(String remoteRepositoryUrl, File localRepositoryFolder)
        throws GitAPIException {
    return Git.cloneRepository().setURI(remoteRepositoryUrl).setDirectory(localRepositoryFolder).call();
}