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:models.PullRequestTest.java

License:Apache License

@Before
public void initRepositories() throws Exception {
    GitRepository.setRepoPrefix(REPO_PREFIX);

    app = support.Helpers.makeTestApplication();
    Helpers.start(app);//from   w ww . jav  a 2s .c om

    Project project = Project.findByOwnerAndProjectName("yobi", "projectYobi");
    forkedProject = Project.findByOwnerAndProjectName("yobi", "projectYobi-1");

    // 1. projectYobi  
    RepositoryService.createRepository(project);

    // 2. projectYobi ?  
    {
        String localRepoPath = LOCAL_REPO_PREFIX + project.name;
        Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(project))
                .setDirectory(new File(localRepoPath)).call();
        Repository repo = git.getRepository();
        baseCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncat\n", "commit 1");
        git.push().setRefSpecs(new RefSpec("+refs/heads/master:refs/heads/master")).call();
    }

    // 3. ??? ? ??  
    GitRepository.cloneLocalRepository(project, forkedProject);

    // 4. ??? ?     ? ? ? 
    {
        String localRepoPath = LOCAL_REPO_PREFIX + forkedProject.name;
        Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(forkedProject))
                .setDirectory(new File(localRepoPath)).call();
        git.branchCreate().setName("fix/1").call();
        git.checkout().setName("fix/1").call();
        Repository repo = git.getRepository();
        assertThat(repo.isBare()).describedAs("projectYobi-1 must be non-bare").isFalse();
        firstCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncorn\n", "commit 1");
        secondCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncake\n", "commit 2");
        git.push().setRefSpecs(new RefSpec("+refs/heads/fix/1:refs/heads/fix/1")).call();
    }

    // 5.   projectYobi? pullrequest .
    pullRequest = PullRequest.createNewPullRequest(forkedProject, project, "refs/heads/fix/1",
            "refs/heads/master");
    pullRequest.save();

    // 6. attempt merge
    boolean isConflict = pullRequest.updateMerge().conflicts();

    assertThat(isConflict).isFalse();
}

From source file:neembuu.uploader.zip.generator.UpdaterGenerator.java

License:Apache License

/**
 * Clone GIT repository from sourceforge.
 *
 * @param gitDirectory The directory of Git.
 *//*from  w ww  .j a va2s . c  om*/
private void gitClone(File gitDirectory) {
    try {
        git = Git.cloneRepository().setDirectory(gitDirectory).setURI(env.gitURI())
                //.setURI("http://git.code.sf.net/p/neembuuuploader/gitcode")
                .setProgressMonitor(new TextProgressMonitor()).call();

        for (Ref f : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            git.checkout().setName(f.getName()).call();
            System.out.println(
                    "checked out branch " + f.getName() + ". HEAD: " + git.getRepository().getRef("HEAD"));
        }
        // try to checkout branches by specifying abbreviated names
        git.checkout().setName("master").call();
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.orpiske.ssps.common.scm.git.GitSCM.java

License:Apache License

/**
 * Clones de repository//from  w  w w  .j  av  a 2s.co m
 * @param url URL
 * @param repositoryDir destination directory
 * @throws ScmCheckoutException if unable to checkout
 */
private void clone(final String url, final File repositoryDir) throws ScmCheckoutException {
    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(url);
    cloneCommand.setDirectory(repositoryDir);
    cloneCommand.setProgressMonitor(new TextProgressMonitor());

    //final String branch = repositoryInfo.getRepositoryVersion();
    if (branch != null && !branch.getName().isEmpty()) {
        cloneCommand.setBranch(branch.getName());
    }

    try {
        logger.info("SCM repository does not exist. Cloning from " + url);

        cloneCommand.call();
    } catch (InvalidRemoteException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }

        throw new ScmCheckoutException(e.getMessage(), e);
    } catch (TransportException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }

        throw new ScmCheckoutException(e.getMessage(), e);
    } catch (GitAPIException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }

        throw new ScmCheckoutException(e.getMessage(), e);
    }
}

From source file:net.riezebos.thoth.content.impl.GitContentManager.java

License:Apache License

