List of usage examples for org.eclipse.jgit.api Git cloneRepository
public static CloneCommand cloneRepository()
From source file:de.br0tbox.gitfx.ui.controllers.ProjectsController.java
License:Apache License
@FXML public void cloneButtonClicked() { // showMessage("00001"); final File gitDir = openDirectoryChooserAtLastOpened(); if (gitDir != null) { gitDir.delete();//from ww w . j a v a 2 s.c o m gitDir.mkdirs(); final CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setDirectory(gitDir).setURI("https://github.com/VanillaDev/Vanilla.git"); final GitCloneTask fxTask = GitTaskFactory.cloneTask(cloneCommand); runGitTaskWithProgressDialog(fxTask); addProject(new File(gitDir, ".git"), gitDir.getName(), false); } }
From source file:de.egore911.versioning.deployer.performer.PerformCheckout.java
License:Open Source License
private static void performGit(String target, String url) { String tmp = target + File.separatorChar + "checkout"; try {//from w w w . ja va2 s. c om File tmpDir = new File(tmp); try { if (!new File(tmp + "/.git").exists()) { Git.cloneRepository().setURI(url).setDirectory(tmpDir).call(); } else { FileRepository fileRepository = new FileRepository(tmp + "/.git"); Git git = new Git(fileRepository); git.pull().setRebase(true).call(); } FileUtils.copyDirectory(tmpDir, new File(target)); } finally { FileUtils.deleteDirectory(tmpDir); } } catch (GitAPIException | IOException e) { LOG.error(e.getMessage(), e); } }
From source file:de.fraunhofer.ipa.CobPipelineProperty.java
License:Open Source License
@JavaScriptMethod public JSONObject doGeneratePipeline() throws Exception { JSONObject response = new JSONObject(); String message = ""; // wait until config.xml is updated File configFile = new File(Jenkins.getInstance().getRootDir(), "users/" + user.getId() + "/config.xml"); Date mod = new Date(); Long start = mod.getTime();//from w w w .ja va2 s .co m Date now; do { try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (configFile.exists()) { try { mod = new Date(configFile.lastModified()); } catch (Exception ex) { } } now = new Date(); if (now.getTime() - start > 30000) { throw new Exception("Timeout"); } } while (start.equals(mod.getTime()) || now.getTime() - mod.getTime() > 15000); try { Map<String, Object> data = new HashMap<String, Object>(); data.put("user_name", user.getId()); data.put("server_name", getMasterName()); data.put("email", this.email); data.put("committer_email_enabled", this.committerEmailEnabled); Map<String, Object> repos = new HashMap<String, Object>(); for (RootRepository rootRepo : this.rootRepos) { Map<String, Object> repo = new HashMap<String, Object>(); repo.put("type", rootRepo.type); repo.put("url", rootRepo.url); repo.put("version", rootRepo.branch); repo.put("poll", rootRepo.poll); repo.put("ros_distro", rootRepo.getRosDistro()); repo.put("prio_ubuntu_distro", rootRepo.getPrioUbuntuDistro()); repo.put("prio_arch", rootRepo.getPrioArch()); repo.put("regular_matrix", rootRepo.getMatrixDistroArch()); repo.put("jobs", rootRepo.getJobs()); repo.put("robots", rootRepo.robot); Map<String, Object> deps = new HashMap<String, Object>(); for (Repository repoDep : rootRepo.getRepoDeps()) { Map<String, Object> dep = new HashMap<String, Object>(); if (repoDep.fork.equals("") || repoDep.fork.equals(null)) { response.put("message", Messages.Pipeline_GenerationNoFork(rootRepo.fullName)); response.put("status", "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>"); return response; } if (repoDep.name.equals("") || repoDep.name.equals(null)) { response.put("message", Messages.Pipeline_GenerationNoDepName(rootRepo.fullName)); response.put("status", "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>"); return response; } if (repoDep.branch.equals("") || repoDep.branch.equals(null)) { response.put("message", Messages.Pipeline_GenerationNoBranch(rootRepo.fullName)); response.put("status", "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>"); return response; } dep.put("type", repoDep.type); dep.put("url", repoDep.url); dep.put("version", repoDep.branch); dep.put("poll", repoDep.poll); dep.put("test", repoDep.test); deps.put(repoDep.name, dep); } repo.put("dependencies", deps); repos.put(rootRepo.fullName, repo); } data.put("repositories", repos); Yaml yaml = new Yaml(); yaml.dump(data, getPipelineConfigFile()); LOGGER.log(Level.INFO, "Created " + getPipelineConfigFilePath().getAbsolutePath()); //TODO } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to save " + getPipelineConfigFilePath().getAbsolutePath(), e); //TODO } // clone/pull configuration repository File configRepoFolder = new File(Jenkins.getInstance() .getDescriptorByType(CobPipelineProperty.DescriptorImpl.class).getConfigFolder(), "jenkins_config"); String configRepoURL = "git@github.com:" + Jenkins.getInstance() .getDescriptorByType(CobPipelineProperty.DescriptorImpl.class).getPipelineReposOwner() + "/jenkins_config.git"; Git git = new Git(new FileRepository(configRepoFolder + "/.git")); // check if configuration repository exists if (!configRepoFolder.isDirectory()) { try { Git.cloneRepository().setURI(configRepoURL).setDirectory(configRepoFolder).call(); LOGGER.log(Level.INFO, "Successfully cloned configuration repository from " + configRepoURL); //TODO } catch (Exception ex) { LOGGER.log(Level.WARNING, "Failed to clone configuration repository", ex); //TODO } } else { try { git.pull().call(); LOGGER.log(Level.INFO, "Successfully pulled configuration repository from " + configRepoURL); //TODO } catch (Exception ex) { LOGGER.log(Level.WARNING, "Failed to pull configuration repository", ex); //TODO } } // copy pipeline-config.yaml into repository File configRepoFile = new File(configRepoFolder, getMasterName() + "/" + user.getId() + "/"); if (!configRepoFile.isDirectory()) configRepoFile.mkdirs(); String[] cpCommand = { "cp", "-f", getPipelineConfigFilePath().getAbsolutePath(), configRepoFile.getAbsolutePath() }; Runtime rt = Runtime.getRuntime(); Process proc; BufferedReader readIn, readErr; String s, feedback; proc = rt.exec(cpCommand); readIn = new BufferedReader(new InputStreamReader(proc.getInputStream())); readErr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); feedback = ""; while ((s = readErr.readLine()) != null) feedback += s + "\n"; if (feedback.length() != 0) { LOGGER.log(Level.WARNING, "Failed to copy " + getPipelineConfigFilePath().getAbsolutePath() + " to config repository: " + configRepoFile.getAbsolutePath()); //TODO LOGGER.log(Level.WARNING, feedback); //TODO } else { LOGGER.log(Level.INFO, "Successfully copied " + getPipelineConfigFilePath().getAbsolutePath() + " to config repository: " + configRepoFile.getAbsolutePath()); //TODO } // add try { git.add().addFilepattern(getMasterName() + "/" + user.getId() + "/pipeline_config.yaml").call(); LOGGER.log(Level.INFO, "Successfully added file to configuration repository"); //TODO } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to add " + getMasterName() + "/" + user.getId() + "/pipeline_config.yaml", e); //TODO } // commit try { git.commit().setMessage("Updated pipeline configuration for " + user.getId()).call(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to commit change in " + getMasterName() + "/" + user.getId() + "/pipeline_config.yaml", e); //TODO } // push try { git.push().call(); LOGGER.log(Level.INFO, "Successfully pushed configuration repository"); //TODO } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to push configuration repository", e); //TODO } // trigger Python job generation script String[] generationCall = { new File(Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class) .getConfigFolder(), "jenkins_setup/scripts/generate_buildpipeline.py").toString(), "-m", Jenkins.getInstance().getRootUrl(), "-l", Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class) .getJenkinsLogin(), "-p", Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class) .getJenkinsPassword(), "-c", Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class) .getConfigFolder(), "-o", Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class) .getPipelineReposOwner(), "-t", Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class) .getTarballLocation(), "-u", user.getId() }; proc = rt.exec(generationCall); readIn = new BufferedReader(new InputStreamReader(proc.getInputStream())); readErr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); feedback = ""; while ((s = readErr.readLine()) != null) feedback += s + "\n"; if (feedback.length() != 0) { LOGGER.log(Level.WARNING, "Failed to generate pipeline: "); //TODO LOGGER.log(Level.WARNING, feedback); response.put("message", feedback.replace("\n", "<br/>")); response.put("status", "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>"); return response; } else { feedback = ""; while ((s = readIn.readLine()) != null) feedback += s + "\n"; if (feedback.length() != 0) { LOGGER.log(Level.INFO, feedback); LOGGER.log(Level.INFO, "Successfully generated pipeline"); //TODO message += feedback; } } response.put("message", message.replace("\n", "<br/>")); response.put("status", "<font color=\"green\">" + Messages.Pipeline_GenerationSuccess() + "</font>"); return response; }
From source file:de._692b8c32.cdlauncher.tasks.GITUpdateTask.java
License:Open Source License
@Override public void doWork() { try {// w w w . j av a 2 s. c om Git git; if (!cacheDir.exists()) { cacheDir.mkdirs(); git = Git.cloneRepository().setURI(repoUri).setDirectory(cacheDir).setNoCheckout(true) .setProgressMonitor(this).call(); } else { git = Git.open(cacheDir); git.fetch().setProgressMonitor(this).call(); } git.close(); } catch (RepositoryNotFoundException | InvalidRemoteException ex) { Logger.getLogger(GITUpdateTask.class.getName()).log(Level.SEVERE, "Could not find repository", ex); try { FileUtils.delete(cacheDir); run(); } catch (IOException | StackOverflowError ex1) { throw new RuntimeException("Fix of broken repository failed", ex1); } } catch (GitAPIException | IOException ex) { throw new RuntimeException("Could not download data", ex); } }
From source file:deployer.publishers.openshift.OpenShiftThriftRunnerTest.java
License:Apache License
private void testSingleInstance(int existing) throws DeploymentException, GitAPIException, IOException { String strExisting = Integer.toString(existing); File remoteTestDir = Files.resolve(GIT_TEST_DIR, strExisting, "thriftRunnerviaOpenshift.git"); File testDir = Files.resolve(GIT_TEST_DIR, strExisting, "thriftRunnerviaOpenshift"); System.out.println(testDir);/*from w w w . jav a 2 s. com*/ Files.createDirectories(testDir); AppDirs[] theGits = makeNumberGits(existing, existing + "/thriftRunnerviaOpenshift"); Git.init().setBare(true).setDirectory(remoteTestDir).call(); Git git = Git.cloneRepository().setURI(remoteTestDir.toURI().toString()).setDirectory(testDir).call(); Rhc rhc = createMock(Rhc.class); IApplication instance = createMock(IApplication.class); IDomain domain = createMock(IDomain.class); IUser mockUser = createMock(IUser.class); EzReverseProxyRegister ezReverseProxyRegister = createMock(EzReverseProxyRegister.class); expect(instance.getName()).andReturn("UnitTestApplication").anyTimes(); expect(domain.getUser()).andReturn(mockUser).anyTimes(); expect(mockUser.getRhlogin()).andReturn("UnitTestuser").anyTimes(); if (existing == 0 || existing == 1) { expect(rhc.listApplicationInstances(TestUtils.getOpenShiftAppName(), TestUtils.getOpenShiftDomainName())).andReturn(Collections.EMPTY_LIST).once(); } else { expect(rhc.listApplicationInstances(TestUtils.getOpenShiftAppName(), TestUtils.getOpenShiftDomainName())).andReturn(getExistingInstances(theGits, instance, domain)) .once(); instance.stop(); expectLastCall().times(existing - 1); instance.destroy(); expectLastCall().times(existing - 1); } expect(rhc.getOrCreateApplication(TestUtils.buildOpenShiftAppName(0), TestUtils.getOpenShiftDomainName(), new StandaloneCartridge("java-thriftrunner"), ApplicationScale.NO_SCALE, GearProfile.SMALL)) .andReturn(new RhcApplication(git, instance, domain, testDir, null)).once(); expect(instance.getEnvironmentVariables()).andReturn(new HashMap<String, IEnvironmentVariable>()) .anyTimes(); expect(instance.addEnvironmentVariable("EZBAKE_APPLICATION_NAME", TestUtils.APP_NAME)) .andReturn(envVariableValue("EZBAKE_APPLICATION_NAME", TestUtils.APP_NAME)).anyTimes(); expect(instance.addEnvironmentVariable("EZBAKE_SERVICE_NAME", TestUtils.SERVICE_NAME)) .andReturn(envVariableValue("EZBAKE_SERVICE_NAME", TestUtils.SERVICE_NAME)).anyTimes(); expect(instance.getEmbeddedCartridges()).andReturn(new ArrayList<IEmbeddedCartridge>()).anyTimes(); IEmbeddedCartridge cart = createMock(IEmbeddedCartridge.class); expect(instance.addEmbeddableCartridge(new EmbeddableCartridge("logstash"))).andReturn(cart).anyTimes(); expect(instance.addEmbeddableCartridge(new EmbeddableCartridge("cron"))).andReturn(cart).anyTimes(); replay(instance, domain, mockUser, ezReverseProxyRegister, rhc); EzOpenShiftPublisher publisher = new EzOpenShiftPublisherMock(rhc, ezReverseProxyRegister); DeploymentArtifact deploymentArtifact = createSampleDeploymentArtifact(ArtifactType.Thrift); publisher.publish(deploymentArtifact, ThriftTestUtils.generateTestSecurityToken("U")); verify(instance, domain, mockUser, ezReverseProxyRegister, rhc); assertGitRepositoryFilesForUpdateGitRepoTest(testDir); }
From source file:deployer.publishers.openshift.OpenShiftWebAppTest.java
License:Apache License
private File runSingleInstanceTest(int existing, DeploymentArtifact deploymentArtifact) throws Exception { String strExisting = Integer.toString(existing); File remoteTestDir = Files.resolve(TestUtils.GIT_TEST_DIR, strExisting, "webappviaOpenshift.git"); File testDir = Files.resolve(TestUtils.GIT_TEST_DIR, strExisting, "webappviaOpenshift"); System.out.println(testDir);/*from w w w . j a v a 2 s. co m*/ Files.createDirectories(testDir); ArtifactHelpers.addFilesToArtifact(deploymentArtifact, new JavaWebAppArtifactContentsPublisher().generateEntries(deploymentArtifact)); TestUtils.AppDirs[] theGits = TestUtils.makeNumberGits(existing, existing + "/webappviaOpenshift"); Git.init().setBare(true).setDirectory(remoteTestDir).call(); Git git = Git.cloneRepository().setURI(remoteTestDir.toURI().toString()).setDirectory(testDir).call(); Rhc rhc = createMock(Rhc.class); IApplication instance = createMock(IApplication.class); IDomain domain = createMock(IDomain.class); IUser mockUser = createMock(IUser.class); EzReverseProxy.Client ezReverseProxyClient = createMock(EzReverseProxy.Client.class); ThriftClientPool clientPool = createMockPool((existing >= 2 ? existing : 1), "EzBakeFrontend", EzReverseProxyConstants.SERVICE_NAME, ezReverseProxyClient); EzReverseProxyRegister ezReverseProxyRegister = new EzReverseProxyRegister( new EzDeployerConfiguration(new Properties()), clientPool); expect(instance.getName()).andReturn("UnitTestApplication").anyTimes(); expect(instance.getApplicationUrl()).andReturn("http://unit-test.local/").anyTimes(); expect(domain.getUser()).andReturn(mockUser).anyTimes(); expect(mockUser.getRhlogin()).andReturn("UnitTestuser").anyTimes(); if (existing == 0 || existing == 1) { expect(rhc.listApplicationInstances(TestUtils.getOpenShiftAppName(), TestUtils.getOpenShiftDomainName())).andReturn(Collections.EMPTY_LIST).once(); } else { expect(rhc.listApplicationInstances(TestUtils.getOpenShiftAppName(), TestUtils.getOpenShiftDomainName())) .andReturn(TestUtils.getExistingInstances(theGits, instance, domain)).once(); instance.stop(); expectLastCall().times(existing - 1); instance.destroy(); expectLastCall().times(existing - 1); ezReverseProxyClient.removeUpstreamServerRegistration( eqRegistration("example.local/" + TestUtils.SERVICE_NAME + "/", TestUtils.SERVICE_NAME, "unit-test.local:443", "")); expectLastCall().times(existing - 1); } ezReverseProxyClient .addUpstreamServerRegistration(eqRegistration("example.local/" + TestUtils.SERVICE_NAME + "/", TestUtils.SERVICE_NAME, "unit-test.local:443", "")); expect(rhc.getOrCreateApplication(TestUtils.buildOpenShiftAppName(0), TestUtils.getOpenShiftDomainName(), new StandaloneCartridge("jbossas"), ApplicationScale.NO_SCALE, GearProfile.SMALL)) .andReturn(new RhcApplication(git, instance, domain, testDir, null)).once(); expect(instance.getEnvironmentVariable("OPENSHIFT_GEAR_DNS")) .andReturn(envVariableValue("OPENSHIFT_GEAR_DNS", "unit-test.local")).anyTimes(); expect(instance.getEnvironmentVariable("OPENSHIFT_JAVA_THRIFTRUNNER_TCP_PROXY_PORT")) .andReturn(envVariableValue("OPENSHIFT_JAVA_THRIFTRUNNER_TCP_PROXY_PORT", "32456")).anyTimes(); expect(instance.getEnvironmentVariables()).andReturn(new HashMap<String, IEnvironmentVariable>()) .anyTimes(); expect(instance.addEnvironmentVariable("EZBAKE_APPLICATION_NAME", TestUtils.APP_NAME)) .andReturn(envVariableValue("EZBAKE_APPLICATION_NAME", TestUtils.APP_NAME)).anyTimes(); expect(instance.addEnvironmentVariable("EZBAKE_SERVICE_NAME", TestUtils.SERVICE_NAME)) .andReturn(envVariableValue("EZBAKE_SERVICE_NAME", TestUtils.SERVICE_NAME)).anyTimes(); expect(instance.getEmbeddedCartridges()).andReturn(new ArrayList<IEmbeddedCartridge>()).anyTimes(); IEmbeddedCartridge cart = createMock(IEmbeddedCartridge.class); expect(instance.addEmbeddableCartridge(new EmbeddableCartridge("logstash"))).andReturn(cart).anyTimes(); expect(instance.addEmbeddableCartridge(new EmbeddableCartridge("cron"))).andReturn(cart).anyTimes(); replay(instance, domain, mockUser, ezReverseProxyClient, rhc); EzOpenShiftPublisher publisher = new EzOpenShiftPublisherMock(rhc, ezReverseProxyRegister); publisher.publish(deploymentArtifact, ThriftTestUtils.generateTestSecurityToken("U")); verify(instance, domain, mockUser, ezReverseProxyClient, rhc, clientPool); return testDir; }
From source file:deployer.publishers.openshift.RhcApplicationGitRepoModificationsTest.java
License:Apache License
@Test public void shouldUpdateGitRepoWithModifications() throws IOException, GitAPIException, ArchiveException, DeploymentException { File remoteTestDir = Files.resolve(GIT_TEST_DIR, "shouldUpdateGitRepoWithModificationsOrigin.git"); File testDir = Files.resolve(GIT_TEST_DIR, "shouldUpdateGitRepoWithModifications"); Files.createDirectories(testDir); Git remoteGit = Git.init().setBare(true).setDirectory(remoteTestDir).call(); Git git = Git.cloneRepository().setURI(remoteTestDir.toString()).setDirectory(testDir).call(); populateWithInitialFiles(git, testDir); IApplication instance = createMock(IApplication.class); IDomain domain = createMock(IDomain.class); IUser mockUser = createMock(IUser.class); expect(instance.getName()).andReturn("UnitTestApplication").anyTimes(); expect(domain.getUser()).andReturn(mockUser).anyTimes(); expect(mockUser.getRhlogin()).andReturn("UnitTestuser").anyTimes(); replay(instance, domain, mockUser);// w ww.j a va 2 s. com RhcApplication app = new RhcApplication(git, instance, domain, testDir, null); ByteBuffer sampleTarBall = TestUtils.createSampleAppTarBall(ArtifactType.Thrift); app.updateWithTarBall(sampleTarBall.array(), "v1.0"); app.addStreamAsFile(Files.get(TestUtils.CONFIG_DIRECTORY, "extraInfo.conf"), new ByteArrayInputStream("Extra information".getBytes())); app.publishChanges(); verify(instance, domain, mockUser); assertGitRepositoryFilesForUpdateGitRepoTest(testDir); File ensuredDir = Files.resolve(GIT_TEST_DIR, "shouldUpdateGitRepoWithModificationsEnsured"); Git.cloneRepository().setURI(remoteTestDir.toURI().toString()).setDirectory(ensuredDir).call(); assertGitRepositoryFilesForUpdateGitRepoTest(ensuredDir); }
From source file:deployer.TestUtils.java
License:Apache License
public static AppDirs[] makeNumberGits(int number, String baseName) throws GitAPIException { List<AppDirs> gits = Lists.newArrayListWithCapacity(number); for (int i = 0; i < number; i++) { File remoteTestDir = Files.resolve(GIT_TEST_DIR, baseName + "xx" + i + ".git"); File testDir = Files.resolve(GIT_TEST_DIR, baseName + "xx" + i); Files.createDirectories(testDir); Git remoteGit = Git.init().setBare(true).setDirectory(remoteTestDir).call(); Git git = Git.cloneRepository().setURI(remoteTestDir.toURI().toString()).setDirectory(testDir).call(); gits.add(new AppDirs(remoteGit, git, testDir)); }/*from w w w . j a v a2s. c om*/ return gits.toArray(new AppDirs[gits.size()]); }
From source file:digital.torpedo.yaci.autobuilder.fileprocessers.Gitter.java
License:Open Source License
@Override public Path processFile(String p, Path baseFolder, String stamp, YACITaskConf config) { Path folder = baseFolder.resolve(getGitName(p) + "_" + stamp); try {/*from w w w . j av a 2 s. com*/ Files.createDirectories(folder); } catch (IOException e) { e.printStackTrace(); } CloneCommand c = Git.cloneRepository().setURI(p).setDirectory(folder.toFile()); config.gitBranch.ifPresent(c::setBranch); try (Git repo = c.call()) { repo.close(); repo.getRepository().close(); return folder; } catch (GitAPIException e) { e.printStackTrace(); } return null; }
From source file:edu.nju.cs.inform.jgit.porcelain.CloneRemoteRepository.java
License:Apache License
public static void main(String[] args) throws IOException, InvalidRemoteException, TransportException, GitAPIException { // prepare a new folder for the cloned repository File localPath = File.createTempFile("TestGitRepository", ""); localPath.delete();//from w w w . ja v a 2s. c om // then clone System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); try (Git result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call()) { // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! System.out.println("Having repository: " + result.getRepository().getDirectory()); } }