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

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

Introduction

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

Prototype

public void markStart(Collection<RevCommit> list)
        throws MissingObjectException, IncorrectObjectTypeException, IOException 

Source Link

Document

Mark commits to start graph traversal from.

Usage

From source file:actors.PostReceiveActor.java

License:Apache License

protected Collection<? extends RevCommit> parseCommitsFrom(ReceiveCommand command, Project project) {
    Repository repository = GitRepository.buildGitRepository(project);
    List<RevCommit> list = new ArrayList<>();

    try {//from w  w  w  . j a  va2 s. c  om
        ObjectId endRange = command.getNewId();
        ObjectId startRange = command.getOldId();

        RevWalk rw = new RevWalk(repository);
        rw.markStart(rw.parseCommit(endRange));
        if (startRange.equals(ObjectId.zeroId())) {
            // maybe this is a tag or an orphan branch
            list.add(rw.parseCommit(endRange));
            rw.dispose();
            return list;
        } else {
            rw.markUninteresting(rw.parseCommit(startRange));
        }

        for (RevCommit rev : rw) {
            list.add(rev);
        }
        rw.dispose();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return list;
}

From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java

License:Open Source License

private void _run() throws IOException, MinerException, SQLException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(settings.srcLocalPath, ".git")).readEnvironment()
            .findGitDir().build();//  w ww .  j  av  a  2 s .  c om

    /*
    Map<String,Ref> refs = repository.getAllRefs();
    for (Map.Entry<String, Ref> ref : refs.entrySet ()) {
       System.out.println (ref.getKey ());
    }
    */

    Ref head = repository.getRef(startRef);
    if (head == null) {
        throw new MinerException("Unknown reference: '" + startRef + "'");
    }

    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(head.getObjectId());
    walk.markStart(commit);
    walk.sort(RevSort.REVERSE);

    // count commit: (fast)
    int commitCount = 0;
    Iterator<RevCommit> iter = walk.iterator();
    while (iter.hasNext()) {
        iter.next();
        commitCount++;
    }

    emitTasksTotal(commitCount);

    // process commits: (slow)
    walk.reset();
    walk.markStart(commit);
    walk.sort(RevSort.REVERSE);

    Map<String, ManagedFile> fileCache = new HashMap<String, ManagedFile>();

    for (RevCommit rev : walk) {
        if (stopped == true) {
            break;
        }

        processCommit(repository, walk, rev, fileCache);
    }

    walk.dispose();
    repository.close();
}

From source file:br.com.metricminer2.scm.GitRepository.java

License:Apache License

public SCMRepository info() {
    RevWalk rw = null;
    Git git = null;/*from  w  ww.  j  a  va  2  s.  c o m*/
    try {
        git = Git.open(new File(path));
        AnyObjectId headId = git.getRepository().resolve(Constants.HEAD);

        rw = new RevWalk(git.getRepository());
        RevCommit root = rw.parseCommit(headId);
        rw.sort(RevSort.REVERSE);
        rw.markStart(root);
        RevCommit lastCommit = rw.next();

        String origin = git.getRepository().getConfig().getString("remote", "origin", "url");

        return new SCMRepository(this, origin, path, headId.getName(), lastCommit.getName());
    } catch (Exception e) {
        throw new RuntimeException("error when info " + path, e);
    } finally {
        if (rw != null)
            rw.release();
        if (git != null)
            git.close();
    }

}

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 ww.  ja  v  a 2s.c o  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: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/*from  w  w  w.  ja  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./* ww w . j av  a2 s  .  c  om*/
 *
 * @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 w  w  w. ja  va 2  s. c  o m
 */
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.gitblit.LuceneExecutor.java

License:Apache License

/**
 * This completely indexes the repository and will destroy any existing
 * index./*from w  w w . ja va 2s  . c om*/
 * 
 * @param repositoryName
 * @param repository
 * @return IndexResult
 */