@Override
protected synchronized String cloneOrPull() throws ContentManagerException {
    StringBuilder log = new StringBuilder();
    try {//ww  w .j av  a  2 s. c  om
        Configuration config = getConfiguration();
        RepositoryDefinition repositoryDefinition = getContextDefinition().getRepositoryDefinition();
        String repositoryUrl = repositoryDefinition.getLocation();
        String workspaceLocation = config.getWorkspaceLocation();
        if (StringUtils.isBlank(workspaceLocation))
            throw new IllegalArgumentException("No environment variable or system variable named "
                    + Configuration.WORKSPACELOCATION + " was set");
        File file = new File(workspaceLocation);
        if (!file.isDirectory()) {
            severe(log, "The library path " + workspaceLocation
                    + " does not exist. Cannot initialize content manager");
        } else {
            try {
                String contextFolder = getContextFolder();
                File target = new File(contextFolder);
                CredentialsProvider credentialsProvider = getCredentialsProvider();

                if (target.isDirectory()) {
                    try (Git repos = getRepository()) {

                        Repository repository = repos.getRepository();
                        ObjectId oldHead = repository.resolve(HEAD_TREE);

                        PullResult pullResult = repos.pull().setCredentialsProvider(credentialsProvider).call();
                        ObjectId newHead = repository.resolve(HEAD_TREE);
                        boolean changes = (oldHead == null && newHead != null)//
                                || (oldHead != null && !oldHead.equals(newHead));
                        if (changes)
                            notifyContextContentsChanged();

                        String message = pullResult.isSuccessful() ? ": Pull successful, "
                                : ": Pull of failed, ";
                        message += changes ? CHANGES_DETECTED_MSG : NO_CHANGES_DETECTED_MSG;
                        info(log, getContextName() + message);

                        setLatestRefresh(new Date());
                    } catch (Exception e) {
                        severe(log, e);
                    }
                } else {
                    info(log, getContextName() + ": Cloning from " + repositoryUrl + " to " + contextFolder);
                    target.mkdirs();
                    try (Git result = Git.cloneRepository()//
                            .setURI(repositoryUrl)//
                            .setBranch(getBranch())//
                            .setCredentialsProvider(credentialsProvider)//
                            .setDirectory(target).call()) {
                        info(log, getContextName() + ": Cloned repository: "
                                + result.getRepository().getDirectory());
                        setLatestRefresh(new Date());
                        notifyContextContentsChanged();
                    } catch (Exception e) {
                        severe(log, e);
                    }
                }
            } catch (Exception e) {
                severe(log, e);
            }
        }

    } catch (Exception e) {
        throw new ContentManagerException(e);
    }

    return log.toString().trim();
}

From source file:net.sf.authorship.strategies.GitStrategy.java

License:Open Source License

/**
 * Clones remote repository into local folder.
 * /* w  w  w  .  j a  va 2  s .c o  m*/
 * @param readOnlyUrl
 *            read only Git repository URL.
 * @param folder
 *            local repository folder.
 */
private void cloneRepository(String readOnlyUrl, String folder) throws IOException {
    Git.cloneRepository().setURI(readOnlyUrl).setDirectory(new File(folder)).call();
}

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

License:Open Source License

protected String install(String path) throws Exception {
    //staticDir.mkdirs();
    Git result = null;//from  ww  w.  j ava  2s .c  om
    try {
        File installLogDir = new File(staticDir, "logs");
        installLogDir.mkdirs();
        //make log name
        String logFile = "output.log";
        File output = new File(installLogDir, logFile);
        File destDir = new File(staticDir, SLASH + path);
        destDir.mkdirs();
        String gitPath = github + path + ".git";
        logger.debug("Cloning from " + gitPath + " to " + destDir.getAbsolutePath());
        FileUtils.writeStringToFile(output,
                "Updating from " + gitPath + " to " + destDir.getAbsolutePath() + "\n", false);
        try {
            result = Git.cloneRepository().setURI(gitPath).setDirectory(destDir).call();
            result.fetch().setRemote(gitPath);
            logger.debug("Cloned " + gitPath + " repository: " + result.getRepository().getDirectory());
            FileUtils.writeStringToFile(output,
                    "DONE: Cloned " + gitPath + " repository: " + result.getRepository().getDirectory(), true);
        } catch (Exception e) {
            FileUtils.writeStringToFile(output, e.getMessage(), true);
            FileUtils.writeStringToFile(output, e.getStackTrace().toString(), true);
            logger.debug("Error updating " + gitPath + " repository: " + e.getMessage(), e);
        }
        /*try{
           //now run npm install
           runNpmInstall(output, destDir);
        }catch(Exception e){
           FileUtils.writeStringToFile(output, e.getMessage(),true);
           FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true);
           logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e);
        }*/
        return logFile;

    } finally {
        if (result != null)
            result.close();
    }

}

