Java Code Examples for org.eclipse.jgit.api.Git#getRepository()
The following examples show how to use
org.eclipse.jgit.api.Git#getRepository() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitTool.java From yacy_grid_mcp with GNU Lesser General Public License v2.1 | 7 votes |
public GitTool() { File gitWorkDir = new File("."); try { Git git = Git.open(gitWorkDir); Iterable<RevCommit> commits = git.log().all().call(); Repository repo = git.getRepository(); branch = repo.getBranch(); RevCommit latestCommit = commits.iterator().next(); name = latestCommit.getName(); message = latestCommit.getFullMessage(); } catch (Throwable e) { name = ""; message = ""; branch = ""; } }
Example 2
Source File: DiffCalculator.java From diff-check with GNU Lesser General Public License v2.1 | 6 votes |
private Map<String, BlobWrapper> getContentMapByTreeAndFilter( Git git, AbstractTreeIterator tree, TreeFilter filter) throws Exception { Map<String, BlobWrapper> contentMap = new LinkedHashMap<>(); try (TreeWalk treeWalk = new TreeWalk(git.getRepository())) { treeWalk.addTree(tree); treeWalk.setRecursive(true); treeWalk.setFilter(filter); while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = git.getRepository().open(objectId); BlobWrapper blobWrapper = BlobWrapper.builder() .blobId(objectId) .content(loader.getBytes()) .build(); contentMap.put(treeWalk.getPathString(), blobWrapper); } } return contentMap; }
Example 3
Source File: GitServiceImpl.java From apidiff with MIT License | 6 votes |
@Override public Repository openRepositoryAndCloneIfNotExists(String path, String projectName, String cloneUrl) throws Exception { File folder = new File(UtilTools.getPathProject(path , projectName)); Repository repository = null; if (folder.exists()) { this.logger.info(projectName + " exists. Reading properties ... (wait)"); RepositoryBuilder builder = new RepositoryBuilder(); repository = builder .setGitDir(new File(folder, ".git")) .readEnvironment() .findGitDir() .build(); } else { this.logger.info("Cloning " + cloneUrl + " in " + cloneUrl + " ... (wait)"); Git git = Git.cloneRepository() .setDirectory(folder) .setURI(cloneUrl) .setCloneAllBranches(true) .call(); repository = git.getRepository(); } this.logger.info("Process " + projectName + " finish."); return repository; }
Example 4
Source File: AppraiseGitReviewClient.java From git-appraise-eclipse with Eclipse Public License 1.0 | 6 votes |
/** * Reads a single note out as a string from the given commit hash. * Returns null if the note isn't found. */ private String readOneNote(Git git, String notesRef, String hash) throws GitClientException { try (RevWalk walker = new RevWalk(git.getRepository())) { ShowNoteCommand cmd = git.notesShow(); cmd.setNotesRef(notesRef); ObjectId ref = git.getRepository().resolve(hash); RevCommit commit = walker.parseCommit(ref); cmd.setObjectId(commit); Note note = cmd.call(); if (note == null) { return null; } return noteToString(repo, note); } catch (Exception e) { throw new GitClientException(e); } }
Example 5
Source File: GitCommit.java From app-runner with MIT License | 5 votes |
public static GitCommit fromHEAD(Git git) throws Exception { ObjectId head = git.getRepository().resolve("HEAD"); if (head != null) { RevCommit mostRecentCommit; try (RevWalk walk = new RevWalk(git.getRepository())) { mostRecentCommit = walk.parseCommit(head); } Date commitDate = new Date(1000L * mostRecentCommit.getCommitTime()); String id = mostRecentCommit.getId().name(); PersonIdent author = mostRecentCommit.getAuthorIdent(); return new GitCommit(id, commitDate, author.getName(), mostRecentCommit.getFullMessage()); } else { return null; } }
Example 6
Source File: DiffCalculator.java From diff-check with GNU Lesser General Public License v2.1 | 5 votes |
private List<DiffEntryWrapper> doCalculateCommitDiff( RevCommit oldCommit, RevCommit newCommit, ObjectReader reader, Git git, File repoDir, Set<String> excludedPathSet) throws Exception { if (Objects.equals(oldCommit.getId(), newCommit.getId())) { return Collections.emptyList(); } if (Objects.equals(oldCommit.getTree().getId(), newCommit.getTree().getId())) { return Collections.emptyList(); } RenameDetector detector = new RenameDetector(git.getRepository()); AbstractTreeIterator oldTree = new CanonicalTreeParser(null, reader, oldCommit.getTree()); AbstractTreeIterator newTree = new CanonicalTreeParser(null, reader, newCommit.getTree()); List<DiffEntry> entries = git.diff() .setOldTree(oldTree) .setNewTree(newTree) .call(); detector.reset(); detector.addAll(entries); entries = detector.compute(); return entries.stream() .filter(entry -> !excludedPathSet.contains(entry.getNewPath())) .map(entry -> { RawText oldText = newRawText(entry, DiffEntry.Side.OLD, reader); RawText newText = newRawText(entry, DiffEntry.Side.NEW, reader); return DiffEntryWrapper.builder() .gitDir(repoDir) .diffEntry(entry) .editList(calculateEditList(oldText, newText)) .build(); }).collect(Collectors.toList()); }
Example 7
Source File: GitHelperTest.java From repairnator with MIT License | 5 votes |
@Test public void testcomputePatchStats() throws GitAPIException, IOException { JobStatus jobStatus = new JobStatus("fakePomDirPath"); String remoteRepo = "https://github.com/Spirals-Team/jtravis.git"; String parentCommit = "2d65266f9a52b27f955ec9a74aa9ab4dac5537d7"; String commit = "f267c73200e2ebb9431d6ffe80e507222567696c"; // GH says: 14 changed files, 443 additions, 104 deletions, // on java files is: 13 changed files, 405 additions, 104 deletions tmpDir = java.nio.file.Files.createTempDirectory("jtravis").toFile(); Git git = Git.cloneRepository().setURI(remoteRepo).setBranch("master").setDirectory(tmpDir).call(); RevWalk revwalk = new RevWalk(git.getRepository()); RevCommit revParentCommit = revwalk.parseCommit(ObjectId.fromString(parentCommit)); RevCommit revCommit = revwalk.parseCommit(ObjectId.fromString(commit)); GitHelper gitHelper = new GitHelper(); gitHelper.computePatchStats(jobStatus, git, revCommit, revParentCommit); PatchDiff patchDiff = jobStatus.getProperties().getPatchDiff(); assertEquals(8, patchDiff.getFiles().getNumberAdded()); assertEquals(1, patchDiff.getFiles().getNumberDeleted()); assertEquals(4, patchDiff.getFiles().getNumberChanged()); assertEquals(405, patchDiff.getLines().getNumberAdded()); assertEquals(104, patchDiff.getLines().getNumberDeleted()); }
Example 8
Source File: DocumentationGitBasedManager.java From scava with Eclipse Public License 2.0 | 5 votes |
private String getLastRevisionBeforeDate(VcsRepository repository, Date date) throws Exception { Git git = getGit((GitRepository)repository); Repository repo = git.getRepository(); RevWalk walk = new RevWalk(repo); Iterator<RevCommit> iterator = git.log().call().iterator(); String revision=""; // The commits are ordered latest first, so we want to find the fist that it is before the date int dateComparison; while(iterator.hasNext()) { RevCommit commit = walk.parseCommit(iterator.next()); dateComparison=new Date(Long.valueOf(commit.getCommitTime())*1000).compareTo(date); if (dateComparison < 0) { revision=commit.getId().getName(); break; } } walk.close(); repo.close(); git.close(); if(revision.isEmpty()) return ""; return revision; }
Example 9
Source File: GitCommitTest.java From app-runner with MIT License | 5 votes |
@Test public void returnsCurrentCommitForNonEmptyRepos() throws Exception { long timeAtStartOfTest = System.currentTimeMillis() - 1000; Git git = emptyRepo(); FileRepository repository = (FileRepository) git.getRepository(); File dir = repository.getDirectory(); FileUtils.writeStringToFile(new File(dir, "file1"), "Hello", "UTF-8"); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit") .setAuthor(new PersonIdent("Author Test", "[email protected]")) .call(); FileUtils.writeStringToFile(new File(dir, "file2"), "Hello too", "UTF-8"); git.add().addFilepattern(".").call(); git.commit().setMessage("Second commit") .setAuthor(new PersonIdent("Second contributor", "[email protected]")) .call(); JSONObject actual = GitCommit.fromHEAD(git).toJSON(); JSONAssert.assertEquals("{" + "author: 'Second contributor', message: 'Second commit'" + "}", actual, JSONCompareMode.LENIENT); assertThat(actual.getLong("date"), Matchers.greaterThanOrEqualTo(timeAtStartOfTest)); assertThat(actual.getString("id"), actual.getString("id").length(), is("3688d7063d2d647e3989d62d9770d0dfd0ce3c25".length())); }
Example 10
Source File: AbstractGitPersistenceResourceTestCase.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
private List<String> listTags(Git git) throws IOException, GitAPIException { List<String> tags = new ArrayList<>(); for (Ref tag : git.tagList().call()) { RevWalk revWalk = new RevWalk(git.getRepository()); revWalk.sort(RevSort.COMMIT_TIME_DESC, true); try { RevTag annotatedTag = revWalk.parseTag(tag.getObjectId()); tags.add(annotatedTag.getTagName() + " : " + annotatedTag.getFullMessage()); } catch (IncorrectObjectTypeException ex) { tags.add(tag.getName().substring("refs/tags/".length())); } } return tags; }
Example 11
Source File: GitManager.java From scava with Eclipse Public License 2.0 | 5 votes |
@Override public int compareVersions(VcsRepository repository, String versionOne, String versionTwo) throws Exception { Git git = getGit((GitRepository)repository); Repository repo = git.getRepository(); RevWalk walk = new RevWalk(repo); Iterator<RevCommit> iterator = git.log().call().iterator(); walk.parseCommit(iterator.next()); List<String> revisions = new ArrayList<String>(); // The commits are ordered latest first, so we want the last one. while(iterator.hasNext()) { RevCommit commit = iterator.next(); revisions.add(commit.getId().getName()); } Integer oneIndex = revisions.indexOf(versionOne); Integer twoIndex = revisions.indexOf(versionTwo); // System.out.println(oneIndex); // System.out.println(twoIndex); // System.out.println(revisions); repo.close(); git.close(); // Because the revision list is reversed, we compare two to one instead of the other way around return twoIndex.compareTo(oneIndex); }
Example 12
Source File: Status.java From wandora with GNU General Public License v3.0 | 5 votes |
@Override public void execute(Wandora wandora, Context context) { try { Git git = getGit(); if(git != null) { setDefaultLogger(); setLogTitle("Git status"); Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); log("Git conf:"); log(config.toText()); log("Git status:"); org.eclipse.jgit.api.Status status = git.status().call(); log("Added: " + status.getAdded()); log("Changed: " + status.getChanged()); log("Conflicting: " + status.getConflicting()); log("ConflictingStageState: " + status.getConflictingStageState()); log("IgnoredNotInIndex: " + status.getIgnoredNotInIndex()); log("Missing: " + status.getMissing()); log("Modified: " + status.getModified()); log("Removed: " + status.getRemoved()); log("Untracked: " + status.getUntracked()); log("UntrackedFolders: " + status.getUntrackedFolders()); log("Ready."); } else { logAboutMissingGitRepository(); } } catch(Exception e) { log(e); } setState(WAIT); }
Example 13
Source File: GitServiceImpl.java From RefactoringMiner with MIT License | 4 votes |
@Override public Repository cloneIfNotExists(String projectPath, String cloneUrl/*, String branch*/) throws Exception { File folder = new File(projectPath); Repository repository; if (folder.exists()) { RepositoryBuilder builder = new RepositoryBuilder(); repository = builder .setGitDir(new File(folder, ".git")) .readEnvironment() .findGitDir() .build(); //logger.info("Project {} is already cloned, current branch is {}", cloneUrl, repository.getBranch()); } else { logger.info("Cloning {} ...", cloneUrl); Git git = Git.cloneRepository() .setDirectory(folder) .setURI(cloneUrl) .setCloneAllBranches(true) .call(); repository = git.getRepository(); //logger.info("Done cloning {}, current branch is {}", cloneUrl, repository.getBranch()); } // if (branch != null && !repository.getBranch().equals(branch)) { // Git git = new Git(repository); // // String localBranch = "refs/heads/" + branch; // List<Ref> refs = git.branchList().call(); // boolean branchExists = false; // for (Ref ref : refs) { // if (ref.getName().equals(localBranch)) { // branchExists = true; // } // } // // if (branchExists) { // git.checkout() // .setName(branch) // .call(); // } else { // git.checkout() // .setCreateBranch(true) // .setName(branch) // .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) // .setStartPoint("origin/" + branch) // .call(); // } // // logger.info("Project {} switched to {}", cloneUrl, repository.getBranch()); // } return repository; }
Example 14
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 4 votes |
protected String doDiff(Git git, String objectId, String baseObjectId, String pathOrBlobPath) throws IOException { Repository r = git.getRepository(); String blobPath = trimLeadingSlash(pathOrBlobPath); RevCommit commit; if (Strings.isNotBlank(objectId)) { commit = CommitUtils.getCommit(r, objectId); } else { commit = CommitUtils.getHead(r); } RevCommit baseCommit = null; if (Strings.isNotBlank(baseObjectId) && !Objects.equals(baseObjectId, objectId)) { baseCommit = CommitUtils.getCommit(r, baseObjectId); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DiffFormatter formatter = createDiffFormatter(r, buffer); RevTree commitTree = commit.getTree(); RevTree baseTree; if (baseCommit == null) { if (commit.getParentCount() > 0) { final RevWalk rw = new RevWalk(r); RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); rw.dispose(); baseTree = parent.getTree(); } else { // FIXME initial commit. no parent?! baseTree = commitTree; } } else { baseTree = baseCommit.getTree(); } List<DiffEntry> diffEntries = formatter.scan(baseTree, commitTree); if (blobPath != null && blobPath.length() > 0) { for (DiffEntry diffEntry : diffEntries) { if (diffEntry.getNewPath().equalsIgnoreCase(blobPath)) { formatter.format(diffEntry); break; } } } else { formatter.format(diffEntries); } formatter.flush(); return buffer.toString(); }
Example 15
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 4 votes |
protected static RevCommit doGetCommit(Git git, String commitId) { Repository repository = git.getRepository(); return CommitUtils.getCommit(repository, commitId); }
Example 16
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 4 votes |
protected List<CommitInfo> doHistory(Git git, String objectId, String pathOrBlobPath, int limit) { List<CommitInfo> results = new ArrayList<CommitInfo>(); Repository r = git.getRepository(); try { String head = getHEAD(git); } catch (Exception e) { LOG.error("Cannot find HEAD of this git repository! " + e, e); return results; } String path = trimLeadingSlash(pathOrBlobPath); CommitFinder finder = new CommitFinder(r); CommitListFilter filter = new CommitListFilter(); if (Strings.isNotBlank(path)) { finder.setFilter(PathFilterUtils.and(path)); } finder.setFilter(filter); if (limit > 0) { finder.setFilter(new CommitLimitFilter(limit).setStop(true)); } if (Strings.isNotBlank(objectId)) { finder.findFrom(objectId); } else { if (Strings.isNotBlank(branch)) { ObjectId branchObjectId = getBranchObjectId(git); if (branchObjectId != null) { finder = finder.findFrom(branchObjectId); } else { finder = finder.findInBranches(); } } else { finder.find(); } } List<RevCommit> commits = filter.getCommits(); for (RevCommit entry : commits) { CommitInfo commitInfo = createCommitInfo(entry); results.add(commitInfo); } return results; }
Example 17
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 4 votes |
protected String doGetContent(Git git, String objectId, String pathOrBlobPath) { objectId = defaultObjectId(git, objectId); Repository r = git.getRepository(); String blobPath = trimLeadingSlash(pathOrBlobPath); return BlobUtils.getContent(r, objectId, blobPath); }
Example 18
Source File: CloneCheckoutBranchRepository.java From repairnator with MIT License | 4 votes |
@Override protected StepStatus businessExecute() { String repoUrl = ((GitRepositoryProjectInspector) getInspector()).getGitRepositoryUrl() + ".git"; String branch = null; if (((GitRepositoryProjectInspector) getInspector()).getGitRepositoryBranch() != null) { branch = "refs/heads/" + ((GitRepositoryProjectInspector) getInspector()).getGitRepositoryBranch(); } String repoLocalPath = this.getInspector().getRepoLocalPath(); try { this.getLogger().info("Cloning repository " + repoUrl + " in the following directory: " + repoLocalPath); List<String> branchList = new ArrayList<String>(); branchList.add(branch); CloneCommand cloneRepositoryCommand = Git.cloneRepository() .setCloneSubmodules(true) .setURI( repoUrl ) .setDirectory(new File(repoLocalPath)); if (branch != null) { cloneRepositoryCommand.setBranchesToClone(branchList).setBranch(branch); } Git git = cloneRepositoryCommand.call(); Repository repository = git.getRepository(); List<RevCommit> commits = getBranchCommits(repository, repoLocalPath); if (getConfig().isGitRepositoryFirstCommit()) { git.checkout().setName(commits.get(commits.size()-1).getName()).call(); } else if (getConfig().getGitRepositoryIdCommit() != null) { git.checkout().setName(getConfig().getGitRepositoryIdCommit()).call(); } else { git.checkout().setName(commits.get(0).getName()).call(); } return StepStatus.buildSuccess(this); } catch (Exception e) { this.addStepError("Repository " + repoUrl + " cannot be cloned.", e); return StepStatus.buildError(this, PipelineState.NOTCLONABLE); } }
Example 19
Source File: GitHelper.java From repairnator with MIT License | 4 votes |
public boolean mergeTwoCommitsForPR(Git git, Build build, PullRequest prInformation, String repository, AbstractStep step, List<String> paths) { try { String remoteBranchPath = Utils.getCompleteGithubRepoUrl(prInformation.getOtherRepo().getFullName()); RemoteAddCommand remoteBranchCommand = git.remoteAdd(); remoteBranchCommand.setName("PR"); remoteBranchCommand.setUri(new URIish(remoteBranchPath)); remoteBranchCommand.call(); git.fetch().setRemote("PR").call(); String commitHeadSha = this.testCommitExistence(git, prInformation.getHead().getSHA1(), step, build); String commitBaseSha = this.testCommitExistence(git, prInformation.getBase().getSHA1(), step, build); if (commitHeadSha == null) { step.addStepError("Commit head ref cannot be retrieved from the repository: " + prInformation.getHead().getSHA1() + ". Operation aborted."); return false; } if (commitBaseSha == null) { step.addStepError("Commit base ref cannot be retrieved from the repository: " + prInformation.getBase().getSHA1() + ". Operation aborted."); return false; } this.getLogger().debug("Step " + step.getName() + " - Get the commit " + commitHeadSha + " for repo " + repository); if (paths != null) { this.gitResetPaths(commitHeadSha, paths, git.getRepository().getDirectory().getParentFile()); git.commit().setMessage("Undo changes on source code").setAuthor(this.getCommitterIdent()).setCommitter(this.getCommitterIdent()).call(); } else { git.checkout().setName(commitHeadSha).call(); } RevWalk revwalk = new RevWalk(git.getRepository()); RevCommit revCommitBase = revwalk.lookupCommit(git.getRepository().resolve(commitBaseSha)); this.getLogger().debug("Step " + step.getName() + " - Do the merge with the PR commit for repo " + repository); MergeResult result = git.merge().include(revCommitBase).setFastForward(MergeCommand.FastForwardMode.NO_FF).call(); this.nbCommits++; } catch (Exception e) { step.addStepError(e.getMessage()); this.getLogger().error("Step " + step.getName() + " - Repository " + repository + " cannot be cloned.",e); return false; } return true; }
Example 20
Source File: ThemeServiceImpl.java From halo with GNU General Public License v3.0 | 4 votes |
private void pullFromGit(@NonNull ThemeProperty themeProperty) throws IOException, GitAPIException, URISyntaxException { Assert.notNull(themeProperty, "Theme property must not be null"); // Get branch String branch = StringUtils.isBlank(themeProperty.getBranch()) ? DEFAULT_REMOTE_BRANCH : themeProperty.getBranch(); Git git = null; try { git = GitUtils.openOrInit(Paths.get(themeProperty.getThemePath())); Repository repository = git.getRepository(); RevWalk revWalk = new RevWalk(repository); Ref ref = repository.findRef(Constants.HEAD); Assert.notNull(ref, Constants.HEAD + " ref was not found!"); RevCommit lastCommit = revWalk.parseCommit(ref.getObjectId()); // Force to set remote name git.remoteRemove().setRemoteName(THEME_PROVIDER_REMOTE_NAME).call(); RemoteConfig remoteConfig = git.remoteAdd() .setName(THEME_PROVIDER_REMOTE_NAME) .setUri(new URIish(themeProperty.getRepo())) .call(); // Add all changes git.add() .addFilepattern(".") .call(); // Commit the changes git.commit().setMessage("Commit by halo automatically").call(); // Check out to specified branch if (!StringUtils.equalsIgnoreCase(branch, git.getRepository().getBranch())) { boolean present = git.branchList() .call() .stream() .map(Ref::getName) .anyMatch(name -> StringUtils.equalsIgnoreCase(name, branch)); git.checkout() .setCreateBranch(true) .setForced(!present) .setName(branch) .call(); } // Pull with rebasing PullResult pullResult = git.pull() .setRemote(remoteConfig.getName()) .setRemoteBranchName(branch) .setRebase(true) .call(); if (!pullResult.isSuccessful()) { log.debug("Rebase result: [{}]", pullResult.getRebaseResult()); log.debug("Merge result: [{}]", pullResult.getMergeResult()); throw new ThemeUpdateException("拉取失败!您与主题作者可能同时更改了同一个文件"); } // updated successfully. ThemeProperty updatedThemeProperty = getProperty(Paths.get(themeProperty.getThemePath())); // Not support current halo version. if (StringUtils.isNotEmpty(updatedThemeProperty.getRequire()) && !VersionUtil.compareVersion(HaloConst.HALO_VERSION, updatedThemeProperty.getRequire())) { // reset theme version git.reset() .setMode(ResetCommand.ResetType.HARD) .setRef(lastCommit.getName()) .call(); throw new ThemeNotSupportException("新版本主题仅支持 Halo " + updatedThemeProperty.getRequire() + " 以上的版本"); } } finally { GitUtils.closeQuietly(git); } }