Example usage for org.eclipse.jgit.revwalk RevWalk parseBody

List of usage examples for org.eclipse.jgit.revwalk RevWalk parseBody

Introduction

In this page you can find the example usage for org.eclipse.jgit.revwalk RevWalk parseBody.

Prototype

public void parseBody(RevObject obj) throws MissingObjectException, IOException 

Source Link

Document

Ensure the object's full body content is available.

Usage

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 w  w w. j a v  a  2 s . c om
        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:com.gitblit.git.GitblitReceivePack.java

License:Apache License

/**
 * Automatically closes open tickets and adds references to tickets if made in the commit message.
 *
 * @param cmd//  ww w  .  j a  va2 s.  c  om
 */
private Collection<TicketModel> processReferencedTickets(ReceiveCommand cmd) {
    Map<Long, TicketModel> changedTickets = new LinkedHashMap<Long, TicketModel>();

    final RevWalk rw = getRevWalk();
    try {
        rw.reset();
        rw.markStart(rw.parseCommit(cmd.getNewId()));
        if (!ObjectId.zeroId().equals(cmd.getOldId())) {
            rw.markUninteresting(rw.parseCommit(cmd.getOldId()));
        }

        RevCommit c;
        while ((c = rw.next()) != null) {
            rw.parseBody(c);
            List<TicketLink> ticketLinks = JGitUtils.identifyTicketsFromCommitMessage(getRepository(), settings,
                    c);
            if (ticketLinks == null) {
                continue;
            }

            for (TicketLink link : ticketLinks) {

                TicketModel ticket = ticketService.getTicket(repository, link.targetTicketId);
                if (ticket == null) {
                    continue;
                }

                Change change = null;
                String commitSha = c.getName();
                String branchName = Repository.shortenRefName(cmd.getRefName());

                switch (link.action) {
                case Commit: {
                    //A commit can reference a ticket in any branch even if the ticket is closed.
                    //This allows developers to identify and communicate related issues
                    change = new Change(user.username);
                    change.referenceCommit(commitSha);
                }
                    break;

                case Close: {
                    // As this isn't a patchset theres no merging taking place when closing a ticket
                    if (ticket.isClosed()) {
                        continue;
                    }

                    change = new Change(user.username);
                    change.setField(Field.status, Status.Fixed);

                    if (StringUtils.isEmpty(ticket.responsible)) {
                        // unassigned tickets are assigned to the closer
                        change.setField(Field.responsible, user.username);
                    }
                }

                default: {
                    //No action
                }
                    break;
                }

                if (change != null) {
                    ticket = ticketService.updateTicket(repository, ticket.number, change);
                }

                if (ticket != null) {
                    sendInfo("");
                    sendHeader("#{0,number,0}: {1}", ticket.number,
                            StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG));

                    switch (link.action) {
                    case Commit: {
                        sendInfo("referenced by push of {0} to {1}", commitSha, branchName);
                        changedTickets.put(ticket.number, ticket);
                    }
                        break;

                    case Close: {
                        sendInfo("closed by push of {0} to {1}", commitSha, branchName);
                        changedTickets.put(ticket.number, ticket);
                    }
                        break;

                    default: {
                    }
                    }

                    sendInfo(ticketService.getTicketUrl(ticket));
                    sendInfo("");
                } else {
                    switch (link.action) {
                    case Commit: {
                        sendError("FAILED to reference ticket {0} by push of {1}", link.targetTicketId,
                                commitSha);
                    }
                        break;

                    case Close: {
                        sendError("FAILED to close ticket {0} by push of {1}", link.targetTicketId, commitSha);
                    }
                        break;

                    default: {
                    }
                    }
                }
            }
        }

    } catch (IOException e) {
        LOGGER.error("Can't scan for changes to reference or close", e);
    } finally {
        rw.reset();
    }

    return changedTickets.values();
}

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

License:Apache License

/**
 * Prepares a patchset command./*from  w  w w  . j a v a 2s.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;
}

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

License:Apache License

/**
 * Automatically closes open tickets that have been merged to their integration
 * branch by a client and adds references to tickets if made in the commit message.
 *
 * @param cmd//from ww  w .  ja v a 2  s.  c  om
 */