From source file:org.ajoberstar.gradle.git.tasks.GitClone.java

License:Apache License

/**
 * Clones a Git repository as configured.
 *//*from   w  ww. j  a v  a2s . c  om*/
@TaskAction
public void cloneRepo() {
    CloneCommand cmd = Git.cloneRepository();
    TransportAuthUtil.configure(cmd, this);
    cmd.setURI(getUri().toString());
    cmd.setRemote(getRemote());
    cmd.setBare(getBare());
    cmd.setNoCheckout(!getCheckout());
    cmd.setBranch(getRef());
    cmd.setBranchesToClone(getBranchesToClone());
    cmd.setCloneAllBranches(getCloneAllBranches());
    cmd.setDirectory(getDestinationDir());
    try {
        cmd.call();
    } catch (InvalidRemoteException e) {
        throw new GradleException("Invalid remote specified: " + getRemote(), e);
    } catch (TransportException e) {
        throw new GradleException("Problem with transport.", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem with clone.", e);
    }
    //TODO add progress monitor to log progress to Gradle status bar
}

From source file:org.apache.gobblin.service.modules.core.GitConfigMonitorTest.java

License:Apache License

@BeforeClass
public void setup() throws Exception {
    cleanUpDir(TEST_DIR);/* w w w .  ja v a 2s. co  m*/

    // Create a bare repository
    RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED);
    this.remoteRepo = fileKey.open(false);
    this.remoteRepo.create(true);

    this.gitForPush = Git.cloneRepository().setURI(this.remoteRepo.getDirectory().getAbsolutePath())
            .setDirectory(cloneDir).call();

    // push an empty commit as a base for detecting changes
    this.gitForPush.commit().setMessage("First commit").call();
    this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();

    this.config = ConfigBuilder.create()
            .addPrimitive(
                    GitConfigMonitor.GIT_CONFIG_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_URI,
                    this.remoteRepo.getDirectory().getAbsolutePath())
            .addPrimitive(
                    GitConfigMonitor.GIT_CONFIG_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_DIR,
                    TEST_DIR + "/jobConfig")
            .addPrimitive(FlowCatalog.FLOWSPEC_STORE_DIR_KEY, TEST_DIR + "flowCatalog")
            .addPrimitive(ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5).build();

    this.flowCatalog = new FlowCatalog(config);
    this.flowCatalog.startAsync().awaitRunning();
    this.gitConfigMonitor = new GitConfigMonitor(this.config, this.flowCatalog);
    this.gitConfigMonitor.setActive(true);
}

From source file:org.apache.gobblin.service.modules.core.GitFlowGraphMonitorTest.java

License:Apache License

@BeforeClass
public void setUp() throws Exception {
    cleanUpDir(TEST_DIR);/*from   www.  ja  v a  2s.  c o  m*/

    // Create a bare repository
    RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED);
    this.remoteRepo = fileKey.open(false);
    this.remoteRepo.create(true);

    this.gitForPush = Git.cloneRepository().setURI(this.remoteRepo.getDirectory().getAbsolutePath())
            .setDirectory(cloneDir).call();

    // push an empty commit as a base for detecting changes
    this.gitForPush.commit().setMessage("First commit").call();
    this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();

    URI topologyCatalogUri = this.getClass().getClassLoader().getResource("topologyspec_catalog").toURI();
    Map<URI, TopologySpec> topologySpecMap = MultiHopFlowCompilerTest.buildTopologySpecMap(topologyCatalogUri);

    this.config = ConfigBuilder.create()
            .addPrimitive(
                    GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                            + ConfigurationKeys.GIT_MONITOR_REPO_URI,
                    this.remoteRepo.getDirectory().getAbsolutePath())
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TEST_DIR + "/git-flowgraph")
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5)
            .build();

    // Create a FSFlowTemplateCatalog instance
    URI flowTemplateCatalogUri = this.getClass().getClassLoader().getResource("template_catalog").toURI();
    Properties properties = new Properties();
    properties.put(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY,
            flowTemplateCatalogUri.toString());
    Config config = ConfigFactory.parseProperties(properties);
    Config templateCatalogCfg = config.withValue(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY,
            config.getValue(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY));
    this.flowCatalog = Optional.of(new FSFlowTemplateCatalog(templateCatalogCfg));

    //Create a FlowGraph instance with defaults
    this.flowGraph = new BaseFlowGraph();

    this.gitFlowGraphMonitor = new GitFlowGraphMonitor(this.config, this.flowCatalog, this.flowGraph,
            topologySpecMap, new CountDownLatch(1));
    this.gitFlowGraphMonitor.setActive(true);
}

