List of usage examples for org.eclipse.jgit.api Git pull
public PullCommand pull()
From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java
License:Open Source License
/** * Update a git repository and return if it has changed and the differences *//*from w w w .j a va 2s .co m*/ public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) { boolean changed = false; List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName); Repository localRepository = null; Git git = null; try { localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git")); Ref head = localRepository.getRef("HEAD"); git = new Git(localRepository); git.reset(); git.clean(); PullCommand pullCmd = git.pull(); if (useCredentials) { pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword)); } pullCmd.call(); Ref newHEAD = localRepository.getRef("HEAD"); if (!head.toString().equals(newHEAD.toString())) { changed = true; // Get the differences between the the heads which we updated at // and use these to just update the differences between them ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}"); ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}"); ObjectReader reader = localRepository.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, oldHead); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, newHead); List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call(); for (DiffEntry entry : entries) { if ("DELETE".equals(entry.getChangeType().name())) { deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath())); } else { changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath())); } } } } catch (IOException | GitAPIException | InvalidPathException ex) { changed = false; Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage()); } finally { Singleton.getHelpers().closeQuietly(localRepository); Singleton.getHelpers().closeQuietly(git); } return new RepositoryChanged(changed, changedFiles, deletedFiles); }
From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java
License:Apache License
private void changeAndRenameFile() throws IOException, GitAPIException { final Git git = Git.open(gitCloneDirectory); git.pull().setRemote("origin").setRemoteBranchName("master").call(); try (FileWriter writer = new FileWriter(file2, true)) { writer.append("\nchanged"); }//w ww . j a v a2 s . c o m if (!file2.renameTo(file2.toPath().resolveSibling("file3.adoc").toFile())) throw new IOException("Could not rename file2 to file3"); git.add().setUpdate(true).addFilepattern(".").call(); git.add().addFilepattern(".").call(); git.commit().setMessage("changed file2 and renamed to file3").call(); git.push().setRemote("origin").add("master").call(); git.close(); }
From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java
License:Apache License
private void createNextCommit() throws IOException, GitAPIException { final Git git = Git.open(gitCloneDirectory); git.pull().setRemote("origin").setRemoteBranchName("master").call(); try (FileWriter writer = new FileWriter(file1, true)) { writer.write("hi world!\nhello hi"); }/*ww w. j av a 2 s . co m*/ git.add().addFilepattern(".").call(); git.commit().setMessage("updated file1").call(); try (FileWriter writer = new FileWriter(file2, true)) { writer.write("world"); } git.add().addFilepattern(".").call(); git.commit().setMessage("updated file2").call(); git.push().setRemote("origin").add("master").call(); git.close(); }
From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java
License:Apache License
private void renameFile() throws IOException, GitAPIException { final Git git = Git.open(gitCloneDirectory); git.pull().setRemote("origin").setRemoteBranchName("master").call(); if (!file2.renameTo(file2.toPath().resolveSibling("file3.adoc").toFile())) throw new IOException("Could not rename file2 to file3"); git.add().setUpdate(true).addFilepattern(".").call(); git.add().addFilepattern(".").call(); git.commit().setMessage("renamed file2 to file3").call(); git.push().setRemote("origin").add("master").call(); git.close();/*from w w w.ja va 2 s .c o m*/ }
From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java
License:Apache License
private void deleteFile() throws IOException, GitAPIException { final Git git = Git.open(gitCloneDirectory); git.pull().setRemote("origin").setRemoteBranchName("master").call(); if (!file2.delete()) throw new IOException("Could not delete file2"); git.add().setUpdate(true).addFilepattern(".").call(); git.commit().setMessage("deleted file2").call(); git.push().setRemote("origin").add("master").call(); git.close();//from ww w .j a v a2 s .c o m }
From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java
License:Apache License
private void addNotRelevantFile(final String fileName) throws GitAPIException, IOException { final Git git = Git.open(gitCloneDirectory); git.pull().setRemote("origin").setRemoteBranchName("master").call(); try (FileWriter writer = new FileWriter(file1.toPath().resolveSibling(fileName + ".mustache").toFile(), true)) {/* www. ja v a 2 s . c o m*/ writer.write("hello {{world}}"); } git.add().addFilepattern(".").call(); git.commit().setMessage("added template").call(); git.push().setRemote("origin").add("master").call(); git.close(); }
From source file:com.sillelien.dollar.plugins.pipe.GithubModuleResolver.java
License:Apache License
@NotNull @Override/*from ww w . j av a2s.c om*/ public <T> Pipeable resolve(@NotNull String uriWithoutScheme, @NotNull T scope) throws Exception { logger.debug(uriWithoutScheme); String[] githubRepo = uriWithoutScheme.split(":"); GitHub github = GitHub.connect(); final String githubUser = githubRepo[0]; GHRepository repository = github.getUser(githubUser).getRepository(githubRepo[1]); final String branch = githubRepo[2].length() > 0 ? githubRepo[2] : "master"; FileRepositoryBuilder builder = new FileRepositoryBuilder(); final File dir = new File(BASE_PATH + "/" + githubUser + "/" + githubRepo[1] + "/" + branch); dir.mkdirs(); final File gitDir = new File(dir, ".git"); if (gitDir.exists()) { Repository localRepo = builder.setGitDir(gitDir).readEnvironment().findGitDir().build(); Git git = new Git(localRepo); PullCommand pull = git.pull(); pull.call(); } else { Repository localRepo = builder.setGitDir(dir).readEnvironment().findGitDir().build(); Git git = new Git(localRepo); CloneCommand clone = Git.cloneRepository(); clone.setBranch(branch); clone.setBare(false); clone.setCloneAllBranches(false); clone.setDirectory(dir).setURI(repository.getGitTransportUrl()); // UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(login, password); // clone.setCredentialsProvider(user); clone.call(); } final ClassLoader classLoader; String content; File mainFile; if (githubRepo.length == 4) { classLoader = getClass().getClassLoader(); mainFile = new File(dir, githubRepo[3]); content = new String(Files.readAllBytes(mainFile.toPath())); } else { final File moduleFile = new File(dir, "module.json"); var module = DollarStatic.$(new String(Files.readAllBytes(moduleFile.toPath()))); mainFile = new File(dir, module.$("main").$S()); content = new String(Files.readAllBytes(mainFile.toPath())); classLoader = DependencyRetriever.retrieve( module.$("dependencies").$list().stream().map(var::toString).collect(Collectors.toList())); } return (params) -> ((Scope) scope).getDollarParser().inScope(false, "github-module", ((Scope) scope), newScope -> { final ImmutableMap<var, var> paramMap = params[0].$map(); for (Map.Entry<var, var> entry : paramMap.entrySet()) { newScope.set(entry.getKey().$S(), entry.getValue(), true, null, null, false, false, false); } return new DollarParserImpl(((Scope) scope).getDollarParser().options(), classLoader, dir) .parse(newScope, content); }); }
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 {/*www . jav a 2s . com*/ 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 . j a v a 2s . 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:edu.tum.cs.mylyn.provisioning.git.ui.GitProvisioningWizard.java
License:Open Source License
private void pull(Repository repository) throws IOException { Git git = new Git(repository); PullCommand pull = git.pull(); pull.setCredentialsProvider(new EGitCredentialsProvider()); try {/* w w w . ja v a2s . co m*/ pull.call(); } catch (TransportException e) { throw new IOException(e); } catch (GitAPIException e) { throw new IOException(e); } SubmoduleUpdateCommand update = git.submoduleUpdate(); try { update.call(); } catch (Exception e) { throw new IOException(e); } }