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.n52.wps.repository.git.GitAlgorithmRepository.java

License:Open Source License

private File[] cloneToLocalRepository() throws GitAlgorithmsRepositoryConfigException {
    try {//  w  w w .j  av  a 2 s . co m
        Git git = Git.cloneRepository().setDirectory(new File(localPath)).setURI(remotePath).call();
        return getFiles(git.getRepository().getWorkTree());
    } catch (GitAPIException e) {
        throw new GitAlgorithmsRepositoryConfigException("Cloning failed: " + remotePath, e);
    }
}

From source file:org.n52.wps.repository.git.GitAlgorithmRepositoryTest.java

License:Open Source License

@Test
public void initLocalGitRepository() throws IOException, GitAPIException {
    File file = cleanRepository.resolve("hello_world.txt").toFile();
    file.createNewFile();/*from   w ww . j a v a 2  s.c o m*/

    Git repoGit = Git.open(cleanRepository.toFile());
    repoGit.add().addFilepattern(file.getPath());
    repoGit.commit().setMessage("initial commit").call();

    File wc = testRoot.newFolder("workingCopy");

    Git wcGit = Git.cloneRepository().setURI(cleanRepository.toUri().toString()).setDirectory(wc).call();

    int i = 0;
    Iterator<RevCommit> commits = wcGit.log().all().call().iterator();
    while (commits.hasNext()) {
        i++;
        commits.next();
    }
    MatcherAssert.assertThat(i, Is.is(1));
}

From source file:org.n52.wps.repository.git.GitTest.java

License:Open Source License

@Before
public void init() throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    String tmpdir = System.getProperty("java.io.tmpdir");
    localPath = (tmpdir.endsWith(File.separator) ? tmpdir : (tmpdir + File.separator)) + "tmp-git-dir-"
            + UUID.randomUUID().toString().substring(0, 5);
    new File(localPath).deleteOnExit();
    remotePath = "https://github.com/bpross-52n/scriptsNprocesses.git";
    localRepo = new FileRepository(localPath + File.separator + ".git");
    logger.info("Cloning {} into {}", remotePath, localPath);
    Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call();
    logger.info("Cloning succeeded");
    logger.info("Creating new Git repository {}", localPath);
    git = new Git(localRepo);
}

From source file:org.nuxeo.lang.ext.LangExtAssistantRoot.java

License:Open Source License

