Search in sources :

Example 1 with RevFilter

use of org.eclipse.jgit.revwalk.filter.RevFilter in project maven-scm by apache.

the class JGitUtils method getRevCommits.

/**
 * Get a list of commits between two revisions.
 *
 * @param repo     the repository to work on
 * @param sortings sorting
 * @param fromRev  start revision
 * @param toRev    if null, falls back to head
 * @param fromDate from which date on
 * @param toDate   until which date
 * @param maxLines max number of lines
 * @return a list of commits, might be empty, but never <code>null</code>
 * @throws IOException
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 */
public static List<RevCommit> getRevCommits(Repository repo, RevSort[] sortings, String fromRev, String toRev, final Date fromDate, final Date toDate, int maxLines) throws IOException, MissingObjectException, IncorrectObjectTypeException {
    List<RevCommit> revs = new ArrayList<RevCommit>();
    RevWalk walk = new RevWalk(repo);
    ObjectId fromRevId = fromRev != null ? repo.resolve(fromRev) : null;
    ObjectId toRevId = toRev != null ? repo.resolve(toRev) : null;
    if (sortings == null || sortings.length == 0) {
        sortings = new RevSort[] { RevSort.TOPO, RevSort.COMMIT_TIME_DESC };
    }
    for (final RevSort s : sortings) {
        walk.sort(s, true);
    }
    if (fromDate != null && toDate != null) {
        // walk.setRevFilter( CommitTimeRevFilter.between( fromDate, toDate ) );
        walk.setRevFilter(new RevFilter() {

            @Override
            public boolean include(RevWalk walker, RevCommit cmit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
                int cmtTime = cmit.getCommitTime();
                return (cmtTime >= (fromDate.getTime() / 1000)) && (cmtTime <= (toDate.getTime() / 1000));
            }

            @Override
            public RevFilter clone() {
                return this;
            }
        });
    } else {
        if (fromDate != null) {
            walk.setRevFilter(CommitTimeRevFilter.after(fromDate));
        }
        if (toDate != null) {
            walk.setRevFilter(CommitTimeRevFilter.before(toDate));
        }
    }
    if (fromRevId != null) {
        RevCommit c = walk.parseCommit(fromRevId);
        c.add(RevFlag.UNINTERESTING);
        RevCommit real = walk.parseCommit(c);
        walk.markUninteresting(real);
    }
    if (toRevId != null) {
        RevCommit c = walk.parseCommit(toRevId);
        c.remove(RevFlag.UNINTERESTING);
        RevCommit real = walk.parseCommit(c);
        walk.markStart(real);
    } else {
        final ObjectId head = repo.resolve(Constants.HEAD);
        if (head == null) {
            throw new RuntimeException("Cannot resolve " + Constants.HEAD);
        }
        RevCommit real = walk.parseCommit(head);
        walk.markStart(real);
    }
    int n = 0;
    for (final RevCommit c : walk) {
        n++;
        if (maxLines != -1 && n > maxLines) {
            break;
        }
        revs.add(c);
    }
    return revs;
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) CommitTimeRevFilter(org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) StopWalkException(org.eclipse.jgit.errors.StopWalkException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RevSort(org.eclipse.jgit.revwalk.RevSort)

Example 2 with RevFilter

use of org.eclipse.jgit.revwalk.filter.RevFilter in project gerrit by GerritCodeReview.

the class ReceiveCommits method validateConnected.

// Validate that the new commits are connected with the target
// branch.  If they aren't, we want to abort. We do this check by
// looking to see if we can compute a merge base between the new
// commits and the target branch head.
private boolean validateConnected(ReceiveCommand cmd, BranchNameKey dest, RevCommit tip) {
    try (TraceTimer traceTimer = newTimer("validateConnected", Metadata.builder().branchName(dest.branch()))) {
        RevWalk walk = receivePack.getRevWalk();
        try {
            Ref targetRef = receivePackRefCache.exactRef(dest.branch());
            if (targetRef == null || targetRef.getObjectId() == null) {
                // The destination branch does not yet exist. Assume the
                // history being sent for review will start it and thus
                // is "connected" to the branch.
                logger.atFine().log("Branch is unborn");
                // This is not an error condition.
                return true;
            }
            RevCommit h = walk.parseCommit(targetRef.getObjectId());
            logger.atFine().log("Current branch tip: %s", h.name());
            RevFilter oldRevFilter = walk.getRevFilter();
            try {
                walk.reset();
                walk.setRevFilter(RevFilter.MERGE_BASE);
                walk.markStart(tip);
                walk.markStart(h);
                if (walk.next() == null) {
                    reject(cmd, "no common ancestry");
                    return false;
                }
            } finally {
                walk.reset();
                walk.setRevFilter(oldRevFilter);
            }
        } catch (IOException e) {
            cmd.setResult(REJECTED_MISSING_OBJECT);
            logger.atSevere().withCause(e).log("Invalid pack upload; one or more objects weren't sent");
            return false;
        }
        return true;
    }
}
Also used : Ref(org.eclipse.jgit.lib.Ref) RefNames.isConfigRef(com.google.gerrit.entities.RefNames.isConfigRef) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 3 with RevFilter

use of org.eclipse.jgit.revwalk.filter.RevFilter in project chuidiang-ejemplos by chuidiang.

the class GitAnalyzer method analyze.

public void analyze(HtmlFormat format, String issuePattern, String issueName) throws IOException {
    try (RevWalk walk = new RevWalk(repository)) {
        RevFilter filter = MessageRevFilter.create(issuePattern);
        walk.setRevFilter(filter);
        walk.markStart(walk.parseCommit(repository.resolve("HEAD")));
        Iterator<RevCommit> iterator = walk.iterator();
        if (!iterator.hasNext()) {
            return;
        }
        format.addIssue(issueName);
        while (iterator.hasNext()) {
            RevCommit commit = iterator.next();
            String commitNumber = commit.getId().getName();
            Date date = commit.getAuthorIdent().getWhen();
            String author = commit.getAuthorIdent().getName();
            String comment = commit.getFullMessage();
            ObjectId objectId = commit.getTree().getId();
            RevCommit parent = commit.getParent(0);
            PatchIdDiffFormatter formatter = new PatchIdDiffFormatter();
            formatter.setRepository(repository);
            ArrayList<String> files = new ArrayList<>();
            try {
                List<DiffEntry> entries = formatter.scan(parent, objectId);
                entries.forEach((entry) -> {
                    try {
                        FileHeader header = formatter.toFileHeader(entry);
                        files.add(header.getChangeType() + " " + getPath(header));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            format.addChange(commitNumber, date, author, comment, files.toArray(new String[] {}));
        }
        format.endIssue();
    } catch (Exception e) {
        format.endIssue();
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Date(java.util.Date) IOException(java.io.IOException) MessageRevFilter(org.eclipse.jgit.revwalk.filter.MessageRevFilter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) FileHeader(org.eclipse.jgit.patch.FileHeader) RevCommit(org.eclipse.jgit.revwalk.RevCommit) PatchIdDiffFormatter(org.eclipse.jgit.diff.PatchIdDiffFormatter) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 4 with RevFilter

use of org.eclipse.jgit.revwalk.filter.RevFilter in project gerrit by GerritCodeReview.

the class ReceiveCommits method parseMagicBranch.

private void parseMagicBranch(ReceiveCommand cmd) {
    // Permit exactly one new change request per push.
    if (magicBranch != null) {
        reject(cmd, "duplicate request");
        return;
    }
    logDebug("Found magic branch {}", cmd.getRefName());
    magicBranch = new MagicBranchInput(user, cmd, labelTypes, notesMigration);
    magicBranch.reviewer.addAll(reviewersFromCommandLine);
    magicBranch.cc.addAll(ccFromCommandLine);
    String ref;
    CmdLineParser clp = optionParserFactory.create(magicBranch);
    magicBranch.clp = clp;
    try {
        ref = magicBranch.parse(clp, repo, rp.getAdvertisedRefs().keySet(), pushOptions);
    } catch (CmdLineException e) {
        if (!clp.wasHelpRequestedByOption()) {
            logDebug("Invalid branch syntax");
            reject(cmd, e.getMessage());
            return;
        }
        // never happen
        ref = null;
    }
    if (clp.wasHelpRequestedByOption()) {
        StringWriter w = new StringWriter();
        w.write("\nHelp for refs/for/branch:\n\n");
        clp.printUsage(w, null);
        addMessage(w.toString());
        reject(cmd, "see help");
        return;
    }
    if (projectControl.getProjectState().isAllUsers() && RefNames.REFS_USERS_SELF.equals(ref)) {
        logDebug("Handling {}", RefNames.REFS_USERS_SELF);
        ref = RefNames.refsUsers(user.getAccountId());
    }
    if (!rp.getAdvertisedRefs().containsKey(ref) && !ref.equals(readHEAD(repo))) {
        logDebug("Ref {} not found", ref);
        if (ref.startsWith(Constants.R_HEADS)) {
            String n = ref.substring(Constants.R_HEADS.length());
            reject(cmd, "branch " + n + " not found");
        } else {
            reject(cmd, ref + " not found");
        }
        return;
    }
    magicBranch.dest = new Branch.NameKey(project.getNameKey(), ref);
    magicBranch.ctl = projectControl.controlForRef(ref);
    if (projectControl.getProject().getState() != com.google.gerrit.extensions.client.ProjectState.ACTIVE) {
        reject(cmd, "project is read only");
        return;
    }
    if (magicBranch.draft) {
        if (!receiveConfig.allowDrafts) {
            errors.put(Error.CODE_REVIEW, ref);
            reject(cmd, "draft workflow is disabled");
            return;
        } else if (projectControl.controlForRef(MagicBranch.NEW_DRAFT_CHANGE + ref).isBlocked(Permission.PUSH)) {
            errors.put(Error.CODE_REVIEW, ref);
            reject(cmd, "cannot upload drafts");
            return;
        }
    }
    if (!magicBranch.ctl.canUpload()) {
        errors.put(Error.CODE_REVIEW, ref);
        reject(cmd, "cannot upload review");
        return;
    }
    if (magicBranch.isPrivate && magicBranch.removePrivate) {
        reject(cmd, "the options 'private' and 'remove-private' are mutually exclusive");
        return;
    }
    if (magicBranch.workInProgress && magicBranch.ready) {
        reject(cmd, "the options 'wip' and 'ready' are mutually exclusive");
        return;
    }
    if (magicBranch.publishComments && magicBranch.noPublishComments) {
        reject(cmd, "the options 'publish-comments' and 'no-publish-comments' are mutually exclusive");
        return;
    }
    if (magicBranch.draft && magicBranch.submit) {
        reject(cmd, "cannot submit draft");
        return;
    }
    if (magicBranch.submit && !projectControl.controlForRef(MagicBranch.NEW_CHANGE + ref).canSubmit(true)) {
        reject(cmd, "submit not allowed");
        return;
    }
    RevWalk walk = rp.getRevWalk();
    RevCommit tip;
    try {
        tip = walk.parseCommit(magicBranch.cmd.getNewId());
        logDebug("Tip of push: {}", tip.name());
    } catch (IOException ex) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        logError("Invalid pack upload; one or more objects weren't sent", ex);
        return;
    }
    String destBranch = magicBranch.dest.get();
    try {
        if (magicBranch.merged) {
            if (magicBranch.draft) {
                reject(cmd, "cannot be draft & merged");
                return;
            }
            if (magicBranch.base != null) {
                reject(cmd, "cannot use merged with base");
                return;
            }
            RevCommit branchTip = readBranchTip(cmd, magicBranch.dest);
            if (branchTip == null) {
                // readBranchTip already rejected cmd.
                return;
            }
            if (!walk.isMergedInto(tip, branchTip)) {
                reject(cmd, "not merged into branch");
                return;
            }
        }
        // if %base or %merged was specified, ignore newChangeForAllNotInTarget.
        if (tip.getParentCount() > 1 || magicBranch.base != null || magicBranch.merged || tip.getParentCount() == 0) {
            logDebug("Forcing newChangeForAllNotInTarget = false");
            newChangeForAllNotInTarget = false;
        }
        if (magicBranch.base != null) {
            logDebug("Handling %base: {}", magicBranch.base);
            magicBranch.baseCommit = Lists.newArrayListWithCapacity(magicBranch.base.size());
            for (ObjectId id : magicBranch.base) {
                try {
                    magicBranch.baseCommit.add(walk.parseCommit(id));
                } catch (IncorrectObjectTypeException notCommit) {
                    reject(cmd, "base must be a commit");
                    return;
                } catch (MissingObjectException e) {
                    reject(cmd, "base not found");
                    return;
                } catch (IOException e) {
                    logWarn(String.format("Project %s cannot read %s", project.getName(), id.name()), e);
                    reject(cmd, "internal server error");
                    return;
                }
            }
        } else if (newChangeForAllNotInTarget) {
            RevCommit branchTip = readBranchTip(cmd, magicBranch.dest);
            if (branchTip == null) {
                // readBranchTip already rejected cmd.
                return;
            }
            magicBranch.baseCommit = Collections.singletonList(branchTip);
            logDebug("Set baseCommit = {}", magicBranch.baseCommit.get(0).name());
        }
    } catch (IOException ex) {
        logWarn(String.format("Error walking to %s in project %s", destBranch, project.getName()), ex);
        reject(cmd, "internal server error");
        return;
    }
    //
    try {
        Ref targetRef = rp.getAdvertisedRefs().get(magicBranch.ctl.getRefName());
        if (targetRef == null || targetRef.getObjectId() == null) {
            // The destination branch does not yet exist. Assume the
            // history being sent for review will start it and thus
            // is "connected" to the branch.
            logDebug("Branch is unborn");
            return;
        }
        RevCommit h = walk.parseCommit(targetRef.getObjectId());
        logDebug("Current branch tip: {}", h.name());
        RevFilter oldRevFilter = walk.getRevFilter();
        try {
            walk.reset();
            walk.setRevFilter(RevFilter.MERGE_BASE);
            walk.markStart(tip);
            walk.markStart(h);
            if (walk.next() == null) {
                reject(magicBranch.cmd, "no common ancestry");
            }
        } finally {
            walk.reset();
            walk.setRevFilter(oldRevFilter);
        }
    } catch (IOException e) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        logError("Invalid pack upload; one or more objects weren't sent", e);
    }
}
Also used : CmdLineParser(com.google.gerrit.util.cli.CmdLineParser) ObjectId(org.eclipse.jgit.lib.ObjectId) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Ref(org.eclipse.jgit.lib.Ref) StringWriter(java.io.StringWriter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) CmdLineException(org.kohsuke.args4j.CmdLineException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 5 with RevFilter

use of org.eclipse.jgit.revwalk.filter.RevFilter in project egit by eclipse.

the class CommitUtil method areCommitsInCurrentBranch.

/**
 * Returns whether the commits are on the current branch, ie. if they are
 * reachable from the current HEAD.
 *
 * @param commits
 *            the commits to check
 * @param repository
 *            the repository
 * @return true if the commits are reachable from HEAD
 * @throws IOException
 *             if there is an I/O error
 */
public static boolean areCommitsInCurrentBranch(Collection<RevCommit> commits, Repository repository) throws IOException {
    try (RevWalk walk = new RevWalk(repository)) {
        ObjectId headCommitId = repository.resolve(Constants.HEAD);
        RevCommit headCommit = walk.parseCommit(headCommitId);
        for (final RevCommit commit : commits) {
            walk.reset();
            walk.markStart(headCommit);
            RevFilter revFilter = new RevFilter() {

                @Override
                public boolean include(RevWalk walker, RevCommit cmit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
                    return cmit.equals(commit);
                }

                @Override
                public RevFilter clone() {
                    return null;
                }
            };
            walk.setRevFilter(revFilter);
            if (walk.next() == null)
                return false;
        }
        return true;
    }
}
Also used : RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

RevCommit (org.eclipse.jgit.revwalk.RevCommit)6 RevWalk (org.eclipse.jgit.revwalk.RevWalk)6 RevFilter (org.eclipse.jgit.revwalk.filter.RevFilter)6 IOException (java.io.IOException)5 ObjectId (org.eclipse.jgit.lib.ObjectId)5 ArrayList (java.util.ArrayList)3 IncorrectObjectTypeException (org.eclipse.jgit.errors.IncorrectObjectTypeException)3 MissingObjectException (org.eclipse.jgit.errors.MissingObjectException)3 StopWalkException (org.eclipse.jgit.errors.StopWalkException)2 Ref (org.eclipse.jgit.lib.Ref)2 CommitTimeRevFilter (org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter)2 RefNames.isConfigRef (com.google.gerrit.entities.RefNames.isConfigRef)1 Branch (com.google.gerrit.reviewdb.client.Branch)1 TraceTimer (com.google.gerrit.server.logging.TraceContext.TraceTimer)1 MagicBranch (com.google.gerrit.server.util.MagicBranch)1 CmdLineParser (com.google.gerrit.util.cli.CmdLineParser)1 StringWriter (java.io.StringWriter)1 Date (java.util.Date)1 DiffEntry (org.eclipse.jgit.diff.DiffEntry)1 PatchIdDiffFormatter (org.eclipse.jgit.diff.PatchIdDiffFormatter)1