private Collection<TicketModel> processReferencedTickets(ReceiveCommand cmd) {
    Map<Long, TicketModel> mergedTickets = new LinkedHashMap<Long, TicketModel>();
    final RevWalk rw = getRevWalk();
    try {
        rw.reset();
        rw.markStart(rw.parseCommit(cmd.getNewId()));
        if (!ObjectId.zeroId().equals(cmd.getOldId())) {
            rw.markUninteresting(rw.parseCommit(cmd.getOldId()));
        }

        RevCommit c;
        while ((c = rw.next()) != null) {
            rw.parseBody(c);
            List<TicketLink> ticketLinks = JGitUtils.identifyTicketsFromCommitMessage(getRepository(), settings,
                    c);
            if (ticketLinks == null) {
                continue;
            }

            for (TicketLink link : ticketLinks) {

                if (mergedTickets.containsKey(link.targetTicketId)) {
                    continue;
                }

                TicketModel ticket = ticketService.getTicket(repository, link.targetTicketId);
                if (ticket == null) {
                    continue;
                }
                String integrationBranch;
                if (StringUtils.isEmpty(ticket.mergeTo)) {
                    // unspecified integration branch
                    integrationBranch = null;
                } else {
                    // specified integration branch
                    integrationBranch = Constants.R_HEADS + ticket.mergeTo;
                }

                Change change;
                Patchset patchset = null;
                String mergeSha = c.getName();
                String mergeTo = Repository.shortenRefName(cmd.getRefName());

                if (link.action == TicketAction.Commit) {
                    //A commit can reference a ticket in any branch even if the ticket is closed.
                    //This allows developers to identify and communicate related issues
                    change = new Change(user.username);
                    change.referenceCommit(mergeSha);
                } else {
                    // ticket must be open and, if specified, the ref must match the integration branch
                    if (ticket.isClosed()
                            || (integrationBranch != null && !integrationBranch.equals(cmd.getRefName()))) {
                        continue;
                    }

                    String baseRef = PatchsetCommand.getBasePatchsetBranch(ticket.number);
                    boolean knownPatchset = false;
                    Set<Ref> refs = getRepository().getAllRefsByPeeledObjectId().get(c.getId());
                    if (refs != null) {
                        for (Ref ref : refs) {
                            if (ref.getName().startsWith(baseRef)) {
                                knownPatchset = true;
                                break;
                            }
                        }
                    }

                    if (knownPatchset) {
                        // identify merged patchset by the patchset tip
                        for (Patchset ps : ticket.getPatchsets()) {
                            if (ps.tip.equals(mergeSha)) {
                                patchset = ps;
                                break;
                            }
                        }

                        if (patchset == null) {
                            // should not happen - unless ticket has been hacked
                            sendError("Failed to find the patchset for {0} in ticket {1,number,0}?!", mergeSha,
                                    ticket.number);
                            continue;
                        }

                        // create a new change
                        change = new Change(user.username);
                    } else {
                        // new patchset pushed by user
                        String base = cmd.getOldId().getName();
                        patchset = newPatchset(ticket, base, mergeSha);
                        PatchsetCommand psCmd = new PatchsetCommand(user.username, patchset);
                        psCmd.updateTicket(c, mergeTo, ticket, null);

                        // create a ticket patchset ref
                        updateRef(psCmd.getPatchsetBranch(), c.getId(), patchset.type);
                        RefUpdate ru = updateRef(psCmd.getTicketBranch(), c.getId(), patchset.type);
                        updateReflog(ru);

                        // create a change from the patchset command
                        change = psCmd.getChange();
                    }

                    // set the common change data about the merge
                    change.setField(Field.status, Status.Merged);
                    change.setField(Field.mergeSha, mergeSha);
                    change.setField(Field.mergeTo, mergeTo);

                    if (StringUtils.isEmpty(ticket.responsible)) {
                        // unassigned tickets are assigned to the closer
                        change.setField(Field.responsible, user.username);
                    }
                }

                ticket = ticketService.updateTicket(repository, ticket.number, change);

                if (ticket != null) {
                    sendInfo("");
                    sendHeader("#{0,number,0}: {1}", ticket.number,
                            StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG));

                    switch (link.action) {
                    case Commit: {
                        sendInfo("referenced by push of {0} to {1}", c.getName(), mergeTo);
                    }
                        break;

                    case Close: {
                        sendInfo("closed by push of {0} to {1}", patchset, mergeTo);
                        mergedTickets.put(ticket.number, ticket);
                    }
                        break;

                    default: {

                    }
                    }

                    sendInfo(ticketService.getTicketUrl(ticket));
                    sendInfo("");

                } else {
                    String shortid = mergeSha.substring(0,
                            settings.getInteger(Keys.web.shortCommitIdLength, 6));

                    switch (link.action) {
                    case Commit: {
                        sendError("FAILED to reference ticket {0,number,0} by push of {1}", link.targetTicketId,
                                shortid);
                    }
                        break;
                    case Close: {
                        sendError("FAILED to close ticket {0,number,0} by push of {1}", link.targetTicketId,
                                shortid);
                    }
                        break;

                    default: {

                    }
                    }
                }
            }
        }

    } catch (IOException e) {
        LOGGER.error("Can't scan for changes to reference or close", e);
    } finally {
        rw.reset();
    }

    return mergedTickets.values();
}