public IndexResult reindex(RepositoryModel model, Repository repository) {
    IndexResult result = new IndexResult();
    if (!deleteIndex(model.name)) {
        return result;
    }
    try {
        String[] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]);
        FileBasedConfig config = getConfig(repository);
        Set<String> indexedCommits = new TreeSet<String>();
        IndexWriter writer = getIndexWriter(model.name);
        // build a quick lookup of tags
        Map<String, List<String>> tags = new HashMap<String, List<String>>();
        for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
            if (!tag.isAnnotatedTag()) {
                // skip non-annotated tags
                continue;
            }
            if (!tags.containsKey(tag.getObjectId())) {
                tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
            }
            tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
        }

        ObjectReader reader = repository.newObjectReader();

        // get the local branches
        List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);

        // sort them by most recently updated
        Collections.sort(branches, new Comparator<RefModel>() {
            @Override
            public int compare(RefModel ref1, RefModel ref2) {
                return ref2.getDate().compareTo(ref1.getDate());
            }
        });

        // reorder default branch to first position
        RefModel defaultBranch = null;
        ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
        for (RefModel branch : branches) {
            if (branch.getObjectId().equals(defaultBranchId)) {
                defaultBranch = branch;
                break;
            }
        }
        branches.remove(defaultBranch);
        branches.add(0, defaultBranch);

        // walk through each branch
        for (RefModel branch : branches) {

            boolean indexBranch = false;
            if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
                    && branch.equals(defaultBranch)) {
                // indexing "default" branch
                indexBranch = true;
            } else if (IssueUtils.GB_ISSUES.equals(branch)) {
                // skip the GB_ISSUES branch because it is indexed later
                // note: this is different than updateIndex
                indexBranch = false;
            } else {
                // normal explicit branch check
                indexBranch = model.indexedBranches.contains(branch.getName());
            }

            // if this branch is not specifically indexed then skip
            if (!indexBranch) {
                continue;
            }

            String branchName = branch.getName();
            RevWalk revWalk = new RevWalk(reader);
            RevCommit tip = revWalk.parseCommit(branch.getObjectId());
            String tipId = tip.getId().getName();

            String keyName = getBranchKey(branchName);
            config.setString(CONF_ALIAS, null, keyName, branchName);
            config.setString(CONF_BRANCH, null, keyName, tipId);

            // index the blob contents of the tree
            TreeWalk treeWalk = new TreeWalk(repository);
            treeWalk.addTree(tip.getTree());
            treeWalk.setRecursive(true);

            Map<String, ObjectId> paths = new TreeMap<String, ObjectId>();
            while (treeWalk.next()) {
                // ensure path is not in a submodule
                if (treeWalk.getFileMode(0) != FileMode.GITLINK) {
                    paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0));
                }
            }

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] tmp = new byte[32767];

            RevWalk commitWalk = new RevWalk(reader);
            commitWalk.markStart(tip);

            RevCommit commit;
            while ((paths.size() > 0) && (commit = commitWalk.next()) != null) {
                TreeWalk diffWalk = new TreeWalk(reader);
                int parentCount = commit.getParentCount();
                switch (parentCount) {
                case 0:
                    diffWalk.addTree(new EmptyTreeIterator());
                    break;
                case 1:
                    diffWalk.addTree(getTree(commitWalk, commit.getParent(0)));
                    break;
                default:
                    // skip merge commits
                    continue;
                }
                diffWalk.addTree(getTree(commitWalk, commit));
                diffWalk.setFilter(ANY_DIFF);
                diffWalk.setRecursive(true);
                while ((paths.size() > 0) && diffWalk.next()) {
                    String path = diffWalk.getPathString();
                    if (!paths.containsKey(path)) {
                        continue;
                    }

                    // remove path from set
                    ObjectId blobId = paths.remove(path);
                    result.blobCount++;

                    // index the blob metadata
                    String blobAuthor = getAuthor(commit);
                    String blobCommitter = getCommitter(commit);
                    String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L, Resolution.MINUTE);

                    Document doc = new Document();
                    doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), Store.YES,
                            Index.NOT_ANALYZED_NO_NORMS));
                    doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_COMMIT, commit.getName(), Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_PATH, path, Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_DATE, blobDate, Store.YES, Index.NO));
                    doc.add(new Field(FIELD_AUTHOR, blobAuthor, Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_COMMITTER, blobCommitter, Store.YES, Index.ANALYZED));

                    // determine extension to compare to the extension
                    // blacklist
                    String ext = null;
                    String name = path.toLowerCase();
                    if (name.indexOf('.') > -1) {
                        ext = name.substring(name.lastIndexOf('.') + 1);
                    }

                    // index the blob content
                    if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
                        ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB);
                        InputStream in = ldr.openStream();
                        int n;
                        while ((n = in.read(tmp)) > 0) {
                            os.write(tmp, 0, n);
                        }
                        in.close();
                        byte[] content = os.toByteArray();
                        String str = StringUtils.decodeString(content, encodings);
                        doc.add(new Field(FIELD_CONTENT, str, Store.YES, Index.ANALYZED));
                        os.reset();
                    }

                    // add the blob to the index
                    writer.addDocument(doc);
                }
            }

            os.close();

            // index the tip commit object
            if (indexedCommits.add(tipId)) {
                Document doc = createDocument(tip, tags.get(tipId));
                doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
                writer.addDocument(doc);
                result.commitCount += 1;
                result.branchCount += 1;
            }

            // traverse the log and index the previous commit objects
            RevWalk historyWalk = new RevWalk(reader);
            historyWalk.markStart(historyWalk.parseCommit(tip.getId()));
            RevCommit rev;
            while ((rev = historyWalk.next()) != null) {
                String hash = rev.getId().getName();
                if (indexedCommits.add(hash)) {
                    Document doc = createDocument(rev, tags.get(hash));
                    doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
                    writer.addDocument(doc);
                    result.commitCount += 1;
                }
            }
        }

        // finished
        reader.release();

        // this repository has a gb-issues branch, index all issues
        if (IssueUtils.getIssuesBranch(repository) != null) {
            List<IssueModel> issues = IssueUtils.getIssues(repository, null);
            if (issues.size() > 0) {
                result.branchCount += 1;
            }
            for (IssueModel issue : issues) {
                result.issueCount++;
                Document doc = createDocument(issue);
                writer.addDocument(doc);
            }
        }

        // commit all changes and reset the searcher
        config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION);
        config.save();
        writer.commit();
        resetIndexSearcher(model.name);
        result.success();
    } catch (Exception e) {
        logger.error("Exception while reindexing " + model.name, e);
    }
    return result;
}

