Example usage for org.eclipse.jgit.revwalk.filter RevFilter MERGE_BASE

List of usage examples for org.eclipse.jgit.revwalk.filter RevFilter MERGE_BASE

Introduction

In this page you can find the example usage for org.eclipse.jgit.revwalk.filter RevFilter MERGE_BASE.

Prototype

RevFilter MERGE_BASE

To view the source code for org.eclipse.jgit.revwalk.filter RevFilter MERGE_BASE.

Click Source Link

Document

Selects only merge bases of the starting points (thread safe).

Usage

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Returns the merge base of two commits or null if there is no common
 * ancestry./* w w w .j  av a  2 s. c o  m*/
 *
 * @param repository
 * @param commitIdA
 * @param commitIdB
 * @return the commit id of the merge base or null if there is no common base
 */
public static String getMergeBase(Repository repository, ObjectId commitIdA, ObjectId commitIdB) {
    RevWalk rw = new RevWalk(repository);
    try {
        RevCommit a = rw.lookupCommit(commitIdA);
        RevCommit b = rw.lookupCommit(commitIdB);

        rw.setRevFilter(RevFilter.MERGE_BASE);
        rw.markStart(a);
        rw.markStart(b);
        RevCommit mergeBase = rw.next();
        if (mergeBase == null) {
            return null;
        }
        return mergeBase.getName();
    } catch (Exception e) {
        LOGGER.error("Failed to determine merge base", e);
    } finally {
        rw.dispose();
    }
    return null;
}

From source file:com.github.checkstyle.regression.git.DiffParser.java

License:Open Source License

/**
 * Gets the merge-base of two commits.//from w  w  w  . j  av  a  2 s.  c  om
 * A merge-base is a best common ancestor between two commits. One common ancestor is
 * better than another common ancestor if the latter is an ancestor of the former.
 * A common ancestor that does not have any better common ancestor is a best common ancestor.
 * @param walk    the {@link RevWalk} for computing merge bases
 * @param commitA the first commit to start the walk with
 * @param commitB the second commit to start the walk with
 * @return the merge-base of two commits
 * @throws IOException JGit library exception
 */
private static RevCommit getMergeBaseCommit(RevWalk walk, RevCommit commitA, RevCommit commitB)
        throws IOException {
    walk.reset();
    walk.setRevFilter(RevFilter.MERGE_BASE);
    walk.markStart(commitA);
    walk.markStart(commitB);
    return walk.next();
}

From source file:com.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java

License:Open Source License

/**
 * Gets the merge base for the two given commits.
 * Danger -- the commits need to be from the given RevWalk or this will
 * fail in a not-completely-obvious way.
 */// www  .  j  a  v a 2s .c  o  m
private RevCommit getMergeBase(RevWalk walk, RevCommit commit1, RevCommit commit2) throws GitClientException {
    try {
        walk.setRevFilter(RevFilter.MERGE_BASE);
        walk.markStart(commit1);
        walk.markStart(commit2);
        return walk.next();
    } catch (Exception e) {
        throw new GitClientException("Failed to get merge base commit for " + commit1 + " and " + commit2, e);
    }
}

From source file:com.google.gerrit.server.git.ReceiveCommits.java

License:Apache License

private void parseMagicBranch(final ReceiveCommand cmd) {
    // Permit exactly one new change request per push.
    if (magicBranch != null) {
        reject(cmd, "duplicate request");
        return;//from  ww w  . j  a v  a 2  s. c o  m
    }

    magicBranch = new MagicBranchInput(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());
    } catch (CmdLineException e) {
        if (!clp.wasHelpRequestedByOption()) {
            reject(cmd, e.getMessage());
            return;
        }
        ref = null; // never happen
    }
    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 (!rp.getAdvertisedRefs().containsKey(ref) && !ref.equals(readHEAD(repo))) {
        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 (!magicBranch.ctl.canWrite()) {
        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("refs/drafts/" + 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.draft && magicBranch.submit) {
        reject(cmd, "cannot submit draft");
        return;
    }

    if (magicBranch.submit && !projectControl.controlForRef(MagicBranch.NEW_CHANGE + ref).canSubmit()) {
        reject(cmd, "submit not allowed");
        return;
    }

    RevWalk walk = rp.getRevWalk();
    RevCommit tip;
    try {
        tip = walk.parseCommit(magicBranch.cmd.getNewId());
    } catch (IOException ex) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        log.error("Invalid pack upload; one or more objects weren't sent", ex);
        return;
    }

    // If tip is a merge commit, or the root commit or
    // if %base was specified, ignore newChangeForAllNotInTarget
    if (tip.getParentCount() > 1 || magicBranch.base != null || tip.getParentCount() == 0) {
        newChangeForAllNotInTarget = false;
    }

    if (magicBranch.base != null) {
        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) {
                log.warn(String.format("Project %s cannot read %s", project.getName(), id.name()), e);
                reject(cmd, "internal server error");
                return;
            }
        }
    } else if (newChangeForAllNotInTarget) {
        String destBranch = magicBranch.dest.get();
        try {
            Ref r = repo.getRefDatabase().exactRef(destBranch);
            if (r == null) {
                reject(cmd, destBranch + " not found");
                return;
            }

            ObjectId baseHead = r.getObjectId();
            magicBranch.baseCommit = Collections.singletonList(walk.parseCommit(baseHead));
        } catch (IOException ex) {
            log.warn(String.format("Project %s cannot read %s", project.getName(), destBranch), ex);
            reject(cmd, "internal server error");
            return;
        }
    }

    // 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.
    //
    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.
            return;
        }
        final RevCommit h = walk.parseCommit(targetRef.getObjectId());
        final 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);
        log.error("Invalid pack upload; one or more objects weren't sent", e);
    }
}

