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

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

Introduction

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

Prototype

public final String getShortMessage() 

Source Link

Document

Parse the commit message and return the first "line" of it.

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();/*  w  w w .ja  v  a 2 s  .com*/
    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:br.edu.ifpb.scm.api.git.Git.java

/**
 * Cria um objeto verso/*from   ww  w. ja  va  2s . c  o m*/
 *
 * @param repo {@link org.eclipse.jgit.lib.Repository} JGit
 * @param it RevCommit JGit
 * @return {@link Version} Verso
 */
private Version createVersion(RevCommit it) throws IOException {
    List<ChangedFiles> listOfChangedFiles = getChangedFilesFromSpecifiedVersion(extractHashFromCommit(it));
    List<DiffEntry> listOfDiffs = Collections.EMPTY_LIST;
    boolean flag = false;
    if (it.getParentCount() <= 0) {
        flag = true;
        listOfDiffs = getDiff(extractHashFromCommit(it), flag);
    }
    listOfDiffs = getDiff(extractHashFromCommit(it), flag);
    return new Version(extractLocalDateFromCommit(it), extractHashFromCommit(it), it.getShortMessage(),
            listOfDiffs, createAuthor(it));

    //                .setChanges(listOfChangedFiles);
}

From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java

License:Apache License

@Override
public boolean hasChangedSince(final String modulePath, final List<String> childModules,
        final Collection<ProposedTag> tags) throws SCMException {
    final RevWalk walk = new RevWalk(getGit().getRepository());
    try {//from ww  w  . j  a v  a2  s  .co  m
        walk.setRetainBody(false);
        walk.markStart(walk.parseCommit(getGit().getRepository().findRef("HEAD").getObjectId()));
        filterOutOtherModulesChanges(modulePath, childModules, walk);
        stopWalkingWhenTheTagsAreHit(tags, walk);

        final Iterator<RevCommit> it = walk.iterator();
        boolean changed = it.hasNext();

        if (config.isIncrementSnapshotVersionAfterRelease() && changed) {
            final RevCommit commit = it.next();
            walk.parseBody(commit);
            changed = !SNAPSHOT_COMMIT_MESSAGE.equals(commit.getShortMessage()) || it.hasNext();
        }

        return changed;
    } catch (final IOException e) {
        throw new SCMException(e, "Diff detector could not determine whether module %s has been changed!",
                modulePath);
    } finally {
        walk.dispose();
    }
}

From source file:co.bledo.gitmin.servlet.Review.java

License:Apache License

public Response index(Request request) throws Exception {

    log.entry(request);/*  www.ja  v  a2s . c o  m*/

    DateFormat dformat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");

    List<Repo> repos = GitminStorage.getRepos();
    Map<String, List<GitListItem>> lists = new HashMap<String, List<GitListItem>>();
    for (Repo repo : repos) {
        Git git = Git.open(new File(GitminConfig.getGitRepositoriesPath() + "/" + repo.name));
        Iterable<RevCommit> commits = git.log().setMaxCount(20).call();
        List<GitListItem> list = new ArrayList<GitListItem>();
        for (RevCommit commit : commits) {
            log.debug(commit);
            GitListItem item = new GitListItem();
            item.email = commit.getAuthorIdent().getEmailAddress();
            item.name = commit.getAuthorIdent().getName();
            item.subject = commit.getShortMessage();
            item.gravatar = "http://www.gravatar.com/avatar/" + Util.md5(Util.trim(item.email).toLowerCase())
                    + "?s=40";
            item.hash = commit.getName();
            item.date = dformat.format(new Date(commit.getCommitTime()));
            list.add(item);
        }

        lists.put(repo.name, list);
    }

    VelocityResponse resp = VelocityResponse.newInstance(request, this);
    resp.assign("lists", lists);

    return log.exit(resp);
}

From source file:com.amd.gerrit.plugins.manifestsubscription.ManifestSubscription.java

License:Open Source License

