List of usage examples for org.eclipse.jgit.revwalk RevCommit getCommitterIdent
public final PersonIdent getCommitterIdent()
From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java
License:Open Source License
private void processCommit(Repository repository, RevWalk walk, RevCommit rev, Map<String, ManagedFile> fileCache) throws SQLException, IOException { Identity author = resolveIdentity(rev.getAuthorIdent()); Identity committer = resolveIdentity(rev.getCommitterIdent()); Date date = new java.util.Date((long) rev.getCommitTime() * 1000); String message = rev.getFullMessage(); Map<String, FileStats> fileStats = new HashMap<String, FileStats>(); DiffOutputStream outputStream = new DiffOutputStream(); processDiff(repository, walk, rev, outputStream, fileStats); String revision = rev.getId().getName(); int totalLinesAdded = outputStream.getTotalLinesAdded(); int totalLinesRemoved = outputStream.getTotalLinesRemoved(); int fileCount = fileStats.size(); Commit commit = model.addCommit(revision, project, author, committer, date, message, fileCount, totalLinesAdded, totalLinesRemoved); for (Map.Entry<String, FileStats> item : fileStats.entrySet()) { if (stopped == true) { break; }/*from ww w. jav a 2 s. co m*/ FileStats stats = item.getValue(); String path = item.getKey(); switch (stats.type) { case COPY: // There is no active copy in git, // use ADD instead. /* ManagedFile originalFile = fileCache.get (stats.oldPath); assert (originalFile != null); ManagedFile copiedFile = model.addManagedFile (project, path); model.addFileChange (commit, copiedFile, stats.linesAdded, stats.linesRemoved, stats.emptyLinesAdded, stats.emptyLinesRemoved, stats.chunks); model.addIsCopy (copiedFile, commit, originalFile); fileCache.put (path, copiedFile); break; */ case ADD: ManagedFile addedFile = model.addManagedFile(project, path); model.addFileChange(commit, addedFile, stats.linesAdded, stats.linesRemoved, stats.emptyLinesAdded, stats.emptyLinesRemoved, stats.chunks); fileCache.put(path, addedFile); break; case DELETE: ManagedFile deletedFile = fileCache.get(path); // Merge handling if (deletedFile != null) { model.addFileDeletion(deletedFile, commit); fileCache.remove(stats.oldPath); } break; case MODIFY: ManagedFile modifiedFile = fileCache.get(path); assert (modifiedFile != null); model.addFileChange(commit, modifiedFile, stats.linesAdded, stats.linesRemoved, stats.emptyLinesAdded, stats.emptyLinesRemoved, stats.chunks); break; case RENAME: ManagedFile renamedFile = fileCache.get(stats.oldPath); // E.g. on merges after a rename. if (renamedFile != null) { model.addFileRename(renamedFile, commit, stats.oldPath, path); fileCache.put(path, renamedFile); } break; default: assert (false); } } emitTasksProcessed(1); }
From source file:boa.datagen.scm.GitConnector.java
License:Apache License
@Override protected void setRevisions() { try {// w w w .j a va2 s .c o m revwalk.reset(); revwalk.markStart(revwalk.parseCommit(repository.resolve(Constants.HEAD))); revwalk.sort(RevSort.TOPO, true); revwalk.sort(RevSort.COMMIT_TIME_DESC, true); revwalk.sort(RevSort.REVERSE, true); revisions.clear(); revisionMap = new HashMap<String, Integer>(); for (final RevCommit rc : revwalk) { final GitCommit gc = new GitCommit(repository, this); gc.setId(rc.getName()); gc.setAuthor(rc.getAuthorIdent().getName()); gc.setCommitter(rc.getCommitterIdent().getName()); gc.setDate(new Date(((long) rc.getCommitTime()) * 1000)); gc.setMessage(rc.getFullMessage()); gc.getChangeFiles(this.revisionMap, rc); revisionMap.put(gc.id, revisions.size()); revisions.add(gc); } } catch (final IOException e) { if (debug) System.err.println("Git Error getting parsing HEAD commit for " + path + ". " + e.getMessage()); } }
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
@Override public Commit getCommit(String id) { Git git = null;/*from w w w .j a v a 2 s .c o m*/ try { git = Git.open(new File(path)); Repository repo = git.getRepository(); Iterable<RevCommit> commits = git.log().add(repo.resolve(id)).call(); Commit theCommit = null; for (RevCommit jgitCommit : commits) { Developer author = new Developer(jgitCommit.getAuthorIdent().getName(), jgitCommit.getAuthorIdent().getEmailAddress()); Developer committer = new Developer(jgitCommit.getCommitterIdent().getName(), jgitCommit.getCommitterIdent().getEmailAddress()); String msg = jgitCommit.getFullMessage().trim(); String hash = jgitCommit.getName().toString(); long epoch = jgitCommit.getCommitTime(); String parent = (jgitCommit.getParentCount() > 0) ? jgitCommit.getParent(0).getName().toString() : ""; GregorianCalendar date = new GregorianCalendar(); date.setTime(new Date(epoch * 1000L)); theCommit = new Commit(hash, author, committer, date, msg, parent); List<DiffEntry> diffsForTheCommit = diffsForTheCommit(repo, jgitCommit); if (diffsForTheCommit.size() > MAX_NUMBER_OF_FILES_IN_A_COMMIT) { log.error("commit " + id + " has more than files than the limit"); throw new RuntimeException("commit " + id + " too big, sorry"); } for (DiffEntry diff : diffsForTheCommit) { ModificationType change = Enum.valueOf(ModificationType.class, diff.getChangeType().toString()); String oldPath = diff.getOldPath(); String newPath = diff.getNewPath(); String diffText = ""; String sc = ""; if (diff.getChangeType() != ChangeType.DELETE) { diffText = getDiffText(repo, diff); sc = getSourceCode(repo, diff); } if (diffText.length() > MAX_SIZE_OF_A_DIFF) { log.error("diff for " + newPath + " too big"); diffText = "-- TOO BIG --"; } theCommit.addModification(oldPath, newPath, change, diffText, sc); } break; } return theCommit; } catch (Exception e) { throw new RuntimeException("error detailing " + id + " in " + path, e); } finally { if (git != null) git.close(); } }
From source file:br.edu.ifpb.scm.api.git.Git.java
private LocalDate extractLocalDateFromCommit(RevCommit commit) { return commit.getCommitterIdent().getWhen().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); }
From source file:com.binarybirchtree.contributionart.RepositoryTest.java
License:Open Source License
@Test public void validate_commits() throws IOException, Matrix.FileFormatException, Repository.GitException, GitAPIException { final int factor = 20; final String name = "name"; final String email = "email"; /////from w w w. j a va 2 s . c om /// Encapsulates commit-validation logic. /// class CommitValidator { final ZonedDateTime timestamp; /// /// @param[in] commit Commit to validate. /// @param[in] timestamp Expected timestamp. /// @param[in] message Expected message. /// CommitValidator(RevCommit commit, ZonedDateTime timestamp, String message) { this.timestamp = timestamp; Assert.assertEquals(timestamp.toInstant(), Instant.ofEpochSecond(commit.getCommitTime())); Assert.assertEquals(message, commit.getFullMessage()); new IdentityValidator(commit.getAuthorIdent()); new IdentityValidator(commit.getCommitterIdent()); } /// /// Contains shared validation logic used for both Author and Committer identities. /// class IdentityValidator { private PersonIdent identity; /// /// @param[in] identity Identity to validate. /// public IdentityValidator(PersonIdent identity) { this.identity = identity; validate_name(); validate_email(); validate_timestamp(); } private void validate_name() { Assert.assertEquals(name, identity.getName()); } private void validate_email() { Assert.assertEquals(email, identity.getEmailAddress()); } private void validate_timestamp() { Assert.assertEquals(timestamp.toInstant(), identity.getWhen().toInstant()); } } } Path repo = folder.newFolder().toPath(); Matrix matrix = new Matrix(file); ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS); // Generate commits in a temporary repository. try (Repository repository = new Repository(repo, name, email)) { repository.illustrate(matrix, factor); } // Verify that the state of the repository is as expected. try (Git git = Git.open(repo.toFile())) { // Start from the earliest date for which commits were generated. ZonedDateTime current = today.with(WeekFields.SUNDAY_START.dayOfWeek(), DayOfWeek.values().length) .minusDays(Matrix.AREA); // Prepare to iterate through the definition matrix alongside the commit log, // as the values in the definition matrix affect how many commits should have been generated. Iterator<Matrix.Value> values = matrix.iterator(); Matrix.Value value; int cell_iterations = 0; int commit_count = 0; // Retrieve the list of commits, sorted from earliest to latest. List<RevCommit> commits = Lists.reverse(Lists.newArrayList(git.log().call())); Assert.assertFalse(commits.isEmpty()); // Validate the README commit. String readme = "README.md"; new CommitValidator(Iterables.getLast(commits), today, String.format("Added %s.", readme)); commits.remove(commits.size() - 1); Assert.assertEquals(Repository.README, new String(Files.readAllBytes(repo.resolve(readme)))); // Iterate through the commit log, starting from the earliest commit. for (RevCommit commit : commits) { if (cell_iterations == 0) { Assert.assertTrue(values.hasNext()); value = values.next(); cell_iterations = value.weight() * factor; current = current.plusDays(1); } new CommitValidator(commit, current, ""); ++commit_count; --cell_iterations; } // Determine the expected commit count and compare it with the actual commit count. int expected_commit_count = StreamSupport.stream(matrix.spliterator(), false).map(Matrix.Value::weight) .reduce(0, (accumulator, element) -> accumulator + element * factor); while (values.hasNext()) { expected_commit_count -= values.next().weight() * factor; } Assert.assertEquals(expected_commit_count, commit_count); } }
From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java
License:Apache License
/** * Does not fetch./*w ww . j ava 2 s . c o m*/ */ public CommitInfo getCommitInfo(String path) throws Exception { Iterator<RevCommit> revCommits = git.log().addPath(path).setMaxCount(1).call().iterator(); if (revCommits.hasNext()) { RevCommit revCommit = revCommits.next(); CommitInfo commitInfo = new CommitInfo(revCommit.getId().name()); PersonIdent committerIdent = revCommit.getCommitterIdent(); commitInfo.setCommitter(committerIdent.getName()); commitInfo.setEmail(committerIdent.getEmailAddress()); if ((commitInfo.getCommitter() == null || commitInfo.getCommitter().isEmpty()) && commitInfo.getEmail() != null) commitInfo.setCommitter(commitInfo.getEmail()); commitInfo.setDate(committerIdent.getWhen()); commitInfo.setMessage(revCommit.getShortMessage()); return commitInfo; } return null; }
From source file:com.gitblit.git.GitblitReceivePack.java
License:Apache License
/** * Instrumentation point where the incoming push event has been parsed, * validated, objects created BUT refs have not been updated. You might * use this to enforce a branch-write permissions model. *//*from w w w. j ava 2 s. c o m*/ @Override public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (commands.size() == 0) { // no receive commands to process // this can happen if receive pack subclasses intercept and filter // the commands LOGGER.debug("skipping pre-receive processing, no refs created, updated, or removed"); return; } if (repository.isMirror) { // repository is a mirror for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is a mirror!", repository.name); } return; } if (repository.isFrozen) { // repository is frozen/readonly for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name); } return; } if (!repository.isBare) { // repository has a working copy for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name); } return; } if (!canPush(commands)) { // user does not have push permissions for (ReceiveCommand cmd : commands) { sendRejection(cmd, "User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name); } return; } if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) { // enforce committer verification if (StringUtils.isEmpty(user.emailAddress)) { // reject the push because the pushing account does not have an email address for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Sorry, the account \"{0}\" does not have an email address set for committer verification!", user.username); } return; } // Optionally enforce that the committer of first parent chain // match the account being used to push the commits. // // This requires all merge commits are executed with the "--no-ff" // option to force a merge commit even if fast-forward is possible. // This ensures that the chain first parents has the commit // identity of the merging user. boolean allRejected = false; for (ReceiveCommand cmd : commands) { String firstParent = null; try { List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name()); for (RevCommit commit : commits) { if (firstParent != null) { if (!commit.getName().equals(firstParent)) { // ignore: commit is right-descendant of a merge continue; } } // update expected next commit id if (commit.getParentCount() == 0) { firstParent = null; } else { firstParent = commit.getParents()[0].getId().getName(); } PersonIdent committer = commit.getCommitterIdent(); if (!user.is(committer.getName(), committer.getEmailAddress())) { // verification failed String reason = MessageFormat.format( "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress); LOGGER.warn(reason); cmd.setResult(Result.REJECTED_OTHER_REASON, reason); allRejected &= true; break; } else { allRejected = false; } } } catch (Exception e) { LOGGER.error("Failed to verify commits were made by pushing user", e); } } if (allRejected) { // all ref updates rejected, abort return; } } for (ReceiveCommand cmd : commands) { String ref = cmd.getRefName(); if (ref.startsWith(Constants.R_HEADS)) { switch (cmd.getType()) { case UPDATE_NONFASTFORWARD: case DELETE: // reset branch commit cache on REWIND and DELETE CommitCache.instance().clear(repository.name, ref); break; default: break; } } else if (ref.equals(BranchTicketService.BRANCH)) { // ensure pushing user is an administrator OR an owner // i.e. prevent ticket tampering boolean permitted = user.canAdmin() || repository.isOwner(user.username); if (!permitted) { sendRejection(cmd, "{0} is not permitted to push to {1}", user.username, ref); } } else if (ref.startsWith(Constants.R_FOR)) { // prevent accidental push to refs/for sendRejection(cmd, "{0} is not configured to receive patchsets", repository.name); } } // call pre-receive plugins for (ReceiveHook hook : gitblit.getExtensions(ReceiveHook.class)) { try { hook.onPreReceive(this, commands); } catch (Exception e) { LOGGER.error("Failed to execute extension", e); } } Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(gitblit.getPreReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) { scripts.addAll(repository.preReceiveScripts); } runGroovy(commands, scripts); for (ReceiveCommand cmd : commands) { if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) { LOGGER.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(), cmd.getResult(), cmd.getMessage())); } } }
From source file:com.gitblit.git.ReceiveHook.java
License:Apache License
/** * Instrumentation point where the incoming push event has been parsed, * validated, objects created BUT refs have not been updated. You might * use this to enforce a branch-write permissions model. *//*from w w w . jav a2s. c om*/ @Override public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (repository.isFrozen) { // repository is frozen/readonly String reason = MessageFormat.format("Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (!repository.isBare) { // repository has a working copy String reason = MessageFormat.format( "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (!user.canPush(repository)) { // user does not have push permissions String reason = MessageFormat.format("User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) { // enforce committer verification if (StringUtils.isEmpty(user.emailAddress)) { // emit warning if user does not have an email address logger.warn(MessageFormat.format( "Consider setting an email address for {0} ({1}) to improve committer verification.", user.getDisplayName(), user.username)); } // Optionally enforce that the committer of the left parent chain // match the account being used to push the commits. // // This requires all merge commits are executed with the "--no-ff" // option to force a merge commit even if fast-forward is possible. // This ensures that the chain of left parents has the commit // identity of the merging user. boolean allRejected = false; for (ReceiveCommand cmd : commands) { String linearParent = null; try { List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name()); for (RevCommit commit : commits) { if (linearParent != null) { if (!commit.getName().equals(linearParent)) { // ignore: commit is right-descendant of a merge continue; } } // update expected next commit id if (commit.getParentCount() == 0) { linearParent = null; } else { linearParent = commit.getParents()[0].getId().getName(); } PersonIdent committer = commit.getCommitterIdent(); if (!user.is(committer.getName(), committer.getEmailAddress())) { String reason; if (StringUtils.isEmpty(user.emailAddress)) { // account does not have an email address reason = MessageFormat.format("{0} by {1} <{2}> was not committed by {3} ({4})", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username); } else { // account has an email address reason = MessageFormat.format( "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress); } logger.warn(reason); cmd.setResult(Result.REJECTED_OTHER_REASON, reason); allRejected &= true; break; } else { allRejected = false; } } } catch (Exception e) { logger.error("Failed to verify commits were made by pushing user", e); } } if (allRejected) { // all ref updates rejected, abort return; } } // reset branch commit cache on REWIND and DELETE for (ReceiveCommand cmd : commands) { String ref = cmd.getRefName(); if (ref.startsWith(Constants.R_HEADS)) { switch (cmd.getType()) { case UPDATE_NONFASTFORWARD: case DELETE: CommitCache.instance().clear(repository.name, ref); break; default: break; } } } Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(GitBlit.self().getPreReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) { scripts.addAll(repository.preReceiveScripts); } runGroovy(repository, user, commands, rp, scripts); for (ReceiveCommand cmd : commands) { if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) { logger.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(), cmd.getResult(), cmd.getMessage())); } } }
From source file:com.gitblit.LuceneExecutor.java
License:Apache License
/** * Returns the committer for the commit, if this information is available. * /*from ww w . j a v a2s . com*/ * @param commit * @return an committer or unknown */ private String getCommitter(RevCommit commit) { String name = "unknown"; try { name = commit.getCommitterIdent().getName(); if (StringUtils.isEmpty(name)) { name = commit.getCommitterIdent().getEmailAddress(); } } catch (NullPointerException n) { } return name; }
From source file:com.gitblit.plugin.flowdock.FlowDockReceiveHook.java
License:Apache License
@Override public void onPostReceive(GitblitReceivePack receivePack, Collection<ReceiveCommand> commands) { if (!shallPost(receivePack, commands)) { return;//from w ww . j a v a 2s . co m } IRuntimeManager runtimeManager = GitblitContext.getManager(IRuntimeManager.class); try { for (ReceiveCommand cmd : commands) { if (cmd.getRefName().startsWith(Constants.R_TAGS)) { boolean shallPostTag = runtimeManager.getSettings().getBoolean(Plugin.SETTING_POST_TAGS, true); if (!shallPostTag) { continue; } } else if (cmd.getRefName().startsWith(Constants.R_HEADS)) { boolean shallPostBranch = runtimeManager.getSettings().getBoolean(Plugin.SETTING_POST_BRANCHES, true); if (!shallPostBranch) { continue; } } else { // ignore other refs continue; } RepositoryModel repo = receivePack.getRepositoryModel(); String repoUrl = getUrl(repo.name, null, null); String diffUrl = getUrl(repo.name, cmd.getOldId().getName(), cmd.getNewId().getName()); GitPayload payload = new GitPayload().pusher(receivePack.getUserModel()).repository(repo.name) .repoUrl(repoUrl).tags(getTags(repo)).ref(cmd.getRefName()) .refName(Repository.shortenRefName(cmd.getRefName())).diffUrl(diffUrl) .before(cmd.getOldId().getName()).after(cmd.getNewId().getName()); List<RevCommit> commits = getCommits(receivePack, cmd.getOldId().name(), cmd.getNewId().name()); for (RevCommit commit : commits) { Commit c = new Commit(); c.id = commit.getName(); c.url = getUrl(repo.name, null, commit.getName()); c.message = commit.getFullMessage().trim(); PersonIdent author = commit.getAuthorIdent(); c.author = new Ident(author.getName(), author.getEmailAddress()); c.timestamp = author.getWhen(); if (c.timestamp == null) { c.timestamp = commit.getCommitterIdent().getWhen(); } List<PathChangeModel> paths = JGitUtils.getFilesInCommit(receivePack.getRepository(), commit); c.added = filter(paths, ChangeType.ADD); c.modified = filter(paths, ChangeType.MODIFY); c.removed = filter(paths, ChangeType.DELETE); payload.add(c); } flowdock.setFlow(repo, payload); flowdock.sendAsync(payload); } } catch (Exception e) { log.error("Failed to notify FlowDock!", e); } }