List of usage examples for org.eclipse.jgit.api Git commit
public CommitCommand commit()
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 ww w .j a v a 2s . c o 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.ks.blogging.grav.pages.GravPages.java
License:Apache License
public void addCommit(String msg) throws RuntimeException { Git git = getGit(); if (git != null) { try {/*from w ww . j av a 2 s . co m*/ Status status = git.status().call(); Set<String> modified = status.getModified(); Set<String> untracked = status.getUntracked(); AddCommand add = git.add(); modified.forEach(s -> add.addFilepattern(s)); untracked.forEach(s -> add.addFilepattern(s)); add.call(); CommitCommand commit = git.commit(); if (msg == null || msg.isEmpty()) { commit.setAmend(true); } else { commit.setMessage(msg); } RevCommit rev = commit.call(); log.info("Commited change {} with new rev {}", msg, rev); } catch (Exception e) { log.error("Could not add and commit ", e); throw new RuntimeException(e); } } }
From source file:de.ks.blogging.grav.ui.post.BlogIntegrationBasicFixture.java
License:Apache License
public void createBlogFolders(boolean withGit) throws Exception { dateTime = LocalDateTime.now().withSecond(0).withNano(0); String tmpDir = StandardSystemProperty.JAVA_IO_TMPDIR.value(); fileBlog1 = new File(tmpDir, "blog1"); fileBlog2 = new File(tmpDir, "blog2"); fileBlog1.mkdir();/*from w w w .j av a 2 s . com*/ fileBlog2.mkdir(); Git git = null; if (withGit) { git = Git.init().setDirectory(fileBlog2).call(); } Files.write(new File(fileBlog1, "blog1.md").toPath(), Arrays.asList(getBlog("post 1", "Hello Sauerland"))); Files.write(new File(fileBlog2, "blog2_a.md").toPath(), Arrays.asList(getBlog("post 1", "Hello Woll"))); if (git != null) { git.add().addFilepattern("blog2_a.md").call(); RevCommit commit = git.commit().setAll(true).setMessage("commit 1").call(); commit1 = commit.getId().getName(); } Files.write(new File(fileBlog2, "blog2_b.md").toPath(), Arrays.asList(getBlog("post 2", "Ein Bier bitte"))); if (git != null) { git.add().addFilepattern("blog2_b.md").call(); RevCommit commit = git.commit().setAll(true).setMessage("commit 2").call(); commit2 = commit.getId().getName(); } if (git != null) { Files.write(new File(fileBlog2, "blog2_c.md").toPath(), Arrays.asList(getBlog("post 3", "Ein Tischgedeck bitte"))); git.add().addFilepattern("blog2_c.md").call(); RevCommit commit = git.commit().setAll(true).setMessage("commit 3").call(); commit3 = commit.getId().getName(); Files.move(new File(fileBlog2, "blog2_c.md").toPath(), new File(fileBlog2, "blog2_d.md").toPath()); git.add().addFilepattern("blog2_c.md").addFilepattern("blog2_d.md").call(); commit = git.commit().setAll(true).setMessage("commit moved").call(); commitMoved = commit.getId().getName(); Files.delete(new File(fileBlog2, "blog2_d.md").toPath()); git.add().addFilepattern("blog2_d.md").call(); commit = git.commit().setAll(true).setMessage("commit deleted").call(); commitDeleted = commit.getId().getName(); } }
From source file:deployer.publishers.openshift.RhcApplicationGitRepoModificationsTest.java
License:Apache License
private void populateWithInitialFiles(Git git, File testDir) throws IOException, GitAPIException { log.debug("Git Repo Dir: " + git.getRepository().getDirectory().toString()); log.debug("Test dir: " + testDir.toString()); FileUtils.writeStringToFile(Files.resolve(testDir, "README"), "This is from the RhcApplication unit test."); File aDir = Files.resolve(testDir, "a-dir"); Files.createDirectories(aDir); FileUtils.writeStringToFile(Files.resolve(aDir, "source.json"), "{'hello': 'world'}"); FileUtils.writeStringToFile(Files.resolve(aDir, "AnotherFile.txt"), "A file about nothing"); FileUtils.writeStringToFile(Files.resolve(testDir, "deployed_version.txt"), "v0.33333333333333333"); log.info(git.add().addFilepattern(".").call().toString()); log.info(git.commit().setAuthor("Unit Test", "unit.test@email.com").setMessage("Initial files").setAll(true) .call().toString());/* ww w .j a va 2 s . co m*/ }
From source file:eu.mihosoft.vrl.io.VersionedFile.java
License:Open Source License
/** * Commit file changes. IF flushing for commits is enabled changes will be * flushed.//from w w w .j a va 2 s.com * * @param message commit message * @return this file * @throws IOException * @throws IllegalStateException if this file is currently not open */ public VersionedFile commit(String message) throws IOException { // file has to be opened if (!isOpened()) { throw new IllegalStateException("File\"" + getFile().getPath() + "\" not opened!"); } Git git = null; try { // this should NEVER happen if (hasConflicts()) { throw new IllegalStateException("File \"" + getFile().getPath() + "\" has conflicts!"); } // ensures that message is not null if (message == null || message.isEmpty()) { message = "no message"; } System.out.print(">> commit version "); // open the git repository git = Git.open(tmpFolder); // retrieve the current git status Status status = git.status().call(); // rm command to tell git to remove files RmCommand rm = git.rm(); boolean needsRM = false; // checks whether rm is necessary and adds relevant paths for (String removedFile : status.getMissing()) { rm.addFilepattern(removedFile); needsRM = true; } // calls the rm command if necessary if (needsRM) { rm.call(); } // adds all remaining files git.add().addFilepattern(".").call(); // perform the commit git.commit().setMessage(message).setAuthor(System.getProperty("user.name"), "?").call(); commits = null; // updates the current version number currentVersion = getNumberOfVersions() - 1; System.out.println(currentVersion + ": "); System.out.println(">>> commit-id (SHA-1): " + getVersions().get(currentVersion).getName()); if (isFlushCommits()) { flush(); } closeGit(git); return this; } catch (NoFilepatternException ex) { closeGit(git); throw new IOException("Git exception", ex); } catch (NoHeadException ex) { closeGit(git); throw new IOException("Git exception", ex); } catch (NoMessageException ex) { closeGit(git); throw new IOException("Git exception", ex); } catch (UnmergedPathException ex) { closeGit(git); throw new IOException("Git exception", ex); } catch (ConcurrentRefUpdateException ex) { closeGit(git); throw new IOException("Git exception", ex); } catch (JGitInternalException ex) { closeGit(git); throw new IOException("Git exception", ex); } catch (WrongRepositoryStateException ex) { closeGit(git); throw new IOException("Git exception", ex); } catch (IOException ex) { closeGit(git); throw new IOException("Git exception", ex); } }
From source file:eu.mihosoft.vrl.io.VersionedFile.java
License:Open Source License
/** * Initializes git repository./*from w w w. j a v a2s . co m*/ * * <p><b>Warning:</b> Be careful when calling this method. It will destroy * any existing repository!</p> * * @throws IOException */ private void initGit() throws IOException { File repoFile = new File(tmpFolder.getAbsolutePath() + "/.git"); // delete existing repository if (repoFile.exists()) { IOUtil.deleteDirectory(repoFile); } Git git = null; try { // initialize git repository Git.init().setDirectory(tmpFolder).call(); git = Git.open(tmpFolder); git.add().addFilepattern(".").call(); // perform initial commit git.commit().setMessage("initial commit").setAuthor("VRL-User", "").call(); git.getRepository().close(); } catch (NoHeadException ex) { throw new IOException("Git exception", ex); } catch (NoMessageException ex) { throw new IOException("Git exception", ex); } catch (UnmergedPathException ex) { throw new IOException("Git exception", ex); } catch (ConcurrentRefUpdateException ex) { throw new IOException("Git exception", ex); } catch (JGitInternalException ex) { throw new IOException("Git exception", ex); } catch (WrongRepositoryStateException ex) { throw new IOException("Git exception", ex); } catch (NoFilepatternException ex) { throw new IOException("Git exception", ex); } catch (IOException ex) { throw new IOException("Git exception", ex); } finally { if (git != null) { git.getRepository().close(); } } }
From source file:facade.GitFacade.java
public static void commitRepo(Repository repository, String message) throws GitAPIException { Git git = new Git(repository); git.add().addFilepattern(".").call(); git.commit().setAll(true).setMessage(message).call(); }
From source file:fi.otavanopisto.changelogger.Changelogger.java
private static void prependLine(String line, String message) throws IOException, GitAPIException { FileRepositoryBuilder frBuilder = new FileRepositoryBuilder(); Repository repository = frBuilder.setGitDir(new File("./.git")).readEnvironment().build(); Git git = new Git(repository); git.reset().setMode(ResetCommand.ResetType.HARD).call(); git.clean().call();/* w w w. j ava2 s. co m*/ git.fetch().call(); git.pull().call(); File file = new File(CHANGELOG_FILE); List<String> lines = FileUtils.readLines(file, Charsets.UTF_8); lines.add(0, line); FileUtils.writeLines(file, lines); git.commit().setMessage(message).setAuthor("Changelogger", "changelogger@otavanopisto.fi").call(); git.push().call(); }
From source file:fr.duminy.tools.jgit.JGitToolboxTest.java
License:Open Source License
private static String addAndCommitFile(Git git) throws IOException, GitAPIException { File gitDirectory = git.getRepository().getDirectory().getParentFile(); String filename = "file" + COUNTER++; IOUtils.write(filename + " content", new FileOutputStream(new File(gitDirectory, filename))); git.add().addFilepattern(filename).call(); RevCommit call = git.commit().setMessage("add " + filename).call(); String sha1 = call.getName(); LOGGER.info("{}: Added file {} (sha1: {})", gitDirectory.getName(), filename, sha1); return sha1;//from www . j a v a2s . c om }
From source file:fr.xebia.workshop.git.UpdatePomFileAndCommit.java
License:Apache License
@Override public void updateGitRepository(Git git, GitRepositoryInfo repositoryInfo) throws GitAPIException { File pomFile = getPomFile(git); updatePomGroupId(pomFile, repositoryInfo); git.add().addFilepattern(POM_XML).call(); try {/* w ww. j ava 2 s . com*/ git.commit().setCommitter("Team " + teamId, "").setMessage(COMMIT_MESSAGE).call(); } catch (UnmergedPathException e) { throw new IllegalStateException("Cannot commit git repository", e); } }