List of usage examples for org.eclipse.jgit.api Git Git
public Git(Repository repo)
From source file:com.github.checkstyle.regression.internal.CommitValidationTest.java
License:Open Source License
private static RevCommitsPair resolveRevCommitsPair(Repository repo) { RevCommitsPair revCommitIteratorPair; try (RevWalk revWalk = new RevWalk(repo)) { final Iterator<RevCommit> first; final Iterator<RevCommit> second; final ObjectId headId = repo.resolve(Constants.HEAD); final RevCommit headCommit = revWalk.parseCommit(headId); if (isMergeCommit(headCommit)) { final RevCommit firstParent = headCommit.getParent(0); final RevCommit secondParent = headCommit.getParent(1); try (Git git = new Git(repo)) { first = git.log().add(firstParent).call().iterator(); second = git.log().add(secondParent).call().iterator(); }/*from www . j a v a 2 s.com*/ } else { try (Git git = new Git(repo)) { first = git.log().call().iterator(); } second = Collections.emptyIterator(); } revCommitIteratorPair = new RevCommitsPair(new OmitMergeCommitsIterator(first), new OmitMergeCommitsIterator(second)); } catch (GitAPIException | IOException ex) { revCommitIteratorPair = new RevCommitsPair(); } return revCommitIteratorPair; }
From source file:com.github.checkstyle.regression.internal.GitUtils.java
License:Open Source License
public static void createNewBranchAndCheckout(Repository repository, String branchName) throws GitAPIException { try (Git git = new Git(repository)) { if (git.branchList().call().stream() .anyMatch(ref -> ref.getName().equals(Constants.R_HEADS + branchName))) { git.branchDelete().setBranchNames(branchName).setForce(true).call(); }//from w ww . j a va 2 s .c o m git.branchCreate().setName(branchName).call(); git.checkout().setName(branchName).call(); } }
From source file:com.github.checkstyle.regression.internal.GitUtils.java
License:Open Source License
public static void checkoutBranch(Repository repository, String branchName) throws GitAPIException { try (Git git = new Git(repository)) { git.checkout().setName(branchName).call(); }//w w w. jav a 2 s . c om }
From source file:com.github.checkstyle.regression.internal.GitUtils.java
License:Open Source License
public static File addAnEmptyFileAndCommit(Repository repository, String fileName) throws IOException, GitAPIException { try (Git git = new Git(repository)) { final File file = new File(repository.getDirectory().getParent(), fileName); if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { throw new IOException("Could not create directory " + file.getParentFile()); }/* w w w . ja va2 s .c o m*/ if (!file.createNewFile()) { throw new IOException("Could not create file " + file); } git.add().addFilepattern(fileName).call(); git.commit().setMessage("add " + fileName).call(); return file; } }
From source file:com.github.checkstyle.regression.internal.GitUtils.java
License:Open Source License
public static void addAllAndCommit(Repository repository, String message) throws GitAPIException { try (Git git = new Git(repository)) { // In JGit, the "add ." could not add the deleted files into staging area. // To obtain the same behavior as git CLI command "git add .", we have to // use RmCommand to handle deleted files. final Status status = git.status().call(); if (!status.getMissing().isEmpty() || !status.getRemoved().isEmpty()) { final RmCommand rm = git.rm().setCached(true); Iterables.concat(status.getMissing(), status.getRemoved()).forEach(rm::addFilepattern); rm.call();//w ww. j a v a2 s . c om } git.add().addFilepattern(".").call(); git.commit().setMessage(message).call(); } }
From source file:com.github.checkstyle.regression.internal.GitUtils.java
License:Open Source License
public static void removeFileAndCommit(Repository repository, String fileName) throws GitAPIException { try (Git git = new Git(repository)) { git.rm().addFilepattern(fileName).call(); git.commit().setMessage("rm " + fileName).call(); }/*from ww w . j a v a2 s. co m*/ }
From source file:com.github.kaitoy.goslings.server.dao.jgit.RepositoryResolver.java
License:Open Source License
/** * Get the {@link Git} instance which corresponds to the repository specified by the given token. * * @param token token/*from w w w . j a v a2 s. c o m*/ * @return a {@link Git} instance. Never null. * @throws DaoException if any errors. */ Git getGit(String token) { if (GITS.containsKey(token)) { return GITS.get(token); } File gitDir = Paths.get(REPOS_DIR, token).toFile(); Git git = null; try { Repository repo = new FileRepositoryBuilder().setGitDir(gitDir).readEnvironment().findGitDir().build(); git = new Git(repo); WeakReferenceMonitor.monitor(git, () -> repo.close()); GITS.put(token, git); return git; } catch (IOException e) { LOG.error("Failed to build a repo {}", gitDir, e); throw new DaoException("The server couldn't find a repository by the token: " + token, e); } }
From source file:com.github.rwhogg.git_vcr.App.java
License:Open Source License
/** * main is the entry point for Git-VCR//w ww . j av a 2s . c o m * @param args Command-line arguments */ public static void main(String[] args) { Options options = parseCommandLine(args); HierarchicalINIConfiguration configuration = null; try { configuration = getConfiguration(); } catch (ConfigurationException e) { Util.error("could not parse configuration file!"); } // verify we are in a git folder and then construct the repo final File currentFolder = new File("."); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository localRepo = null; try { localRepo = builder.findGitDir().build(); } catch (IOException e) { Util.error("not in a Git folder!"); } // deal with submodules assert localRepo != null; if (localRepo.isBare()) { FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder(); Repository parentRepo; try { parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build(); localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName()); } catch (IOException e) { Util.error("could not find parent of submodule!"); } } // if we need to retrieve the patch file, get it now URL patchUrl = options.getPatchUrl(); String patchPath = patchUrl.getFile(); File patchFile = null; HttpUrl httpUrl = HttpUrl.get(patchUrl); if (httpUrl != null) { try { patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff"); Request request = new Request.Builder().url(httpUrl).build(); OkHttpClient client = new OkHttpClient(); Call call = client.newCall(request); Response response = call.execute(); ResponseBody body = response.body(); if (!response.isSuccessful()) { Util.error("could not retrieve diff file from URL " + patchUrl); } String content = body.string(); org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null); } catch (IOException ie) { Util.error("could not retrieve diff file from URL " + patchUrl); } } else { patchFile = new File(patchPath); } // find the patch //noinspection ConstantConditions if (!patchFile.canRead()) { Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!"); } final Git git = new Git(localRepo); // handle the branch String branchName = options.getBranchName(); String theOldCommit = null; try { theOldCommit = localRepo.getBranch(); } catch (IOException e2) { Util.error("could not get reference to current branch!"); } final String oldCommit = theOldCommit; // needed to reference from shutdown hook if (branchName != null) { // switch to the branch try { git.checkout().setName(branchName).call(); } catch (RefAlreadyExistsException e) { // FIXME Auto-generated catch block e.printStackTrace(); } catch (RefNotFoundException e) { Util.error("the branch " + branchName + " was not found!"); } catch (InvalidRefNameException e) { Util.error("the branch name " + branchName + " is invalid!"); } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) { Util.error("there was a checkout conflict!"); } catch (GitAPIException e) { Util.error("there was an unspecified Git API failure!"); } } // ensure there are no changes before we apply the patch try { if (!git.status().call().isClean()) { Util.error("cannot run git-vcr while there are uncommitted changes!"); } } catch (NoWorkTreeException e1) { // won't happen assert false; } catch (GitAPIException e1) { Util.error("call to git status failed!"); } // list all the files changed String patchName = patchFile.getName(); Patch patch = new Patch(); try { patch.parse(new FileInputStream(patchFile)); } catch (FileNotFoundException e) { assert false; } catch (IOException e) { Util.error("could not parse the patch file!"); } ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false); try { oldResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // we're about to change the repo, so register a shutdown hook to clean it up Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cleanupGit(git, oldCommit); } }); // apply the patch try { git.apply().setPatch(new FileInputStream(patchFile)).call(); } catch (PatchFormatException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!"); } catch (PatchApplyException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!"); } catch (FileNotFoundException e) { assert false; } catch (GitAPIException e) { Util.error(e.getLocalizedMessage()); } ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true); try { newResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // generate and show the report VelocityReport report = new VelocityReport(patch, oldResults, newResults); File reportFile = null; try { reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html"); org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null); } catch (IOException e) { Util.error("could not generate the results page!"); } try { assert reportFile != null; Desktop.getDesktop().open(reportFile); } catch (IOException e) { Util.error("could not open the results page!"); } }
From source file:com.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java
License:Open Source License
/** * Retrieves all the reviews in the current project's repository by commit hash. *///from w ww .j a v a2s . c o m public Map<String, Review> listReviews() throws GitClientException { // Get the most up-to-date list of reviews. syncCommentsAndReviews(); Map<String, Review> reviews = new LinkedHashMap<>(); Git git = new Git(repo); try { ListNotesCommand cmd = git.notesList(); cmd.setNotesRef(REVIEWS_REF); List<Note> notes = cmd.call(); for (Note note : notes) { String rawNoteDataStr = noteToString(repo, note); Review latest = extractLatestReviewFromNotes(rawNoteDataStr); if (latest != null) { reviews.put(note.getName(), latest); } } } catch (Exception e) { throw new GitClientException(e); } finally { git.close(); } return reviews; }
From source file:com.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java
License:Open Source License
/** * Gets a specific review. Returns null if it is not found. *///from ww w. ja v a 2 s. c o m public Review getReview(String reviewCommitHash) throws GitClientException { try (Git git = new Git(repo)) { String noteDataStr = readOneNote(git, REVIEWS_REF, reviewCommitHash); return extractLatestReviewFromNotes(noteDataStr); } }