From source file:com.gitblit.plugin.flowdock.FlowDockReceiveHook.java

License:Apache License

private List<RevCommit> getCommits(GitblitReceivePack receivePack, String baseId, String tipId) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    RevWalk walk = receivePack.getRevWalk();
    walk.reset();//from  ww  w  . j a  v  a 2  s  .co  m
    walk.sort(RevSort.TOPO);
    try {
        RevCommit tip = walk.parseCommit(receivePack.getRepository().resolve(tipId));
        RevCommit base = walk.parseCommit(receivePack.getRepository().resolve(baseId));
        walk.markStart(tip);
        walk.markUninteresting(base);
        for (;;) {
            RevCommit c = walk.next();
            if (c == null) {
                break;
            }
            list.add(c);
        }
    } catch (IOException e) {
        // Should never happen, the core receive process would have
        // identified the missing object earlier before we got control.
        log.error("failed to get commits", e);
    } finally {
        walk.release();
    }
    return list;
}

From source file:com.gitblit.plugin.flowdock.TicketMessageGenerator.java

License:Apache License

private List<RevCommit> getCommits(String repositoryName, String baseId, String tipId) {
    IRepositoryManager repositoryManager = GitblitContext.getManager(IRepositoryManager.class);
    Repository db = repositoryManager.getRepository(repositoryName);
    List<RevCommit> list = new ArrayList<RevCommit>();
    RevWalk walk = new RevWalk(db);
    walk.reset();//  w ww .  java2  s . c om
    walk.sort(RevSort.TOPO);
    walk.sort(RevSort.REVERSE, true);
    try {
        RevCommit tip = walk.parseCommit(db.resolve(tipId));
        RevCommit base = walk.parseCommit(db.resolve(baseId));
        walk.markStart(tip);
        walk.markUninteresting(base);
        for (;;) {
            RevCommit c = walk.next();
            if (c == null) {
                break;
            }
            list.add(c);
        }
    } catch (IOException e) {
        // Should never happen, the core receive process would have
        // identified the missing object earlier before we got control.
        log.error("failed to get commits", e);
    } finally {
        walk.release();
        db.close();
    }
    return list;
}