From source file:com.google.gerrit.acceptance.git.AbstractSubmoduleSubscription.java

License:Apache License

protected void expectToHaveSubmoduleState(TestRepository<?> repo, String branch, String submodule,
        ObjectId expectedId) throws Exception {

    submodule = name(submodule);/*from  w ww .  j ava 2  s . c  o  m*/
    ObjectId commitId = repo.git().fetch().setRemote("origin").call().getAdvertisedRef("refs/heads/" + branch)
            .getObjectId();

    RevWalk rw = repo.getRevWalk();
    RevCommit c = rw.parseCommit(commitId);
    rw.parseBody(c.getTree());

    RevTree tree = c.getTree();
    RevObject actualId = repo.get(tree, submodule);

    assertThat(actualId).isEqualTo(expectedId);
}

From source file:com.google.gerrit.acceptance.git.SubmoduleSubscriptionsIT.java

License:Apache License

private boolean hasSubmodule(TestRepository<?> repo, String branch, String submodule) throws Exception {

    ObjectId commitId = repo.git().fetch().setRemote("origin").call().getAdvertisedRef("refs/heads/" + branch)
            .getObjectId();/*  w w w  .  ja v  a2  s . c  o  m*/

    RevWalk rw = repo.getRevWalk();
    RevCommit c = rw.parseCommit(commitId);
    rw.parseBody(c.getTree());

    RevTree tree = c.getTree();
    try {
        repo.get(tree, submodule);
        return true;
    } catch (AssertionError e) {
        return false;
    }
}

From source file:com.google.gerrit.server.change.ChangeJson.java

License:Apache License

CommitInfo toCommit(ChangeControl ctl, RevWalk rw, RevCommit commit, boolean addLinks) throws IOException {
    Project.NameKey project = ctl.getChange().getProject();
    CommitInfo info = new CommitInfo();
    info.parents = new ArrayList<>(commit.getParentCount());
    info.author = toGitPerson(commit.getAuthorIdent());
    info.committer = toGitPerson(commit.getCommitterIdent());
    info.subject = commit.getShortMessage();
    info.message = commit.getFullMessage();

    if (addLinks) {
        FluentIterable<WebLinkInfo> links = webLinks.getPatchSetLinks(project, commit.name());
        info.webLinks = links.isEmpty() ? null : links.toList();
    }//from w w w  . java  2 s .  c  om

    for (RevCommit parent : commit.getParents()) {
        rw.parseBody(parent);
        CommitInfo i = new CommitInfo();
        i.commit = parent.name();
        i.subject = parent.getShortMessage();
        if (addLinks) {
            FluentIterable<WebLinkInfo> parentLinks = webLinks.getPatchSetLinks(project, parent.name());
            i.webLinks = parentLinks.isEmpty() ? null : parentLinks.toList();
        }
        info.parents.add(i);
    }
    return info;
}

From source file:com.google.gerrit.server.change.GetPatch.java

License:Apache License

@Override
public BinaryResult apply(RevisionResource rsrc) throws ResourceConflictException, IOException {
    Project.NameKey project = rsrc.getControl().getProject().getNameKey();
    final Repository repo = repoManager.openRepository(project);
    boolean close = true;
    try {// www  .j ava  2  s. c o m
        final RevWalk rw = new RevWalk(repo);
        try {
            final RevCommit commit = rw
                    .parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get()));
            RevCommit[] parents = commit.getParents();
            if (parents.length > 1) {
                throw new ResourceConflictException("Revision has more than 1 parent.");
            } else if (parents.length == 0) {
                throw new ResourceConflictException("Revision has no parent.");
            }
            final RevCommit base = parents[0];
            rw.parseBody(base);

            BinaryResult bin = new BinaryResult() {
                @Override
                public void writeTo(OutputStream out) throws IOException {
                    if (zip) {
                        ZipOutputStream zos = new ZipOutputStream(out);
                        ZipEntry e = new ZipEntry(fileName(rw, commit));
                        e.setTime(commit.getCommitTime() * 1000L);
                        zos.putNextEntry(e);
                        format(zos);
                        zos.closeEntry();
                        zos.finish();
                    } else {
                        format(out);
                    }
                }

                private void format(OutputStream out) throws IOException {
                    out.write(formatEmailHeader(commit).getBytes(UTF_8));
                    try (DiffFormatter fmt = new DiffFormatter(out)) {
                        fmt.setRepository(repo);
                        fmt.format(base.getTree(), commit.getTree());
                        fmt.flush();
                    }
                }

                @Override
                public void close() throws IOException {
                    rw.close();
                    repo.close();
                }
            };

            if (zip) {
                bin.disableGzip().setContentType("application/zip")
                        .setAttachmentName(fileName(rw, commit) + ".zip");
            } else {
                bin.base64().setContentType("application/mbox")
                        .setAttachmentName(download ? fileName(rw, commit) + ".base64" : null);
            }

            close = false;
            return bin;
        } finally {
            if (close) {
                rw.close();
            }
        }
    } finally {
        if (close) {
            repo.close();
        }
    }
}

