Example usage for org.eclipse.jgit.revwalk RevCommit getFullMessage

List of usage examples for org.eclipse.jgit.revwalk RevCommit getFullMessage

Introduction

In this page you can find the example usage for org.eclipse.jgit.revwalk RevCommit getFullMessage.

Prototype

public final String getFullMessage() 

Source Link

Document

Parse the complete commit message and decode it to a string.

Usage

From source file:Node.java

License:Open Source License

public static Node createNode(RevWalk walk, ObjectId id, boolean recur) throws IOException {
    String key = id.getName();/*from   w  ww.ja v  a 2s  .c om*/
    RevCommit commit;
    Node node;

    if (nodeMap.containsKey(key)) {
        // commit node was already mapped
        node = nodeMap.get(key);
    } else {
        // create new commit node
        commit = walk.parseCommit(id);
        node = new Node(key, commit.getAuthorIdent().getEmailAddress(), commit.getCommitTime(),
                commit.getFullMessage(), commit.getShortMessage());
        node.setBackground(new Color(240, 240, 255));
        node.setForeground(new Color(0, 0, 127));

        if (recur) {
            // add parent nodes
            for (ObjectId parentCommit : commit.getParents())
                node.addParent(Node.createNode(walk, parentCommit, recur));
        }
    }

    return node;
}

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;
        }/*w  w  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:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

@SuppressWarnings("restriction")
@Override/*from www.  java  2  s. co m*/
public List<IReviewDescriptor> getReviews(URI uri) throws InvalidReviewRepositoryException {

    List<IReviewDescriptor> changeIds = new LinkedList<>();

    try {
        // connect to the local git repository
        Git git = Git.open(new File(uri));

        try {
            // Assume that origin refers to the remote gerrit repository
            // list all remote refs from origin
            Collection<Ref> remoteRefs = git.lsRemote().setTimeout(60).call();

            Pattern changeRefPattern = Pattern.compile(CHANGE_REF_PATTERN);

            // search for change refs
            for (Ref ref : remoteRefs) {

                Matcher matcher = changeRefPattern.matcher(ref.getName());
                if (matcher.matches()) {
                    String changePk = matcher.group(CHANGE_REF_PATTERN_GROUP_CHANGE_PK);
                    String changeId = "<unknown>";
                    GerritReviewDescriptor reviewDescriptor;
                    try {
                        reviewDescriptor = new GerritReviewDescriptor(Integer.parseInt(changePk), changeId);
                    } catch (NumberFormatException nfe) {
                        // FIXME ignore it or throw an exception?
                        break;
                    }

                    if (!changeIds.contains(reviewDescriptor)) {
                        changeIds.add(reviewDescriptor);

                        /*
                         * the change id is present in all commit messages,
                         * so we extract it from the commit message of the
                         * current ref
                         */
                        FetchResult fetchResult = git.fetch().setRefSpecs(new RefSpec(ref.getName())).call();

                        Ref localRef = fetchResult.getAdvertisedRef(ref.getName());
                        RevWalk revWalk = new RevWalk(git.getRepository());
                        RevCommit commit = revWalk.parseCommit(localRef.getObjectId());
                        String[] paragraphs = commit.getFullMessage().split("\n");
                        String lastParagraph = paragraphs[paragraphs.length - 1];
                        Pattern pattern = Pattern.compile(".*Change-Id: (I[^ \n]*).*");
                        Matcher changeIdMatcher = pattern.matcher(lastParagraph);

                        if (changeIdMatcher.matches()) {
                            changeId = changeIdMatcher.group(1);
                            reviewDescriptor.setChangeId(changeId);
                            ;
                        } else {
                            logger.warn(MessageFormat.format(
                                    "Could not find the change id for Gerrit change with primary key {0}",
                                    changePk));
                        }
                        revWalk.close();
                    }
                }
            }

        } catch (GitAPIException e) {
            throw new RepositoryIOException("Error during loading all remote changes", e);
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    }
    return changeIds;
}

From source file:at.nonblocking.maven.nonsnapshot.impl.ScmHandlerGitImpl.java

License:Apache License

@Override
public boolean checkChangesSinceDate(final File moduleDirectory, final Date date) {
    if (this.git == null) {
        return false;
    }/*from  w  w  w .j  a v  a2s . c  o  m*/

    try {
        String modulePath = PathUtil.relativePath(this.baseDir, moduleDirectory);

        LogCommand logCommand = this.git.log().setMaxCount(100);

        if (!modulePath.isEmpty()) {
            logCommand.addPath(modulePath);
        }

        for (RevCommit commit : logCommand.call()) {
            Date commitTime = new Date(commit.getCommitTime() * 1000L);
            if (commitTime.after(date)) {
                if (!commit.getFullMessage().startsWith(NONSNAPSHOT_COMMIT_MESSAGE_PREFIX)) {
                    LOG.debug("Module folder {}: Change since last commit: rev{} @ {} ({})",
                            new Object[] { moduleDirectory.getAbsolutePath(), commit.getId(), commitTime,
                                    commit.getFullMessage() });
                    return true;
                }
            } else {
                break;
            }
        }

    } catch (Exception e) {
        LOG.warn("Failed to check changes for path: {}" + moduleDirectory.getAbsolutePath(), e);
        return true;
    }

    return false;
}

From source file:boa.datagen.scm.GitConnector.java

License:Apache License

@Override
protected void setRevisions() {
    try {/* w  ww . ja v a2  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;/* w w  w .j  av a  2s . 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.gov.servicos.editor.conteudo.RepositorioGitTest.java

private void garanteQueAlteracaoFoiPara(File localRepo, String branch) throws IOException {
    try (Git git = Git.open(localRepo)) {
        Ref foo = git.getRepository().getRef(branch);
        assertThat(foo, is(notNullValue()));

        RevCommit commit = new RevWalk(git.getRepository()).parseCommit(foo.getObjectId());
        assertThat(commit.getAuthorIdent().getName(), is("fulano"));
        assertThat(commit.getAuthorIdent().getEmailAddress(), is("servicos@planejamento.gov.br"));
        assertThat(commit.getFullMessage(), is("Alterao de teste"));
    }//w ww. j  a va2 s .c  o  m
}

From source file:com.addthis.hydra.job.store.JobStoreGit.java

License:Apache License

/**
 * Get a JSON representation of the log of changes to a file
 *
 * @param jobId The jobId to fetch the log for
 * @return A log of the form [{commit:commitid, time:time, msg:commitmessage}, ...]
 * @throws GitAPIException If there is a problem fetching the log
 * @throws JSONException   If there is a problem generating the JSON
 *//*from w ww .  j ava 2  s . c  om*/
public JSONArray getGitLog(String jobId) throws Exception {
    JSONArray rv = new JSONArray();
    for (RevCommit commit : git.log().addPath(getPathForJobId(jobId)).call()) {
        JSONObject commitJson = new JSONObject().put("commit", commit.getName())
                .put("time", 1000L * (commit.getCommitTime())).put("msg", commit.getFullMessage());
        rv.put(commitJson);
    }
    return rv;
}

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";

    ///// w  w w .  ja  va  2s  .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.buildautomation.jgit.api.CreateListApplyAndDropStash.java

License:Apache License

public static void createListApplyAndDropStash() throws IOException, GitAPIException {
    // prepare a new test-repository
    try (Repository repository = CookbookHelper.createNewRepository()) {
        try (Git git = new Git(repository)) {
            // create a file
            File file1 = new File(repository.getDirectory().getParent(), "testfile");
            FileUtils.writeStringToFile(file1, "some text");
            File file2 = new File(repository.getDirectory().getParent(), "testfile2");
            FileUtils.writeStringToFile(file2, "some text");

            // add and commit the file
            git.add().addFilepattern("testfile").call();
            git.add().addFilepattern("testfile2").call();
            git.commit().setMessage("Added testfiles").call();

            // then modify the file
            FileUtils.writeStringToFile(file1, "some more text", true);

            // push the changes to a new stash
            RevCommit stash = git.stashCreate().call();

            System.out.println("Created stash " + stash);

            // then modify the 2nd file
            FileUtils.writeStringToFile(file2, "some more text", true);

            // push the changes to a new stash
            stash = git.stashCreate().call();

            System.out.println("Created stash " + stash);

            // list the stashes
            Collection<RevCommit> stashes = git.stashList().call();
            for (RevCommit rev : stashes) {
                System.out.println("Found stash: " + rev + ": " + rev.getFullMessage());
            }//from w  w w  .ja v  a 2  s  . c o  m

            // drop the 1st stash without applying it
            ObjectId call = git.stashDrop().setStashRef(0).call();
            System.out.println("StashDrop returned: " + call);

            ObjectId applied = git.stashApply().setStashRef(stash.getName()).call();
            System.out.println("Applied 2nd stash as: " + applied);
        }
    }
}