From source file:com.hpe.application.automation.tools.octane.model.processors.scm.GitSCMProcessor.java

License:Open Source License

@Override
public CommonOriginRevision getCommonOriginRevision(final Run run) {
    //for phase 1 this is hard coded since its not possible to calculate it, and configuration from outside will complicate the feature
    //so for this phase we keep it hardcoded.
    CommonOriginRevision commonOriginRevision = new CommonOriginRevision();

    try {//w w w  . j a  v  a2 s . co  m
        final AbstractBuild abstractBuild = (AbstractBuild) run;
        FilePath workspace = ((AbstractBuild) run).getWorkspace();
        if (workspace != null) {
            commonOriginRevision = workspace.act(new FilePath.FileCallable<CommonOriginRevision>() {
                @Override
                public CommonOriginRevision invoke(File file, VirtualChannel channel)
                        throws IOException, InterruptedException {
                    CommonOriginRevision result = new CommonOriginRevision();
                    File repoDir = new File(getRemoteString(abstractBuild) + File.separator + ".git");
                    Git git = Git.open(repoDir);
                    Repository repo = git.getRepository();
                    final RevWalk walk = new RevWalk(repo);

                    ObjectId resolveForCurrentBranch = repo.resolve(Constants.HEAD);
                    RevCommit currentBranchCommit = walk.parseCommit(resolveForCurrentBranch);
                    ObjectId resolveForMaster = repo.resolve(MASTER);
                    RevCommit masterCommit = walk.parseCommit(resolveForMaster);

                    walk.reset();
                    walk.setRevFilter(RevFilter.MERGE_BASE);
                    walk.markStart(currentBranchCommit);
                    walk.markStart(masterCommit);
                    final RevCommit base = walk.next();
                    if (base == null)
                        return result;
                    final RevCommit base2 = walk.next();
                    if (base2 != null) {
                        throw new NoMergeBaseException(
                                NoMergeBaseException.MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED,
                                MessageFormat.format(JGitText.get().multipleMergeBasesFor,
                                        currentBranchCommit.name(), masterCommit.name(), base.name(),
                                        base2.name()));
                    }
                    result.revision = base.getId().getName();
                    result.branch = getBranchName(run);
                    return result;
                }

                @Override
                public void checkRoles(RoleChecker roleChecker) throws SecurityException {
                    if (roleChecker != null) {
                        logger.info("Note : roleChecker is not empty, but no action was taken");
                    }
                }
            });
        }
        logger.info("most recent common revision resolved to " + commonOriginRevision.revision + " (branch: "
                + commonOriginRevision.branch + ")");
    } catch (Exception e) {
        logger.error("failed to resolve most recent common revision", e);
        return commonOriginRevision;
    }
    return commonOriginRevision;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

protected static RevCommit getBaseCommit(RevWalk walk, RevCommit a, RevCommit b)
        throws IncorrectObjectTypeException, IOException {
    walk.reset();//from  w ww .  jav  a 2s. c  o  m
    walk.setRevFilter(RevFilter.MERGE_BASE);
    walk.markStart(a);
    walk.markStart(b);
    final RevCommit base = walk.next();
    if (base == null)
        return null;
    final RevCommit base2 = walk.next();
    if (base2 != null) {
        // throw new NoMergeBaseException(MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED,
        // MessageFormat.format(JGitText.get().multipleMergeBasesFor, a.name(), b.name(), base.name(),
        // base2.name()));
        throw new IOException(MessageFormat.format(JGitText.get().multipleMergeBasesFor, a.name(), b.name(),
                base.name(), base2.name()));

    }
    return base;
}

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

boolean isRefBehind(Ref behind, Ref tracking) throws IOException {
    RevWalk walk = new RevWalk(_git.getRepository());
    try {//from  ww  w . j a  v a  2s.co m
        RevCommit behindCommit = walk.parseCommit(behind.getObjectId());
        RevCommit trackingCommit = walk.parseCommit(tracking.getObjectId());
        walk.setRevFilter(RevFilter.MERGE_BASE);
        walk.markStart(behindCommit);
        walk.markStart(trackingCommit);
        RevCommit mergeBase = walk.next();
        walk.reset();
        walk.setRevFilter(RevFilter.ALL);
        int aheadCount = RevWalkUtils.count(walk, behindCommit, mergeBase);
        int behindCount = RevWalkUtils.count(walk, trackingCommit, mergeBase);

        return behindCount > aheadCount ? true : false;
    } catch (Throwable e) {
        throw new RuntimeException(String.format("Failed to check if [%s] behind [%s]", behind, tracking), e);
    } finally {
        walk.dispose();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitMergeSupport.java

License:Apache License

@NotNull
private ObjectId rebase(@NotNull GitVcsRoot gitRoot, @NotNull Repository db, @NotNull RevCommit srcCommit,
        @NotNull RevCommit dstCommit) throws IOException, MergeFailedException {
    RevWalk walk = new RevWalk(db);
    try {//from  w  ww  . j  a va  2  s.co  m
        RevCommit src = walk.parseCommit(srcCommit);
        RevCommit dst = walk.parseCommit(dstCommit);
        walk.markStart(src);
        walk.markStart(dst);
        walk.setRevFilter(RevFilter.MERGE_BASE);
        RevCommit base = walk.next();

        Map<ObjectId, RevCommit> tree2commit = new HashMap<ObjectId, RevCommit>();
        RevCommit c;

        if (base != null) {
            walk.reset();
            walk.setRevFilter(RevFilter.ALL);
            walk.markStart(dst);
            walk.markUninteresting(base);
            while ((c = walk.next()) != null) {
                tree2commit.put(c.getTree().getId(), c);
            }
        }

        walk.reset();
        walk.markStart(src);
        walk.markUninteresting(dst);
        walk.sort(RevSort.TOPO);
        walk.sort(RevSort.REVERSE);

        Map<RevCommit, RevCommit> orig2rebased = new HashMap<RevCommit, RevCommit>();
        List<RevCommit> toRebase = new ArrayList<RevCommit>();
        while ((c = walk.next()) != null) {
            ObjectId treeId = c.getTree().getId();
            RevCommit existing = tree2commit.get(treeId);
            if (existing != null) {
                orig2rebased.put(c, existing);
            } else {
                if (c.getParentCount() > 1) {
                    throw new MergeFailedException(asList("Rebase of merge commits is not supported"));
                } else {
                    toRebase.add(c);
                }
            }
        }

        orig2rebased.put(toRebase.get(0).getParent(0), dstCommit);
        ObjectInserter inserter = db.newObjectInserter();
        for (RevCommit commit : toRebase) {
            RevCommit p = commit.getParent(0);
            RevCommit b = orig2rebased.get(p);
            ObjectId rebased = rebaseCommit(gitRoot, db, inserter, commit, b);
            orig2rebased.put(commit, walk.parseCommit(rebased));
        }

        return orig2rebased.get(toRebase.get(toRebase.size() - 1));
    } finally {
        walk.release();
    }
}

From source file:org.ajoberstar.reckon.core.git.GitInventorySupplier.java

License:Apache License

private Optional<Version> findParallel(RevWalk walk, RevCommit head, TaggedVersion candidate,
        Set<RevCommit> tagged) {
    try {//  w  w w.j a  va2s  .  co m
        walk.reset();
        walk.setRevFilter(RevFilter.MERGE_BASE);
        walk.markStart(head);
        walk.markStart(candidate.getCommit());

        RevCommit mergeBase = walk.next();

        walk.reset();
        walk.setRevFilter(RevFilter.ALL);
        boolean taggedSinceMergeBase = RevWalkUtils.find(walk, head, mergeBase).stream()
                .filter(tagged::contains).findAny().isPresent();

        if (mergeBase != null && !taggedSinceMergeBase && !mergeBase.equals(head)
                && !mergeBase.equals(candidate.getCommit())) {
            return Optional.of(Versions.getNormal(candidate.getVersion()));
        } else {
            return Optional.empty();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.eclipse.egit.core.RevUtils.java

License:Open Source License

/**
 * Finds and returns instance of common ancestor commit for given to
 * commit's/*w w  w  . j  av  a2s.  c o  m*/
 *
 * @param repo
 * @param commit1
 * @param commit2
 * @return common ancestor for commit1 and commit2 parameters
 * @throws IOException
 */
public static RevCommit getCommonAncestor(Repository repo, AnyObjectId commit1, AnyObjectId commit2)
        throws IOException {
    RevWalk rw = new RevWalk(repo);
    rw.setRevFilter(RevFilter.MERGE_BASE);

    RevCommit srcRev = rw.lookupCommit(commit1);
    RevCommit dstRev = rw.lookupCommit(commit2);

    rw.markStart(dstRev);
    rw.markStart(srcRev);

    RevCommit result;
    result = rw.next();

    return result != null ? result : null;
}