From source file:com.google.gerrit.server.change.GetRelatedByAncestors.java

License:Apache License

private List<ChangeAndCommit> children(RevisionResource rsrc, RevWalk rw, Map<Change.Id, ChangeData> changes,
        Map<PatchSet.Id, PatchSet> patchSets, Set<Change.Id> added) throws OrmException, IOException {
    // children is a map of parent commit name to PatchSet built on it.
    Multimap<String, PatchSet.Id> children = allChildren(changes.keySet());

    RevFlag seenCommit = rw.newFlag("seenCommit");
    LinkedList<String> q = Lists.newLinkedList();
    seedQueue(rsrc, rw, seenCommit, patchSets, q);

    ProjectControl projectCtl = rsrc.getControl().getProjectControl();
    Set<Change.Id> seenChange = Sets.newHashSet();
    List<ChangeAndCommit> graph = Lists.newArrayList();
    while (!q.isEmpty()) {
        String id = q.remove();/*w w w . j  ava 2 s. c o m*/

        // For every matching change find the most recent patch set.
        Map<Change.Id, PatchSet.Id> matches = Maps.newHashMap();
        for (PatchSet.Id psId : children.get(id)) {
            PatchSet.Id e = matches.get(psId.getParentKey());
            if ((e == null || e.get() < psId.get()) && isVisible(projectCtl, changes, patchSets, psId)) {
                matches.put(psId.getParentKey(), psId);
            }
        }

        for (Map.Entry<Change.Id, PatchSet.Id> e : matches.entrySet()) {
            ChangeData cd = changes.get(e.getKey());
            PatchSet ps = patchSets.get(e.getValue());
            if (cd == null || ps == null || !seenChange.add(e.getKey())) {
                continue;
            }

            RevCommit c = rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
            if (!c.has(seenCommit)) {
                c.add(seenCommit);
                q.addFirst(ps.getRevision().get());
                if (added.add(ps.getId().getParentKey())) {
                    rw.parseBody(c);
                    graph.add(new ChangeAndCommit(cd.change(), ps, c));
                }
            }
        }
    }
    Collections.reverse(graph);
    return graph;
}

From source file:com.google.gerrit.server.change.RebaseChangeOp.java

License:Apache License

@Override
public void updateRepo(RepoContext ctx) throws MergeConflictException, InvalidChangeOperationException,
        RestApiException, IOException, OrmException, NoSuchChangeException {
    // Ok that originalPatchSet was not read in a transaction, since we just
    // need its revision.
    RevId oldRev = originalPatchSet.getRevision();

    RevWalk rw = ctx.getRevWalk();
    RevCommit original = rw.parseCommit(ObjectId.fromString(oldRev.get()));
    rw.parseBody(original);
    RevCommit baseCommit;//from ww  w .  jav  a2 s  . c  om
    if (baseCommitish != null) {
        baseCommit = rw.parseCommit(ctx.getRepository().resolve(baseCommitish));
    } else {
        baseCommit = rw.parseCommit(rebaseUtil.findBaseRevision(originalPatchSet, ctl.getChange().getDest(),
                ctx.getRepository(), ctx.getRevWalk()));
    }

    rebasedCommit = rebaseCommit(ctx, original, baseCommit);

    RevId baseRevId = new RevId(
            (baseCommitish != null) ? baseCommitish : ObjectId.toString(baseCommit.getId()));
    Base base = rebaseUtil.parseBase(new RevisionResource(new ChangeResource(ctl), originalPatchSet),
            baseRevId.get());

    rebasedPatchSetId = ChangeUtil.nextPatchSetId(ctx.getRepository(), ctl.getChange().currentPatchSetId());
    patchSetInserter = patchSetInserterFactory.create(ctl.getRefControl(), rebasedPatchSetId, rebasedCommit)
            .setDraft(originalPatchSet.isDraft()).setSendMail(false).setRunHooks(runHooks)
            .setCopyApprovals(copyApprovals).setMessage("Patch Set " + rebasedPatchSetId.get() + ": Patch Set "
                    + originalPatchSet.getId().get() + " was rebased");

    if (base != null) {
        patchSetInserter.setGroups(base.patchSet().getGroups());
    }
    if (validate != null) {
        patchSetInserter.setValidatePolicy(validate);
    }
    patchSetInserter.updateRepo(ctx);
}