@Override
protected void initialize(Object... args) {
    super.initialize(args);
    if (mergedProp.isEmpty()) {
        try {/*from   w w  w. j av a2  s. c o  m*/
            File localGitRepo = new File(LOCAL_PATH);
            if (!localGitRepo.exists()) {
                Git.cloneRepository().setURI(GIT_REPO_REMOTE_PATH).setDirectory(localGitRepo).call();
            }
            git = Git.open(localGitRepo);
            localRepo = git.getRepository();
            Properties enProp = loadProperties("en", String.format(MESSAGES_FILENAME, "_en"));
            Properties defaultProp = loadProperties("default", String.format(MESSAGES_FILENAME, ""));
            mergedProp.putAll(defaultProp);
            mergedProp.putAll(enProp);
            Enumeration<Object> keys = mergedProp.keys();
            while (keys.hasMoreElements()) {
                sortedKeys.add((String) keys.nextElement());
            }
            Collections.sort(sortedKeys);
            URL classesUrl = getClass().getResource("/");
            File f = new File(classesUrl.toURI());
            String[] messagesFiles = f.list();
            for (String messagesFile : messagesFiles) {
                Matcher m = messagesPattern.matcher(messagesFile);
                if (m.matches()) {
                    String languageKey = m.group(2);
                    loadProperties(languageKey, messagesFile);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("could not initialize webengine module " + this, e);
        }
    }
}

From source file:org.ocpsoft.redoculous.model.impl.GitRepository.java

License:Open Source License

private void cloneRepository() {
    File refsDir = getRefsDir();/*w w  w  .j ava 2s. c om*/
    File cacheDir = getCacheDir();

    if (!getRepoDir().exists()) {
        RedoculousProgressMonitor monitor = new RedoculousProgressMonitor();
        try {
            getRepoDir().mkdirs();
            refsDir.mkdirs();
            cacheDir.mkdirs();

            Git git = Git.cloneRepository().setURI(getUrl()).setRemote("origin").setCloneAllBranches(true)
                    .setDirectory(getRepoDir()).setProgressMonitor(monitor).call();

            try {
                git.fetch().setRemote("origin").setTagOpt(TagOpt.FETCH_TAGS).setThin(false).setTimeout(10)
                        .setProgressMonitor(monitor).call();
            } finally {
                git.getRepository().close();
            }

        } catch (Exception e) {
            throw new RuntimeException("Could not clone repository [" + getUrl() + "] [" + getKey() + "]", e);
        }
    }
}

From source file:org.omegat.core.team.GITRemoteRepository.java

License:Open Source License

public void checkoutFullProject(String repositoryURL) throws Exception {
    Log.logInfoRB("GIT_START", "clone");
    CloneCommand c = Git.cloneRepository();
    c.setURI(repositoryURL);//from   ww  w.  ja va  2  s  .  com
    c.setDirectory(localDirectory);
    try {
        c.call();
    } catch (InvalidRemoteException e) {
        FileUtil.deleteTree(localDirectory);
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) {
            BadRepositoryException bre = new BadRepositoryException(
                    ((org.eclipse.jgit.errors.NoRemoteRepositoryException) cause).getLocalizedMessage());
            bre.initCause(e);
            throw bre;
        }
        throw e;
    }
    repository = Git.open(localDirectory).getRepository();
    new Git(repository).submoduleInit().call();
    new Git(repository).submoduleUpdate().call();

    //Deal with line endings. A normalized repo has LF line endings. 
    //OmegaT uses line endings of OS for storing tmx files.
    //To do auto converting, we need to change a setting:
    StoredConfig config = repository.getConfig();
    if ("\r\n".equals(FileUtil.LINE_SEPARATOR)) {
        //on windows machines, convert text files to CRLF
        config.setBoolean("core", null, "autocrlf", true);
    } else {
        //on Linux/Mac machines (using LF), don't convert text files
        //but use input format, unchanged.
        //NB: I don't know correct setting for OS'es like MacOS <= 9, 
        // which uses CR. Git manual only speaks about converting from/to
        //CRLF, so for CR, you probably don't want conversion either.
        config.setString("core", null, "autocrlf", "input");
    }
    config.save();
    myCredentialsProvider.saveCredentials();
    Log.logInfoRB("GIT_FINISH", "clone");
}

From source file:org.omegat.core.team2.impl.GITRemoteRepository2.java

License:Open Source License

@Override
public void init(RepositoryDefinition repo, File dir, ProjectTeamSettings teamSettings) throws Exception {
    repositoryURL = repo.getUrl();//from  ww  w.ja  v a2s . com
    localDirectory = dir;

    String predefinedUser = repo.getOtherAttributes().get(new QName("gitUsername"));
    String predefinedPass = repo.getOtherAttributes().get(new QName("gitPassword"));
    String predefinedFingerprint = repo.getOtherAttributes().get(new QName("gitFingerprint"));
    ((GITCredentialsProvider) CredentialsProvider.getDefault()).setPredefinedCredentials(repositoryURL,
            predefinedUser, predefinedPass, predefinedFingerprint);
    ((GITCredentialsProvider) CredentialsProvider.getDefault()).setTeamSettings(teamSettings);

    File gitDir = new File(localDirectory, ".git");
    if (gitDir.exists() && gitDir.isDirectory()) {
        // already cloned
        repository = Git.open(localDirectory).getRepository();
    } else {
        Log.logInfoRB("GIT_START", "clone");
        CloneCommand c = Git.cloneRepository();
        c.setURI(repositoryURL);
        c.setDirectory(localDirectory);
        try {
            c.call();
        } catch (InvalidRemoteException e) {
            if (localDirectory.exists()) {
                deleteDirectory(localDirectory);
            }
            Throwable cause = e.getCause();
            if (cause != null && cause instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) {
                BadRepositoryException bre = new BadRepositoryException(
                        ((org.eclipse.jgit.errors.NoRemoteRepositoryException) cause).getLocalizedMessage());
                bre.initCause(e);
                throw bre;
            }
            throw e;
        }
        repository = Git.open(localDirectory).getRepository();
        try (Git git = new Git(repository)) {
            git.submoduleInit().call();
            git.submoduleUpdate().call();
        }

        // Deal with line endings. A normalized repo has LF line endings.
        // OmegaT uses line endings of OS for storing tmx files.
        // To do auto converting, we need to change a setting:
        StoredConfig config = repository.getConfig();
        if ("\r\n".equals(System.lineSeparator())) {
            // on windows machines, convert text files to CRLF
            config.setBoolean("core", null, "autocrlf", true);
        } else {
            // on Linux/Mac machines (using LF), don't convert text files
            // but use input format, unchanged.
            // NB: I don't know correct setting for OS'es like MacOS <= 9,
            // which uses CR. Git manual only speaks about converting from/to
            // CRLF, so for CR, you probably don't want conversion either.
            config.setString("core", null, "autocrlf", "input");
        }
        config.save();
        Log.logInfoRB("GIT_FINISH", "clone");
    }

    // cleanup repository
    try (Git git = new Git(repository)) {
        git.reset().setMode(ResetType.HARD).call();
    }
}

From source file:org.onexus.resource.manager.internal.providers.GitProjectProvider.java

License:Apache License

@Override
protected void importProject() {

    try {/*from   w  w w . j a v  a  2s . c  o m*/

        File projectFolder = getProjectFolder();

        boolean cloneDone = true;

        if (!projectFolder.exists()) {
            projectFolder.mkdir();
            cloneDone = false;
        }

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setWorkTree(projectFolder).readEnvironment().build();
        Git git = new Git(repository);

        if (cloneDone) {
            PullCommand pull = git.pull();
            pull.call();

        } else {
            CloneCommand clone = git.cloneRepository();
            clone.setBare(false);
            clone.setCloneAllBranches(true);
            clone.setDirectory(projectFolder).setURI(getProjectUrl().toString());
            clone.call();

            //TODO Checkout branch
        }

    } catch (Exception e) {
        LOGGER.error("Importing project '" + getProjectUrl() + "'", e);
        throw new InvalidParameterException("Error importing project. " + e.getMessage());
    }
}

From source file:org.opentravel.otm.forum2016.GitRepositorySynchronizer.java

License:Apache License

/**
 * Synchronizes all content from the remote repository.  If the repository does
 * not yet exist on the local file system, it is cloned from the remote repsitory
 * URL.  If a clone has already been created, all local changes will be discarded
 * and managed files updated with their most recent versions from the remote
 * repository.//from w  w  w. j  av  a 2s.  c o  m
 * 
 * @throws IOException  thrown if the local repository cannot be synchronized
 */
public void synchronizeContent() throws IOException {
    boolean repositoryExists = false;

    if (isRepository()) {
        if (!(repositoryExists = isValidRepository())) {
            deleteLocalRepository(localRepository);
        }
    }

    if (!repositoryExists) { // create a clone
        try {
            log.info("Cloning remote Git repository - " + repositoryUrl);
            Git.cloneRepository().setURI(repositoryUrl).setDirectory(localRepository)
                    .setTransportConfigCallback(getTransportConfigCallback()).setBranch(branch).call();

        } catch (GitAPIException e) {
            throw new IOException("Error cloning Git repository.", e);
        }

    } else { // refresh the existing clone
        try (Git git = new Git(gitRepo)) {
            log.info("Refreshing contents of local Git repository.");
            git.reset().setMode(ResetType.HARD).call();
            git.pull().setTransportConfigCallback(getTransportConfigCallback()).call();

        } catch (GitAPIException e) {
            throw new IOException("Error cloning Git repository.", e);
        }
    }
}

From source file:org.ossmeter.platform.vcs.git.GitManager.java

License:Open Source License

protected Git getGit(GitRepository repository) throws Exception {
    String localPath = localBaseDirectory + makeSafe(repository.getUrl()); // FIXME local stora1ge

    Git git;//w ww .j a va2s  .c  o m
    File gitDir = new File(localPath);
    if (gitDir.exists()) {
        git = new Git(new FileRepository(localPath + "/.git"));
        git.pull().call();
    } else {
        git = Git.cloneRepository().setURI(repository.getUrl()).setDirectory(gitDir).call();
    }
    return git;
}