List of usage examples for org.eclipse.jgit.api Git log
public LogCommand log()
From source file:org.ossmeter.platform.vcs.git.GitManager.java
License:Open Source License
@Override public String[] getRevisionsForDate(VcsRepository repository, Date date) throws Exception { long epoch = date.toJavaDate().getTime(); List<String> revisions = new ArrayList<String>(); 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());/*ww w . jav a2s. c o m*/ boolean foundDate = false; while (iterator.hasNext()) { RevCommit commit = iterator.next(); // System.out.println(Long.valueOf(commit.getCommitTime())*1000 + " == " + epoch); // System.err.println("comparing " +new Date(Long.valueOf(commit.getCommitTime())*1000) + " with date " + date + " and epoch " + epoch); if (new Date(Long.valueOf(commit.getCommitTime()) * 1000).compareTo(date) == 0) { foundDate = true; revisions.add(0, commit.getId().getName()); //FIXME: Added the zero index to in an attempt to bugfix } else if (foundDate) { break; } } return revisions.toArray(new String[revisions.size()]); }
From source file:org.ossmeter.platform.vcs.git.GitManager.java
License:Open Source License
@Override public Date getDateForRevision(VcsRepository repository, String revision) 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());/*from ww w. j a v a 2s . com*/ Date date = null; while (iterator.hasNext()) { RevCommit commit = iterator.next(); if (commit.getId().getName().equals(revision)) { date = new Date(Long.valueOf(commit.getCommitTime()) * 1000); } } return date; }
From source file:org.repodriller.scm.GitRepository.java
License:Apache License
private List<ChangeSet> getAllCommits(Git git) throws GitAPIException, IOException { List<ChangeSet> allCs = new ArrayList<>(); for (RevCommit r : git.log().call()) { allCs.add(extractChangeSet(r));//w w w . j a v a 2 s . co m } return allCs; }
From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java
License:Apache License
/** * Tests a special use case where the remote repository has been updated with a forced * push conflicting with the local repo of the Config Server. The Config Server has to * reset hard on the new reference because a simple pull operation could result in a * conflicting local repository./*from www . j av a 2s . c o m*/ */ @Test public void pullDirtyRepo() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); // Create a remote bare repository. Repository remote = ConfigServerTestUtils.prepareBareRemote(); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); // Pushes the raw branch to remote repository. git.push().call(); String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false) .run("--spring.cloud.config.server.git.uri=" + uri); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); // Fetches the repository for the first time. SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), commitToRevertBeforePull); // Resets to the original commit. git.reset().setMode(ResetType.HARD).setRef("master").call(); // Generate a conflicting commit who will be forced on the origin. Path applicationFilePath = Paths.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml"); Files.write(applicationFilePath, Arrays.asList("info:", " foo: bar", "raw: false"), StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); git.add().addFilepattern(".").call(); git.commit().setMessage("Conflicting commit.").call(); git.push().setForce(true).call(); String conflictingCommit = git.log().setMaxCount(1).call().iterator().next().getName(); // Reset to the raw branch. git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call(); // Triggers the repository refresh. locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), conflictingCommit); assertTrue("Local repository is not cleaned after retrieving resources.", git.status().call().isClean()); }
From source file:org.wise.portal.presentation.web.controllers.author.project.JGitUtils.java
License:Open Source License
/** * Returns commit history for specified directory * * @param directoryPath/* w ww . jav a 2 s . c om*/ * @return * @throws IOException * @throws GitAPIException */ public static Iterable<RevCommit> getCommitHistory(String directoryPath) throws IOException, GitAPIException { boolean doCreate = false; Repository gitRepository = getGitRepository(directoryPath, doCreate); if (gitRepository == null) { return null; } else { Git git = new Git(gitRepository); Iterable<RevCommit> commits = git.log().all().call(); gitRepository.close(); return commits; } }
From source file:persistence.git.document.RevCommitRepository.java
License:Open Source License
Optional<RevCommit> getLastRevCommit(final Git git) throws SourceControlUnspecifiedException { Optional<RevCommit> lastCommit; try {//from www .ja va 2 s . c o m lastCommit = Lists.newArrayList(git.log().call()).stream().sorted(Collections.reverseOrder( (RevCommit u1, RevCommit u2) -> Integer.compare(u1.getCommitTime(), u2.getCommitTime()))) .findFirst(); } catch (GitAPIException e) { throw new SourceControlUnspecifiedException(e); } return lastCommit; }
From source file:playRepository.GitRepository.java
License:Apache License
/** * @see <a href="https://www.kernel.org/pub/software/scm/git/docs/git-log.html">git log until</a> *//* w w w . j ava2s . c o m*/ private ObjectNode fileAsJson(TreeWalk treeWalk, AnyObjectId untilCommitId) throws IOException, GitAPIException { Git git = new Git(repository); GitCommit commit = new GitCommit( git.log().add(untilCommitId).addPath(treeWalk.getPathString()).call().iterator().next()); ObjectNode result = Json.newObject(); long commitTime = commit.getCommitTime() * 1000L; User author = commit.getAuthor(); result.put("type", "file"); result.put("msg", commit.getShortMessage()); result.put("author", commit.getAuthorName()); result.put("avatar", getAvatar(author)); result.put("userName", author.name); result.put("userLoginId", author.loginId); result.put("createdDate", commitTime); result.put("commitMessage", commit.getShortMessage()); result.put("commiter", commit.getCommitterName()); result.put("commitDate", commitTime); result.put("commitId", untilCommitId.getName()); ObjectLoader file = repository.open(treeWalk.getObjectId(0)); result.put("size", file.getSize()); boolean isBinary = RawText.isBinary(file.openStream()); result.put("isBinary", isBinary); if (!isBinary && file.getSize() <= MAX_FILE_SIZE_CAN_BE_VIEWED) { byte[] bytes = file.getBytes(); String str = new String(bytes, FileUtil.detectCharset(bytes)); result.put("data", str); } Metadata meta = new Metadata(); meta.add(Metadata.RESOURCE_NAME_KEY, treeWalk.getNameString()); result.put("mimeType", new Tika().detect(file.openStream(), meta)); return result; }
From source file:plumber.core.git.test.BasicGitTest.java
License:Apache License
@Test public void testGitInit() throws IOException, GitAPIException { String targetPath = getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + "/.."; System.setProperty(PLUMBER_GIT_URL.configKey(), "git@github.com:github/testrepo.git"); System.setProperty(PLUMBER_GIT_PATH.configKey(), targetPath + "/junit-git-iaac"); PlumberConfig.reload();/* w w w .j ava 2s . c o m*/ System.clearProperty(PLUMBER_GIT_URL.configKey()); System.clearProperty(PLUMBER_GIT_PATH.configKey()); File gitFolder = new File(PlumberConfig.get(PLUMBER_GIT_PATH)); if (gitFolder.exists() && gitFolder.isDirectory()) { FileUtils.deleteDirectory(gitFolder); } assertTrue(gitFolder.mkdirs()); GitWorker gitWorker = new GitWorker(PlumberConfig.get(PLUMBER_GIT_URL), PlumberConfig.get(PLUMBER_GIT_PATH)); gitWorker.init(); gitWorker = new GitWorker(PlumberConfig.get(PLUMBER_GIT_URL), PlumberConfig.get(PLUMBER_GIT_PATH)); gitWorker.init(); Git git = gitWorker.getGit(); assertNotNull(git); Iterator<RevCommit> log = git.log().call().iterator(); assertTrue(log.hasNext()); String latestRef = log.next().getName(); assertTrue(log.hasNext()); String previousRef = log.next().getName(); assertNotEquals(latestRef, previousRef); ResetCommand resetCommand = git.reset(); resetCommand.setMode(ResetCommand.ResetType.HARD); resetCommand.setRef("HEAD~1"); resetCommand.call(); assertTrue(git.log().call().iterator().hasNext()); log = git.log().call().iterator(); assertTrue(log.hasNext()); String latestRefAfterRebase = log.next().getName(); assertEquals(previousRef, latestRefAfterRebase); PullResult pullResult = gitWorker.pull(); assertTrue(pullResult.isSuccessful()); assertEquals(MergeResult.MergeStatus.FAST_FORWARD, pullResult.getMergeResult().getMergeStatus()); log = git.log().call().iterator(); assertTrue(log.hasNext()); String latestRefAfterRePull = log.next().getName(); assertEquals(latestRef, latestRefAfterRePull); if (gitFolder.exists() && gitFolder.isDirectory()) { FileUtils.deleteDirectory(gitFolder); } }
From source file:replicatorg.app.ui.panels.UpdateChecker.java
License:Open Source License
private void updateFilaments() { final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder(); final Git git; final Status repoStatus; final RemoteAddCommand remoteAddCmd; ResetCommand resetCmd;/*from ww w .java2 s . c o m*/ CheckoutCommand checkoutCmd; final String currentBranch, newBranch; final List<Ref> branchList; Repository filamentsRepo; boolean branchFoundLocally = false; RevCommit stash = null; repoBuilder.setMustExist(true); repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git")); try { try { Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass()); filamentsRepo = repoBuilder.build(); } catch (RepositoryNotFoundException ex) { try { Base.writeLog("Repository wasn't initialized, initializing it to the given URL: " + FILAMENTS_REPO_URL, this.getClass()); repoBuilder.setMustExist(false); filamentsRepo = repoBuilder.build(); filamentsRepo.create(); } catch (IOException ex1) { Base.writeLog("IOException while attempting to initialize repository, not updating filaments", this.getClass()); return; } } currentBranch = filamentsRepo.getBranch(); } catch (IOException ex) { Base.writeLog("IOException while attempting to open repository, not updating filaments", this.getClass()); return; } git = new Git(filamentsRepo); try { // it should be only 1, but it shortens the code needed, as the call() // method returns an iterable for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Current commit hash: " + commit, this.getClass()); } } catch (GitAPIException ex) { Base.writeLog( "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update", this.getClass()); } try { remoteAddCmd = git.remoteAdd(); remoteAddCmd.setName("origin"); remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL)); remoteAddCmd.call(); } catch (URISyntaxException ex) { Base.writeLog("Invalid git filament repo remote URL!", this.getClass()); return; } catch (GitAPIException ex) { Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass()); return; } try { if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH + ", searching for it", this.getClass()); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); branchList = git.branchList().call(); for (Ref ref : branchList) { if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) { Base.writeLog("Correct branch was found locally", this.getClass()); branchFoundLocally = true; break; } } if (branchFoundLocally == false) { Base.writeLog( "No correct branch was found locally, attempting to checkout a new branch tracking the remote", this.getClass()); checkoutCmd.setCreateBranch(true); checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK); checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH); git.fetch().call(); } RevCommit backup = null; if (git.status().call().isClean() == false) { git.add().addFilepattern(".").call(); backup = git.commit().setMessage("local backup of user modifications").call(); } newBranch = checkoutCmd.call().getName(); if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Unable to change to correct branch, aborting update", this.getClass()); return; } else { Base.writeLog("Changed to correct branch, " + newBranch, this.getClass()); } try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after branch change: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update", this.getClass()); } if (backup != null) { // TODO: restore backup of user modifications //git.cherryPick().setNoCommit(true).include(backup).call(); } } repoStatus = git.status().call(); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); checkoutCmd.call(); git.fetch(); resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); git.pull().call(); /* repoStatus = git.status().call(); if (repoStatus.hasUncommittedChanges()) { Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass()); stash = git.stashCreate().call(); git.pull().call(); git.stashApply().call(); // will apply the last stash made git.stashDrop().call(); // remove the last stash made } else { Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass()); git.pull().call(); } */ Base.writeLog("Filament update concluded successfully!", this.getClass()); try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after update process finished: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update", this.getClass()); } } catch (GitAPIException ex) { Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass()); try { resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); if (stash != null) { git.stashApply().call(); git.stashDrop().call(); } } catch (GitAPIException ex1) { Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...", this.getClass()); } } }
From source file:services.player.ZoneManager.java
License:Open Source License
private void loadCommitHistory() { File repoDir = new File("./" + Constants.DOT_GIT); int commitCount = 3; int iterations = 0; try {// w w w . j a va 2 s .c om Git git = Git.open(repoDir); Repository repo = git.getRepository(); try { commitHistory = "The " + commitCount + " most recent commits in branch '" + repo.getBranch() + "':\n"; for (RevCommit commit : git.log().setMaxCount(commitCount).call()) { commitHistory += commit.getName().substring(0, 7) + " " + commit.getShortMessage(); if (commitCount > iterations++) commitHistory += "\n"; } } catch (GitAPIException e) { e.printStackTrace(); } } catch (IOException e) { System.err.println("ZoneManager: Failed to open " + repoDir + " to read commit history"); // An exception is thrown if bash isn't installed. // https://www.eclipse.org/forums/index.php/t/1031740/ } }