@Override
public void onGitReferenceUpdated(Event event) {
    String projectName = event.getProjectName();
    String refName = event.getRefName();
    String branchName = refName.startsWith("refs/heads/") ? refName.substring(11) : "";
    ProjectBranchKey pbKey = new ProjectBranchKey(projectName, branchName);

    if (event.getNewObjectId().equals(ObjectId.zeroId().toString())) {
        // This happens when there's a branch deletion and possibly other events
        log.info("Project: " + projectName + "\nrefName: " + refName);
    } else if (REFS_CONFIG.equals(refName)) {
        // possible change in enabled repos
        processProjectConfigChange(event);
    } else if (enabledManifestSource.containsKey(projectName)
            && enabledManifestSource.get(projectName).getBranches().contains(branchName)) {
        processManifestChange(event, projectName, branchName);

    } else if (subscribedRepos.containsRow(pbKey)) {
        //updates in subscribed repos

        // Manifest store and branch
        Map<String, Map<String, Set<com.amd.gerrit.plugins.manifestsubscription.manifest.Project>>> destinations = subscribedRepos
                .row(pbKey);/*from  ww w  . j a  va 2 s  . c o  m*/

        for (String store : destinations.keySet()) {
            for (String storeBranch : destinations.get(store).keySet()) {
                Set<com.amd.gerrit.plugins.manifestsubscription.manifest.Project> ps = destinations.get(store)
                        .get(storeBranch);

                Manifest manifest = manifestStores.get(store, storeBranch);
                String manifestSrc = manifestSource.get(store, storeBranch);
                StringBuilder extraCommitMsg = new StringBuilder();

                Project.NameKey p = new Project.NameKey(projectName);
                try (Repository r = gitRepoManager.openRepository(p); RevWalk walk = new RevWalk(r)) {

                    RevCommit c = walk.parseCommit(ObjectId.fromString(event.getNewObjectId()));

                    extraCommitMsg.append(event.getNewObjectId().substring(0, 7));
                    extraCommitMsg.append(" ");
                    extraCommitMsg.append(projectName);
                    extraCommitMsg.append(" ");
                    extraCommitMsg.append(c.getShortMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // these are project from the above manifest previously
                // cached in the lookup table
                for (com.amd.gerrit.plugins.manifestsubscription.manifest.Project updateProject : ps) {
                    updateProject.setRevision(event.getNewObjectId());
                }

                try {
                    Utilities.updateManifest(gitRepoManager, metaDataUpdateFactory, changeHooks, store,
                            STORE_BRANCH_PREFIX + storeBranch, manifest, manifestSrc, extraCommitMsg.toString(),
                            null);
                } catch (JAXBException | IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

/**
 * Does not fetch.//from www  .j  a v  a  2s  .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.build.BuildGhPages.java

License:Apache License

public static void main(String[] args) {
    Params params = new Params();
    JCommander jc = new JCommander(params);
    try {//from  ww  w  .  j  ava  2  s .  c  om
        jc.parse(args);
    } catch (ParameterException t) {
        System.err.println(t.getMessage());
        jc.usage();
    }

    File source = new File(params.sourceFolder);
    String ghpages = "refs/heads/gh-pages";
    try {
        File gitDir = FileKey.resolve(new File(params.repositoryFolder), FS.DETECTED);
        Repository repository = new FileRepository(gitDir);

        RefModel issuesBranch = JGitUtils.getPagesBranch(repository);
        if (issuesBranch == null) {
            JGitUtils.createOrphanBranch(repository, "gh-pages", null);
        }

        System.out.println("Updating gh-pages branch...");
        ObjectId headId = repository.resolve(ghpages + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue.
            DirCache index = createIndex(repository, headId, source, params.obliterate);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent author = new PersonIdent("Gitblit", "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage("updated pages");
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(ghpages);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            ghpages, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
        System.out.println("gh-pages updated.");
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.gitblit.git.PatchsetCommand.java

License:Apache License

private String getTitle(RevCommit commit) {
    String title = commit.getShortMessage();
    return title;
}

From source file:com.gitblit.git.PatchsetCommand.java

License:Apache License

/**
 * Returns the body of the commit message
 *
 * @return/* w w w.j a v  a  2  s.  c  om*/
 */
private String getBody(RevCommit commit) {
    String body = commit.getFullMessage().substring(commit.getShortMessage().length()).trim();
    return body;
}

From source file:com.gitblit.git.PatchsetReceivePack.java

License:Apache License

/**
 * Prepares a patchset command.//ww  w .  j a  v  a 2  s  .co m
 *
 * @param cmd
 * @return the patchset command
 */
private PatchsetCommand preparePatchset(ReceiveCommand cmd) {
    String branch = getIntegrationBranch(cmd.getRefName());
    long number = getTicketId(cmd.getRefName());

    TicketModel ticket = null;
    if (number > 0 && ticketService.hasTicket(repository, number)) {
        ticket = ticketService.getTicket(repository, number);
    }

    if (ticket == null) {
        if (number > 0) {
            // requested ticket does not exist
            sendError("Sorry, {0} does not have ticket {1,number,0}!", repository.name, number);
            sendRejection(cmd, "Invalid ticket number");
            return null;
        }
    } else {
        if (ticket.isMerged()) {
            // ticket already merged & resolved
            Change mergeChange = null;
            for (Change change : ticket.changes) {
                if (change.isMerge()) {
                    mergeChange = change;
                    break;
                }
            }
            if (mergeChange != null) {
                sendError("Sorry, {0} already merged {1} from ticket {2,number,0} to {3}!", mergeChange.author,
                        mergeChange.patchset, number, ticket.mergeTo);
            }
            sendRejection(cmd, "Ticket {0,number,0} already resolved", number);
            return null;
        } else if (!StringUtils.isEmpty(ticket.mergeTo)) {
            // ticket specifies integration branch
            branch = ticket.mergeTo;
        }
    }

    final int shortCommitIdLen = settings.getInteger(Keys.web.shortCommitIdLength, 6);
    final String shortTipId = cmd.getNewId().getName().substring(0, shortCommitIdLen);
    final RevCommit tipCommit = JGitUtils.getCommit(getRepository(), cmd.getNewId().getName());
    final String forBranch = branch;
    RevCommit mergeBase = null;
    Ref forBranchRef = getAdvertisedRefs().get(Constants.R_HEADS + forBranch);
    if (forBranchRef == null || forBranchRef.getObjectId() == null) {
        // unknown integration branch
        sendError("Sorry, there is no integration branch named ''{0}''.", forBranch);
        sendRejection(cmd, "Invalid integration branch specified");
        return null;
    } else {
        // determine the merge base for the patchset on the integration branch
        String base = JGitUtils.getMergeBase(getRepository(), forBranchRef.getObjectId(), tipCommit.getId());
        if (StringUtils.isEmpty(base)) {
            sendError("");
            sendError("There is no common ancestry between {0} and {1}.", forBranch, shortTipId);
            sendError("Please reconsider your proposed integration branch, {0}.", forBranch);
            sendError("");
            sendRejection(cmd, "no merge base for patchset and {0}", forBranch);
            return null;
        }
        mergeBase = JGitUtils.getCommit(getRepository(), base);
    }

    // ensure that the patchset can be cleanly merged right now
    MergeStatus status = JGitUtils.canMerge(getRepository(), tipCommit.getName(), forBranch,
            repository.mergeType);
    switch (status) {
    case ALREADY_MERGED:
        sendError("");
        sendError("You have already merged this patchset.", forBranch);
        sendError("");
        sendRejection(cmd, "everything up-to-date");
        return null;
    case MERGEABLE:
        break;
    default:
        if (ticket == null || requireMergeablePatchset) {
            sendError("");
            sendError("Your patchset can not be cleanly merged into {0}.", forBranch);
            sendError("Please rebase your patchset and push again.");
            sendError("NOTE:", number);
            sendError("You should push your rebase to refs/for/{0,number,0}", number);
            sendError("");
            sendError("  git push origin HEAD:refs/for/{0,number,0}", number);
            sendError("");
            sendRejection(cmd, "patchset not mergeable");
            return null;
        }
    }

    // check to see if this commit is already linked to a ticket
    if (ticket != null
            && JGitUtils.getTicketNumberFromCommitBranch(getRepository(), tipCommit) == ticket.number) {
        sendError("{0} has already been pushed to ticket {1,number,0}.", shortTipId, ticket.number);
        sendRejection(cmd, "everything up-to-date");
        return null;
    }

    List<TicketLink> ticketLinks = JGitUtils.identifyTicketsFromCommitMessage(getRepository(), settings,
            tipCommit);

    PatchsetCommand psCmd;
    if (ticket == null) {
        /*
         *  NEW TICKET
         */
        Patchset patchset = newPatchset(null, mergeBase.getName(), tipCommit.getName());

        int minLength = 10;
        int maxLength = 100;
        String minTitle = MessageFormat.format("  minimum length of a title is {0} characters.", minLength);
        String maxTitle = MessageFormat.format("  maximum length of a title is {0} characters.", maxLength);

        if (patchset.commits > 1) {
            sendError("");
            sendError("You may not create a ''{0}'' branch proposal ticket from {1} commits!", forBranch,
                    patchset.commits);
            sendError("");
            // display an ellipsized log of the commits being pushed
            RevWalk walk = getRevWalk();
            walk.reset();
            walk.sort(RevSort.TOPO);
            int boundary = 3;
            int count = 0;
            try {
                walk.markStart(tipCommit);
                walk.markUninteresting(mergeBase);

                for (;;) {

                    RevCommit c = walk.next();
                    if (c == null) {
                        break;
                    }

                    if (count < boundary || count >= (patchset.commits - boundary)) {

                        walk.parseBody(c);
                        sendError("   {0}  {1}", c.getName().substring(0, shortCommitIdLen),
                                StringUtils.trimString(c.getShortMessage(), 60));

                    } else if (count == boundary) {

                        sendError("   ... more commits ...");

                    }

                    count++;
                }

            } catch (IOException e) {
                // Should never happen, the core receive process would have
                // identified the missing object earlier before we got control.
                LOGGER.error("failed to get commit count", e);
            } finally {
                walk.close();
            }

            sendError("");
            sendError("Possible Solutions:");
            sendError("");
            int solution = 1;
            String forSpec = cmd.getRefName().substring(Constants.R_FOR.length());
            if (forSpec.equals("default") || forSpec.equals("new")) {
                try {
                    // determine other possible integration targets
                    List<String> bases = Lists.newArrayList();
                    for (Ref ref : getRepository().getRefDatabase().getRefs(Constants.R_HEADS).values()) {
                        if (!ref.getName().startsWith(Constants.R_TICKET)
                                && !ref.getName().equals(forBranchRef.getName())) {
                            if (JGitUtils.isMergedInto(getRepository(), ref.getObjectId(), tipCommit)) {
                                bases.add(Repository.shortenRefName(ref.getName()));
                            }
                        }
                    }

                    if (!bases.isEmpty()) {

                        if (bases.size() == 1) {
                            // suggest possible integration targets
                            String base = bases.get(0);
                            sendError("{0}. Propose this change for the ''{1}'' branch.", solution++, base);
                            sendError("");
                            sendError("   git push origin HEAD:refs/for/{0}", base);
                            sendError("   pt propose {0}", base);
                            sendError("");
                        } else {
                            // suggest possible integration targets
                            sendError("{0}. Propose this change for a different branch.", solution++);
                            sendError("");
                            for (String base : bases) {
                                sendError("   git push origin HEAD:refs/for/{0}", base);
                                sendError("   pt propose {0}", base);
                                sendError("");
                            }
                        }

                    }
                } catch (IOException e) {
                    LOGGER.error(null, e);
                }
            }
            sendError("{0}. Squash your changes into a single commit with a meaningful message.", solution++);
            sendError("");
            sendError("{0}. Open a ticket for your changes and then push your {1} commits to the ticket.",
                    solution++, patchset.commits);
            sendError("");
            sendError("   git push origin HEAD:refs/for/{id}");
            sendError("   pt propose {id}");
            sendError("");
            sendRejection(cmd, "too many commits");
            return null;
        }

        // require a reasonable title/subject
        String title = tipCommit.getFullMessage().trim().split("\n")[0];
        if (title.length() < minLength) {
            // reject, title too short
            sendError("");
            sendError("Please supply a longer title in your commit message!");
            sendError("");
            sendError(minTitle);
            sendError(maxTitle);
            sendError("");
            sendRejection(cmd, "ticket title is too short [{0}/{1}]", title.length(), maxLength);
            return null;
        }
        if (title.length() > maxLength) {
            // reject, title too long
            sendError("");
            sendError("Please supply a more concise title in your commit message!");
            sendError("");
            sendError(minTitle);
            sendError(maxTitle);
            sendError("");
            sendRejection(cmd, "ticket title is too long [{0}/{1}]", title.length(), maxLength);
            return null;
        }

        // assign new id
        long ticketId = ticketService.assignNewId(repository);

        // create the patchset command
        psCmd = new PatchsetCommand(user.username, patchset);
        psCmd.newTicket(tipCommit, forBranch, ticketId, cmd.getRefName());
    } else {
        /*
         *  EXISTING TICKET
         */
        Patchset patchset = newPatchset(ticket, mergeBase.getName(), tipCommit.getName());
        psCmd = new PatchsetCommand(user.username, patchset);
        psCmd.updateTicket(tipCommit, forBranch, ticket, cmd.getRefName());
    }

    // confirm user can push the patchset
    boolean pushPermitted = ticket == null || !ticket.hasPatchsets() || ticket.isAuthor(user.username)
            || ticket.isPatchsetAuthor(user.username) || ticket.isResponsible(user.username)
            || user.canPush(repository);

    switch (psCmd.getPatchsetType()) {
    case Proposal:
        // proposals (first patchset) are always acceptable
        break;
    case FastForward:
        // patchset updates must be permitted
        if (!pushPermitted) {
            // reject
            sendError("");
            sendError("To push a patchset to this ticket one of the following must be true:");
            sendError("  1. you created the ticket");
            sendError("  2. you created the first patchset");
            sendError("  3. you are specified as responsible for the ticket");
            sendError("  4. you have push (RW) permissions to {0}", repository.name);
            sendError("");
            sendRejection(cmd, "not permitted to push to ticket {0,number,0}", ticket.number);
            return null;
        }
        break;
    default:
        // non-fast-forward push
        if (!pushPermitted) {
            // reject
            sendRejection(cmd, "non-fast-forward ({0})", psCmd.getPatchsetType());
            return null;
        }
        break;
    }

    Change change = psCmd.getChange();
    change.pendingLinks = ticketLinks;

    return psCmd;
}