From source file:org.apache.gobblin.service.modules.core.GobblinServiceManagerTest.java

License:Apache License

@BeforeClass
public void setup() throws Exception {
    cleanUpDir(SERVICE_WORK_DIR);//from   w w  w  .j  a v  a  2 s.com
    cleanUpDir(SPEC_STORE_PARENT_DIR);
    ITestMetastoreDatabase testMetastoreDatabase = TestMetastoreDatabaseFactory.get();

    KafkaTestBase kafkaTestHelper = new KafkaTestBase();
    kafkaTestHelper.startServers();

    Properties serviceCoreProperties = new Properties();
    serviceCoreProperties.put(ConfigurationKeys.STATE_STORE_DB_USER_KEY, "testUser");
    serviceCoreProperties.put(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, "testPassword");
    serviceCoreProperties.put(ConfigurationKeys.STATE_STORE_DB_URL_KEY, testMetastoreDatabase.getJdbcUrl());
    serviceCoreProperties.put("zookeeper.connect", kafkaTestHelper.getZkConnectString());
    serviceCoreProperties.put(ConfigurationKeys.STATE_STORE_FACTORY_CLASS_KEY,
            MysqlJobStatusStateStoreFactory.class.getName());

    serviceCoreProperties.put(ConfigurationKeys.TOPOLOGYSPEC_STORE_DIR_KEY, TOPOLOGY_SPEC_STORE_DIR);
    serviceCoreProperties.put(FlowCatalog.FLOWSPEC_STORE_DIR_KEY, FLOW_SPEC_STORE_DIR);
    serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_TOPOLOGY_NAMES_KEY,
            TEST_GOBBLIN_EXECUTOR_NAME);
    serviceCoreProperties.put(
            ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".description",
            "StandaloneTestExecutor");
    serviceCoreProperties.put(
            ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".version",
            FlowSpec.Builder.DEFAULT_VERSION);
    serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".uri",
            "gobblinExecutor");
    serviceCoreProperties.put(
            ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".specExecutorInstance",
            "org.apache.gobblin.service.InMemorySpecExecutor");
    serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME
            + ".specExecInstance.capabilities", TEST_SOURCE_NAME + ":" + TEST_SINK_NAME);

    serviceCoreProperties.put(ServiceConfigKeys.GOBBLIN_SERVICE_GIT_CONFIG_MONITOR_ENABLED_KEY, true);
    serviceCoreProperties.put(
            GitConfigMonitor.GIT_CONFIG_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_URI,
            GIT_REMOTE_REPO_DIR);
    serviceCoreProperties.put(
            GitConfigMonitor.GIT_CONFIG_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_DIR,
            GIT_LOCAL_REPO_DIR);
    serviceCoreProperties.put(
            GitConfigMonitor.GIT_CONFIG_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL,
            5);

    serviceCoreProperties.put(
            FsJobStatusRetriever.CONF_PREFIX + "." + ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY,
            JOB_STATUS_STATE_STORE_DIR);

    serviceCoreProperties.put(ServiceConfigKeys.GOBBLIN_SERVICE_JOB_STATUS_MONITOR_ENABLED_KEY, false);

    // Create a bare repository
    RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(new File(GIT_REMOTE_REPO_DIR), FS.DETECTED);
    fileKey.open(false).create(true);

    this.gitForPush = Git.cloneRepository().setURI(GIT_REMOTE_REPO_DIR).setDirectory(new File(GIT_CLONE_DIR))
            .call();

    // push an empty commit as a base for detecting changes
    this.gitForPush.commit().setMessage("First commit").call();
    this.gitForPush.push().setRemote("origin").setRefSpecs(new RefSpec("master")).call();

    this.gobblinServiceManager = new GobblinServiceManager("CoreService", "1",
            ConfigUtils.propertiesToConfig(serviceCoreProperties), Optional.of(new Path(SERVICE_WORK_DIR)));
    this.gobblinServiceManager.start();

    this.flowConfigClient = new FlowConfigClient(
            String.format("http://localhost:%s/", this.gobblinServiceManager.restliServer.getPort()));
}