List of usage examples for org.eclipse.jgit.api Git log
public LogCommand log()
From source file:fr.brouillard.oss.jgitver.GitVersionCalculator.java
License:Apache License
private Version buildVersion(Git git, VersionStrategy strategy) { try {/*from w w w. j a v a 2s . c o m*/ // metadatas.registerMetadata(Metadatas.DIRTY, "" + GitUtils.isDirty(git)); // retrieve all tags matching a version, and get all info for each of them List<Ref> allTags = git.tagList().call().stream().map(this::peel) .collect(Collectors.toCollection(ArrayList::new)); // let's have tags sorted from most recent to oldest Collections.reverse(allTags); metadatas.registerMetadataTags(Metadatas.ALL_TAGS, allTags.stream()); metadatas.registerMetadataTags(Metadatas.ALL_ANNOTATED_TAGS, allTags.stream().filter(GitUtils::isAnnotated)); metadatas.registerMetadataTags(Metadatas.ALL_LIGHTWEIGHT_TAGS, allTags.stream().filter(as(GitUtils::isAnnotated).negate())); List<Ref> allVersionTags = allTags.stream().filter(strategy::considerTagAsAVersionOne) .collect(Collectors.toCollection(ArrayList::new)); List<Ref> normals = allVersionTags.stream().filter(GitUtils::isAnnotated).collect(Collectors.toList()); List<Ref> lights = allVersionTags.stream().filter(as(GitUtils::isAnnotated).negate()) .collect(Collectors.toList()); metadatas.registerMetadataTags(Metadatas.ALL_VERSION_TAGS, allVersionTags.stream()); metadatas.registerMetadataTags(Metadatas.ALL_VERSION_ANNOTATED_TAGS, normals.stream()); metadatas.registerMetadataTags(Metadatas.ALL_VERSION_LIGHTWEIGHT_TAGS, lights.stream()); ObjectId rootId = repository.resolve("HEAD"); // handle a call on an empty git repository if (rootId == null) { // no HEAD exist // the GIT repo might just be initialized without any commit return Version.EMPTY_REPOSITORY_VERSION; } git.log().add(rootId).setMaxCount(1).call().spliterator().tryAdvance(rc -> { PersonIdent commitInfo = rc.getAuthorIdent(); metadatas.registerMetadata(Metadatas.HEAD_COMMITTER_NAME, commitInfo.getName()); metadatas.registerMetadata(Metadatas.HEAD_COMMITER_EMAIL, commitInfo.getEmailAddress()); dtfmt.setTimeZone(commitInfo.getTimeZone()); metadatas.registerMetadata(Metadatas.HEAD_COMMIT_DATETIME, dtfmt.format(commitInfo.getWhen())); }); metadatas.registerMetadataTags(Metadatas.HEAD_TAGS, tagsOf(allTags, rootId).stream()); metadatas.registerMetadataTags(Metadatas.HEAD_ANNOTATED_TAGS, tagsOf(allTags.stream().filter(GitUtils::isAnnotated).collect(Collectors.toList()), rootId) .stream()); metadatas.registerMetadataTags(Metadatas.HEAD_LIGHTWEIGHT_TAGS, tagsOf(allTags.stream().filter(as(GitUtils::isAnnotated).negate()).collect(Collectors.toList()), rootId).stream()); metadatas.registerMetadata(Metadatas.GIT_SHA1_FULL, rootId.getName()); metadatas.registerMetadata(Metadatas.GIT_SHA1_8, rootId.getName().substring(0, 8)); Commit head = new Commit(rootId, 0, tagsOf(normals, rootId), tagsOf(lights, rootId)); List<Commit> commits = new LinkedList<>(); try (RevWalk revWalk = new RevWalk(repository)) { revWalk.markStart(revWalk.parseCommit(rootId)); int depth = 0; ObjectId id = null; for (RevCommit rc : revWalk) { id = rc.getId(); List<Ref> annotatedCommitTags = tagsOf(normals, id); List<Ref> lightCommitTags = tagsOf(lights, id); if (annotatedCommitTags.size() > 0 || lightCommitTags.size() > 0) { // we found a commit with version tags Commit c = new Commit(id, depth, annotatedCommitTags, lightCommitTags); commits.add(c); // shall we stop searching for commits if (StrategySearchMode.STOP_AT_FIRST.equals(strategy.searchMode())) { break; // let's stop } else if (depth >= strategy.searchDepthLimit()) { break; // let's stop } } depth++; } // handle the case where we reached the first commit without finding anything if (commits.size() == 0) { commits.add(new Commit(id, depth - 1, Collections.emptyList(), Collections.emptyList())); } } return strategy.build(head, commits); } catch (Exception ex) { throw new IllegalStateException("failure calculating version", ex); } }
From source file:fr.duminy.tools.jgit.JGitToolboxTest.java
License:Open Source License
private static void log(Git git) throws GitAPIException { File gitDirectory = git.getRepository().getDirectory().getParentFile(); LOGGER.info("Log for {}", gitDirectory.getName()); for (RevCommit commit : git.log().call()) { LOGGER.info("{} {}", commit.getName(), commit.getFullMessage()); }/* w ww. java 2s . c o m*/ }
From source file:fr.obeo.ariadne.ide.connector.git.internal.explorer.GitExplorer.java
License:Open Source License
/** * Computes all the commits that exists in the given Git repository and map them as Ariadne concepts in * the given Ariadne repository.//from w w w . j a v a 2 s . c o m * * @param gitRepository * The Git repository * @param ariadneRepository * The Ariadne repository * @param monitor * The progress monitor */ private void computeCommits(Repository gitRepository, fr.obeo.ariadne.model.scm.Repository ariadneRepository, IProgressMonitor monitor) { int maxThreads = Runtime.getRuntime().availableProcessors(); ExecutorService executorService = Executors.newFixedThreadPool(maxThreads); long start = System.currentTimeMillis(); List<Callable<AriadneCommitExplorerEntry>> callables = new ArrayList<>(); Git git = new Git(gitRepository); LogCommand log = git.log(); try { Iterable<RevCommit> logs = log.call(); Iterator<RevCommit> logIterator = logs.iterator(); monitor.subTask(AriadneGitConnectorMessage.getString("GitExplorer.ExploringCommit")); //$NON-NLS-1$ while (logIterator.hasNext()) { monitor.worked(1); RevCommit revCommit = logIterator.next(); // person's settings Person committer = this.getOrCreatePerson(ariadneRepository, revCommit.getCommitterIdent()); Person author = this.getOrCreatePerson(ariadneRepository, revCommit.getAuthorIdent()); Callable<AriadneCommitExplorerEntry> callable = new AriadneCommitExplorerRunnable(gitRepository, revCommit, committer, author); callables.add(callable); } } catch (NoHeadException e) { e.printStackTrace(); } catch (GitAPIException e) { e.printStackTrace(); } try { List<Future<AriadneCommitExplorerEntry>> results = executorService.invokeAll(callables); executorService.shutdown(); for (Future<AriadneCommitExplorerEntry> commit : results) { try { AriadneCommitExplorerEntry ariadneCommitExplorerEntry = commit.get(); this.commit2ariadneCommit.put(ariadneCommitExplorerEntry.getGitCommit(), ariadneCommitExplorerEntry.getAriadneCommit()); ariadneRepository.getCommits().add(ariadneCommitExplorerEntry.getAriadneCommit()); } catch (ExecutionException e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.println( "Commits: " + ariadneRepository.getCommits().size() + " Time: " + (end - start) + "ms"); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:fr.xebia.workshop.git.GithubRepositoriesCreator.java
License:Apache License
private void processGitRepositoryHandler(Git git, GithubCreateRepositoryRequest createRequest) { try {/*from w ww .j ava 2s . c om*/ RevCommit revCommit = git.log().call().iterator().next(); //call delegate createRequest.getGitRepositoryHandler().updateGitRepository(git, createRequest); logger.info("Local repository is pushing on remote {}", createRequest.getGithubRepositoryUrl()); git.push().setCredentialsProvider(createRequest.getCredentialsProvider()) .setRemote(createRequest.getGithubRepositoryUrl()).call(); git.reset().setRef(revCommit.getName()).setMode(ResetCommand.ResetType.HARD).call(); } catch (IOException e) { throw new RuntimeException("cannot perform git operation", e); } catch (GitAPIException e) { throw new RuntimeException("cannot perform git operation", e); } }
From source file:GitBackend.GitAPI.java
License:Apache License
private static HashMap getRevisionsByLog(Repository repository, String filePath) { HashMap commitMap = new HashMap<String, DateTime>(); Git git = new Git(repository); LogCommand logCommand = null;//from www . jav a 2s . c o m try { logCommand = git.log().add(git.getRepository().resolve(Constants.HEAD)).addPath(filePath); } catch (IOException e) { e.printStackTrace(); } try { for (RevCommit revCommit : logCommand.call()) { DateTime commitDate = new DateTime(1000L * revCommit.getCommitTime()); // Store commit hash and date commitMap.put(revCommit.getName(), commitDate); } } catch (GitAPIException e) { e.printStackTrace(); } return commitMap; }
From source file:io.fabric8.forge.generator.pipeline.JenkinsPipelineLibrary.java
License:Apache License
protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent, UserDetails userDetails) {// w w w.j av a2s . c o m StopWatch watch = new StopWatch(); try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); Git git = new Git(repository); File projectFolder = repository.getDirectory(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remote, "url"); if (io.fabric8.utils.Strings.isNullOrBlank(url)) { LOG.warn("No remote repository url for " + branch + " defined for the git repository at " + projectFolder.getCanonicalPath() + " so cannot pull"); //return; } String mergeUrl = config.getString("branch", branch, "merge"); if (io.fabric8.utils.Strings.isNullOrBlank(mergeUrl)) { LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at " + projectFolder.getCanonicalPath() + " so not doing a pull"); //return; } // lets trash any failed changes LOG.debug("Stashing local changes to the repo"); boolean hasHead = true; try { git.log().all().call(); hasHead = git.getRepository().getAllRefs().containsKey("HEAD"); } catch (NoHeadException e) { hasHead = false; } if (hasHead) { // lets stash any local changes just in case.. try { git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write") .setRef("HEAD").call(); } catch (Throwable e) { LOG.error("Failed to stash changes: " + e, e); Throwable cause = e.getCause(); if (cause != null && cause != e) { LOG.error("Cause: " + cause, cause); } } } //LOG.debug("Resetting the repo"); //git.reset().setMode(ResetCommand.ResetType.HARD).call(); LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: " + url); PullCommand pull = git.pull(); GitUtils.configureCommand(pull, userDetails); pull.setRebase(true).call(); } catch (Throwable e) { LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored.", e); } finally { LOG.debug("doPull took " + watch.taken()); } }
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected <T> T gitOperation(final GitContext context, final GitOperation<T> operation) throws Exception { return lockManager.withLock(gitFolder, new Callable<T>() { @Override/* w w w .j a v a 2 s . c om*/ public T call() throws Exception { projectFileSystem.cloneRepoIfNotExist(userDetails, basedir, cloneUrl); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); Git git = new Git(repository); if (Strings.isNullOrBlank(origin)) { throw new IOException("Could not find remote git URL for folder " + gitFolder.getPath()); } CredentialsProvider credentials = userDetails.createCredentialsProvider(); createPersonIdent(); disableSslCertificateChecks(); LOG.info("Stashing local changes to the repo"); boolean hasHead = true; try { git.log().all().call(); hasHead = git.getRepository().getAllRefs().containsKey("HEAD"); } catch (NoHeadException e) { hasHead = false; } if (hasHead) { // lets stash any local changes just in case.. try { git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write") .setRef("HEAD").call(); } catch (Throwable e) { LOG.error("Failed to stash changes: " + e, e); Throwable cause = e.getCause(); if (cause != null && cause != e) { LOG.error("Cause: " + cause, cause); } } } checkoutBranch(git, context); if (context.isRequirePull()) { doPull(git, context); } T result = operation.call(git, context); if (Strings.isNullOrBlank(message)) { message = ""; } if (context.isRequireCommit() && hasGitChanges(git)) { doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, isPushOnCommit()); } return result; } }); }
From source file:io.fabric8.git.internal.GitHelpers.java
License:Apache License
public static boolean hasGitHead(Git git) throws GitAPIException, IOException { boolean hasHead = true; try {//from w ww . ja v a2s . c om git.log().all().call(); hasHead = git.getRepository().getAllRefs().containsKey("HEAD"); } catch (NoHeadException e) { hasHead = false; } return hasHead; }
From source file:io.fabric8.kubernetes.pipeline.devops.git.GitInfoCallback.java
License:Apache License
/** * {@inheritDoc}// w ww .jav a 2 s. c o m */ @Override public GitConfig invoke(Repository repository, VirtualChannel channel) throws IOException, InterruptedException { Git git = new Git(repository); Iterable<RevCommit> log; try { log = git.log().call(); } catch (GitAPIException e) { listener.error("Unable to get git log: " + e); GitConfig config = new GitConfig(); config.setAuthor("UNKNOWN"); config.setCommit("UNKNOWN"); config.setBranch("UNKNOWN"); return config; } RevCommit commit = log.iterator().next(); GitConfig config = new GitConfig(); config.setAuthor(commit.getCommitterIdent().getName()); config.setCommit(commit.getId().getName()); config.setBranch(repository.getBranch()); return config; }
From source file:io.liveoak.git.HTTPGitResourceTest.java
License:Open Source License
@Test public void rootResource() throws Exception { // Test #1 - Git Repo present after install File appDir = new File(testApplication.directory().getParentFile(), "newApp"); File appGitDir = new File(appDir, ".git"); // Verify app and git dir do not exist assertThat(appDir.exists()).isFalse(); assertThat(appGitDir.exists()).isFalse(); // Create new app assertThat(execPost(ADMIN_ROOT, "{ \"id\": \"newApp\" }")).hasStatus(201); awaitStability();//from ww w . j av a2 s. c o m // Verify app and git dirs exist assertThat(appDir.exists()).isTrue(); assertThat(appGitDir.exists()).isTrue(); assertThat(new File(appGitDir, ".git").exists()).isFalse(); // Verify REST endpoints assertThat(execGet(GIT_ADMIN_ROOT)).hasStatus(200); assertThat(execGet(GIT_PUBLIC_ROOT)).hasStatus(404).hasNoSuchResource(); // Test #2 - Post a commit, with auto add files to index // Create a file in the application directory File testFile = new File(appDir, "test.txt"); assertThat(testFile.createNewFile()).isTrue(); Files.write(testFile.toPath(), "content".getBytes()); Git gitRepo = Git.open(appDir); // Execute a commit assertThat( execPost("/admin/applications/newApp/resources/git/commits", "{ \"msg\": \"my commit message\" }")) .hasStatus(201); assertThat(gitRepo.status().call().hasUncommittedChanges()).isFalse(); Iterator<RevCommit> iterator = gitRepo.log().all().call().iterator(); int commitSize = 0; RevCommit latestCommit = null; while (iterator.hasNext()) { RevCommit commit = iterator.next(); if (commitSize == 0) { latestCommit = commit; } commitSize++; } assertThat(commitSize).isEqualTo(2); assertThat(latestCommit.getFullMessage()).isEqualTo("my commit message"); TreeWalk treeWalk = new TreeWalk(gitRepo.getRepository()); treeWalk.addTree(latestCommit.getTree()); treeWalk.setFilter(PathFilter.create("test.txt")); assertThat(treeWalk.next()).isTrue(); String fileContent = new String(treeWalk.getObjectReader().open(treeWalk.getObjectId(0)).getBytes()); treeWalk.release(); assertThat(fileContent).isEqualTo("content"); // Test #3 - Post a commit, with auto add files to index off File anotherFile = new File(appDir, "another.txt"); assertThat(anotherFile.createNewFile()).isTrue(); Files.write(anotherFile.toPath(), "another content".getBytes()); Files.write(testFile.toPath(), "updated content".getBytes()); // Execute a commit assertThat(execPost("/admin/applications/newApp/resources/git/commits", "{ \"msg\": \"another commit\", \"include-untracked\": \"false\" }")).hasStatus(201); assertThat(gitRepo.status().call().isClean()).isFalse(); iterator = gitRepo.log().all().call().iterator(); commitSize = 0; while (iterator.hasNext()) { RevCommit commit = iterator.next(); if (commitSize == 0) { latestCommit = commit; } commitSize++; } assertThat(commitSize).isEqualTo(3); assertThat(latestCommit.getFullMessage()).isEqualTo("another commit"); treeWalk = new TreeWalk(gitRepo.getRepository()); treeWalk.addTree(latestCommit.getTree()); treeWalk.setFilter(PathFilter.create("another.txt")); assertThat(treeWalk.next()).isFalse(); treeWalk.release(); treeWalk = new TreeWalk(gitRepo.getRepository()); treeWalk.addTree(latestCommit.getTree()); treeWalk.setFilter(PathFilter.create("test.txt")); assertThat(treeWalk.next()).isTrue(); fileContent = new String(treeWalk.getObjectReader().open(treeWalk.getObjectId(0)).getBytes()); treeWalk.release(); assertThat(fileContent).isEqualTo("updated content"); // Test #4 - Verify PUT on commit is not supported assertThat(execPut("/admin/applications/newApp/resources/git/commits/" + latestCommit.getName(), "{ \"bad\": \"request\" }")).hasStatus(500).isInternalError(); }