org.eclipse.jgit.revwalk.filter.RevFilter Java Examples

The following examples show how to use org.eclipse.jgit.revwalk.filter.RevFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public ObjectId mergeBase(ObjectId id1, ObjectId id2) throws InterruptedException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk walk = new RevWalk(or)) {
        walk.setRetainBody(false);  // we don't need the body for this computation
        walk.setRevFilter(RevFilter.MERGE_BASE);

        walk.markStart(walk.parseCommit(id1));
        walk.markStart(walk.parseCommit(id2));

        RevCommit base = walk.next();
        if (base==null)     return null;    // no common base
        return base.getId();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #2
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
boolean isRefBehind( Ref behind, Ref tracking ) throws IOException {
  RevWalk walk = new RevWalk( _git.getRepository() );
  try {
    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();
  }
}
 
Example #3
Source File: GetCommonAncestorCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private GitRevisionInfo getSingleBaseCommit (RevWalk walk, List<RevCommit> commits) throws IOException {
    while (commits.size() > 1) {
        walk.reset();
        for (RevCommit c : commits) {
            walk.markStart(walk.parseCommit(c));
        }
        walk.setRevFilter(RevFilter.MERGE_BASE);
        commits.clear();
        for (RevCommit commit = walk.next(); commit != null; commit = walk.next()) {
            commits.add(commit);
        }
    }
    if (commits.isEmpty()) {
        return null;
    } else {
        return getClassFactory().createRevisionInfo(commits.get(0), getRepository());
    }
}
 
Example #4
Source File: MergeBaseCalculator.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * calculate the merge base between two refs
 *
 * @param repoDir           the git directory
 * @param ref1              the ref
 * @param ref2              the other ref
 * @return                  the merge base
 * @throws Exception        throw Exception when error happens
 */
public String calculateMergeBase(File repoDir, String ref1, String ref2) throws Exception {
    try (Git git = Git.open(repoDir);
            ObjectReader reader = git.getRepository().newObjectReader();
            RevWalk rw = new RevWalk(git.getRepository())) {

        RevCommit commit1 = rw.parseCommit(git.getRepository().resolve(ref1));
        RevCommit commit2 = rw.parseCommit(git.getRepository().resolve(ref2));

        rw.setRevFilter(RevFilter.MERGE_BASE);
        rw.markStart(commit1);
        rw.markStart(commit2);

        RevCommit mergeBase = rw.next();

        return mergeBase != null ? mergeBase.name() : "";

    }
}
 
Example #5
Source File: Merger.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Return the merge base of two commits.
 *
 * @param a
 *            the first commit in {@link #sourceObjects}.
 * @param b
 *            the second commit in {@link #sourceObjects}.
 * @return the merge base of two commits
 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
 *             one of the input objects is not a commit.
 * @throws java.io.IOException
 *             objects are missing or multiple merge bases were found.
 * @since 3.0
 */
protected RevCommit getBaseCommit(RevCommit a, RevCommit b)
		throws IncorrectObjectTypeException, IOException {
	walk.reset();
	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()));
	}
	return base;
}
 
Example #6
Source File: GitServiceImpl.java    From apidiff with MIT License 5 votes vote down vote up
@Override
public Integer countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example #7
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public int countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example #8
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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.
 */
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);
  }
}
 
Example #9
Source File: DifferentFiles.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
private RevCommit getMergeBase(RevCommit baseCommit, RevCommit referenceHeadCommit) throws IOException {
    RevWalk walk = new RevWalk(git.getRepository());
    walk.setRevFilter(RevFilter.MERGE_BASE);
    walk.markStart(walk.lookupCommit(baseCommit));
    walk.markStart(walk.lookupCommit(referenceHeadCommit));
    RevCommit commit = walk.next();
    walk.close();
    logger.info("Using merge base of id: " + commit.getId());
    return commit;
}
 
Example #10
Source File: RootCommit.java    From jgitver with Apache License 2.0 5 votes vote down vote up
static RevFilter rootFilter() {
    return new RevFilter() {
        @Override
        public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
            return commit.getParents().length == 0;
        }

        @Override
        public RevFilter clone() {
            return rootFilter();
        }
    };
}
 
Example #11
Source File: GitRevisionInfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void listFiles() throws GitException {
    try (RevWalk revWalk = new RevWalk(repository);
        TreeWalk walk = new TreeWalk(repository)) {
        List<GitFileInfo> result;
        walk.reset();
        walk.setRecursive(true);
        RevCommit parentCommit = null;
        if (revCommit.getParentCount() > 0) {
            for (RevCommit commit : revCommit.getParents()) {
                revWalk.markStart(revWalk.lookupCommit(commit));
            }
            revWalk.setRevFilter(RevFilter.MERGE_BASE);
            Iterator<RevCommit> it = revWalk.iterator();
            if (it.hasNext()) {
                parentCommit = it.next();
            }
            if (parentCommit != null) {
                walk.addTree(parentCommit.getTree().getId());
            }
        }
        walk.addTree(revCommit.getTree().getId());
        walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
        if (parentCommit != null) {
            result = Utils.getDiffEntries(repository, walk, GitClassFactoryImpl.getInstance());
        } else {
            result = new ArrayList<>();
            while (walk.next()) {
                result.add(new GitFileInfo(new File(repository.getWorkTree(), walk.getPathString()), walk.getPathString(), GitFileInfo.Status.ADDED, null, null));
            }
        }
        this.modifiedFiles = result.toArray(new GitFileInfo[result.size()]);
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example #12
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
@Nullable
  public static ObjectId rebase(Repository repository, ObjectId source, ObjectId target, PersonIdent committer) {
  	try (	RevWalk revWalk = new RevWalk(repository);
  			ObjectInserter inserter = repository.newObjectInserter();) {
  		RevCommit sourceCommit = revWalk.parseCommit(source);
  		RevCommit targetCommit = revWalk.parseCommit(target);
  		revWalk.setRevFilter(RevFilter.NO_MERGES);
  		List<RevCommit> commits = RevWalkUtils.find(revWalk, sourceCommit, targetCommit);
  		Collections.reverse(commits);
  		RevCommit headCommit = targetCommit;
  		for (RevCommit commit: commits) {
      		ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
      		merger.setBase(commit.getParent(0));
      		if (merger.merge(headCommit, commit)) {
			if (!headCommit.getTree().getId().equals(merger.getResultTreeId())) {
				if (!commit.getTree().getId().equals(merger.getResultTreeId()) 
						|| !commit.getParent(0).equals(headCommit)) {
			        CommitBuilder commitBuilder = new CommitBuilder();
			        commitBuilder.setAuthor(commit.getAuthorIdent());
			        commitBuilder.setCommitter(committer);
			        commitBuilder.setParentId(headCommit);
			        commitBuilder.setMessage(commit.getFullMessage());
			        commitBuilder.setTreeId(merger.getResultTreeId());
			        headCommit = revWalk.parseCommit(inserter.insert(commitBuilder));
				} else {
					headCommit = commit;
				}
			}
      		} else {
      			return null;
      		}
  		}
  		inserter.flush();
  		return headCommit.copy();
  	} catch (IOException e) {
  		throw new RuntimeException(e);
}
  }
 
Example #13
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
/**
   * @return
   * 			merge base of specified commits, or <tt>null</tt> if two commits do not have related history. In this 
   * 			case, these two commits can not be merged
   */
  @Nullable
  public static ObjectId getMergeBase(Repository repository, ObjectId commitId1, ObjectId commitId2) {
try (RevWalk revWalk = new RevWalk(repository)) {
	revWalk.setRevFilter(RevFilter.MERGE_BASE);
	
	revWalk.markStart(revWalk.parseCommit(commitId1));
	revWalk.markStart(revWalk.parseCommit(commitId2));
	RevCommit mergeBase = revWalk.next();
	return mergeBase!=null?mergeBase.copy():null;
} catch (IOException e) {
	throw new RuntimeException(e);
} 			
  }
 
Example #14
Source File: RevWalk.java    From onedev with MIT License 5 votes vote down vote up
private RevWalk(ObjectReader or, boolean closeReader) {
	reader = or;
	idBuffer = new MutableObjectId();
	objects = new ObjectIdOwnerMap<>();
	roots = new ArrayList<>();
	queue = new DateRevQueue(false);
	pending = new StartGenerator(this);
	sorting = EnumSet.of(RevSort.NONE);
	filter = RevFilter.ALL;
	treeFilter = TreeFilter.ALL;
	this.closeReader = closeReader;
}
 
Example #15
Source File: PendingGenerator.java    From onedev with MIT License 5 votes vote down vote up
PendingGenerator(final RevWalk w, final DateRevQueue p,
		final RevFilter f, final int out) {
	super(w.isFirstParent());
	walker = w;
	pending = p;
	filter = f;
	output = out;
	canDispose = true;
}
 
Example #16
Source File: LogCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Executes the {@code Log} command with all the options and parameters collected by the setter methods (e.g. {@link #add(AnyObjectId)},
 * {@link #not(AnyObjectId)}, ..) of this class. Each instance of this class should only be used for one invocation of the command. Don't call this method
 * twice on an instance.
 *
 * @return an iteration over RevCommits
 * @throws NoHeadException
 *             of the references ref cannot be resolved
 */
@Override
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException {
	checkCallable();
	ArrayList<RevFilter> filters = new ArrayList<RevFilter>();

	if (pathFilters.size() > 0)
		walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF));

	if (msgFilter != null)
		filters.add(msgFilter);
	if (authorFilter != null)
		filters.add(authorFilter);
	if (committerFilter != null)
		filters.add(committerFilter);
	if (sha1Filter != null)
		filters.add(sha1Filter);
	if (dateFilter != null)
		filters.add(dateFilter);
	if (skip > -1)
		filters.add(SkipRevFilter.create(skip));
	if (maxCount > -1)
		filters.add(MaxCountRevFilter.create(maxCount));
	RevFilter filter = null;
	if (filters.size() > 1) {
		filter = AndRevFilter.create(filters);
	} else if (filters.size() == 1) {
		filter = filters.get(0);
	}

	if (filter != null)
		walk.setRevFilter(filter);

	if (!startSpecified) {
		try {
			ObjectId headId = repo.resolve(Constants.HEAD);
			if (headId == null)
				throw new NoHeadException(JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified);
			add(headId);
		} catch (IOException e) {
			// all exceptions thrown by add() shouldn't occur and represent
			// severe low-level exception which are therefore wrapped
			throw new JGitInternalException(JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e);
		}
	}
	setCallable(false);
	return walk;
}
 
Example #17
Source File: TreeRevFilter.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public RevFilter clone() {
	throw new UnsupportedOperationException();
}
 
Example #18
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<PublishingHistoryItem> getPublishingHistory(String siteId, String environment, String pathRegex,
                                                        String publisher, ZonedDateTime fromDate,
                                                        ZonedDateTime toDate, int limit) {
    List<PublishingHistoryItem> toRet = new ArrayList<PublishingHistoryItem>();
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
        Repository publishedRepo = helper.getRepository(siteId, PUBLISHED);
        if (publishedRepo != null) {
            int counter = 0;
            try (Git git = new Git(publishedRepo)) {
                // List all environments
                List<Ref> environments = git.branchList().call();
                for (int i = 0; i < environments.size() && counter < limit; i++) {
                    Ref env = environments.get(i);
                    String environmentGit = env.getName();
                    environmentGit = environmentGit.replace(R_HEADS, "");
                    if ((StringUtils.isBlank(environment) && !StringUtils.equals(MASTER, environmentGit))
                            || StringUtils.equals(environment, environmentGit)) {
                        List<RevFilter> filters = new ArrayList<RevFilter>();
                        if (fromDate != null) {
                            filters.add(CommitTimeRevFilter.after(fromDate.toInstant().toEpochMilli()));
                        }
                        if (toDate != null) {
                            filters.add(CommitTimeRevFilter.before(toDate.toInstant().toEpochMilli()));
                        } else {
                            filters.add(CommitTimeRevFilter.before(ZonedDateTime.now().toInstant().toEpochMilli()));
                        }
                        filters.add(NotRevFilter.create(MessageRevFilter.create("Initial commit.")));
                        if (StringUtils.isNotEmpty(publisher)) {
                            User user = userServiceInternal.getUserByIdOrUsername(-1, publisher);
                            filters.add(AuthorRevFilter.create(helper.getAuthorIdent(user).getName()));
                        }
                        Iterable<RevCommit> branchLog = git.log()
                                .add(env.getObjectId())
                                .setRevFilter(AndRevFilter.create(filters))
                                .call();

                        Iterator<RevCommit> iterator = branchLog.iterator();
                        while (iterator.hasNext() && counter < limit) {
                            RevCommit revCommit = iterator.next();
                            List<String> files = helper.getFilesInCommit(publishedRepo, revCommit);
                            for (int j = 0; j < files.size() && counter < limit; j++) {
                                String file = files.get(j);
                                Path path = Paths.get(file);
                                String fileName = path.getFileName().toString();
                                if (!ArrayUtils.contains(IGNORE_FILES, fileName)) {
                                    boolean addFile = false;
                                    if (StringUtils.isNotEmpty(pathRegex)) {
                                        Pattern pattern = Pattern.compile(pathRegex);
                                        Matcher matcher = pattern.matcher(file);
                                        addFile = matcher.matches();
                                    } else {
                                        addFile = true;
                                    }
                                    if (addFile) {
                                        PublishingHistoryItem phi = new PublishingHistoryItem();
                                        phi.setSiteId(siteId);
                                        phi.setPath(file);
                                        phi.setPublishedDate(
                                                Instant.ofEpochSecond(revCommit.getCommitTime()).atZone(UTC));
                                        phi.setPublisher(revCommit.getAuthorIdent().getName());
                                        phi.setEnvironment(environmentGit.replace(R_HEADS, ""));
                                        toRet.add(phi);
                                        counter++;
                                    }
                                }
                            }
                        }
                    }
                }
                git.close();
                toRet.sort((o1, o2) -> o2.getPublishedDate().compareTo(o1.getPublishedDate()));
            } catch (IOException | GitAPIException | UserNotFoundException | ServiceLayerException e1) {
                logger.error("Error while getting deployment history for site " + siteId, e1);
            }
        }
    } catch (CryptoException e) {
        e.printStackTrace();
    }
    return toRet;
}
 
Example #19
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<DeploymentSyncHistory> getDeploymentHistory(String site, List<String> environmentNames,
                                                        ZonedDateTime fromDate, ZonedDateTime toDate,
                                                        DmFilterWrapper dmFilterWrapper,
                                                        String filterType, int numberOfItems) {
    List<DeploymentSyncHistory> toRet = new ArrayList<DeploymentSyncHistory>();
    Repository publishedRepo = helper.getRepository(site, PUBLISHED);
    int counter = 0;
    try (Git git = new Git(publishedRepo)) {
        // List all environments
        List<Ref> environments = git.branchList().call();
        for (int i = 0; i < environments.size() && counter < numberOfItems; i++) {
            Ref env = environments.get(i);
            String environment = env.getName();
            environment = environment.replace(R_HEADS, "");
            if (environmentNames.contains(environment)) {
                List<RevFilter> filters = new ArrayList<RevFilter>();
                filters.add(CommitTimeRevFilter.after(fromDate.toInstant().toEpochMilli()));
                filters.add(CommitTimeRevFilter.before(toDate.toInstant().toEpochMilli()));
                filters.add(NotRevFilter.create(MessageRevFilter.create("Initial commit.")));

                Iterable<RevCommit> branchLog = git.log()
                        .add(env.getObjectId())
                        .setRevFilter(AndRevFilter.create(filters))
                        .call();

                Iterator<RevCommit> iterator = branchLog.iterator();
                while (iterator.hasNext() && counter < numberOfItems) {
                    RevCommit revCommit = iterator.next();
                    List<String> files = helper.getFilesInCommit(publishedRepo, revCommit);
                    for (int j = 0; j < files.size() && counter < numberOfItems; j++) {
                        String file = files.get(j);
                        Path path = Paths.get(file);
                        String fileName = path.getFileName().toString();
                        if (!ArrayUtils.contains(IGNORE_FILES, fileName)) {
                            if (dmFilterWrapper.accept(site, file, filterType)) {
                                DeploymentSyncHistory dsh = new DeploymentSyncHistory();
                                dsh.setSite(site);
                                dsh.setPath(file);
                                dsh.setSyncDate(
                                        Instant.ofEpochSecond(revCommit.getCommitTime()).atZone(UTC));
                                dsh.setUser(revCommit.getAuthorIdent().getName());
                                dsh.setEnvironment(environment.replace(R_HEADS, ""));
                                toRet.add(dsh);
                                counter++;
                            }
                        }
                    }
                }
            }
        }
        git.close();
        toRet.sort((o1, o2) -> o2.getSyncDate().compareTo(o1.getSyncDate()));
    } catch (IOException | GitAPIException e1) {
        logger.error("Error while getting deployment history for site " + site, e1);
    }
    return toRet;
}
 
Example #20
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 4 votes vote down vote up
@Override
public final RevFilter clone() {
	return this;
}
 
Example #21
Source File: RevWalk.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Determine if a commit is reachable from another commit.
 * <p>
 * A commit <code>base</code> is an ancestor of <code>tip</code> if we
 * can find a path of commits that leads from <code>tip</code> and ends at
 * <code>base</code>.
 * <p>
 * This utility function resets the walker, inserts the two supplied
 * commits, and then executes a walk until an answer can be obtained.
 * Currently allocated RevFlags that have been added to RevCommit instances
 * will be retained through the reset.
 *
 * @param base
 *            commit the caller thinks is reachable from <code>tip</code>.
 * @param tip
 *            commit to start iteration from, and which is most likely a
 *            descendant (child) of <code>base</code>.
 * @return true if there is a path directly from <code>tip</code> to
 *         <code>base</code> (and thus <code>base</code> is fully merged
 *         into <code>tip</code>); false otherwise.
 * @throws org.eclipse.jgit.errors.MissingObjectException
 *             one or more of the next commit's parents are not available
 *             from the object database, but were thought to be candidates
 *             for traversal. This usually indicates a broken link.
 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
 *             one or more of the next commit's parents are not actually
 *             commit objects.
 * @throws java.io.IOException
 *             a pack file or loose object could not be read.
 */
public boolean isMergedInto(RevCommit base, RevCommit tip)
		throws MissingObjectException, IncorrectObjectTypeException,
		IOException {
	final RevFilter oldRF = filter;
	final TreeFilter oldTF = treeFilter;
	try {
		finishDelayedFreeFlags();
		reset(~freeFlags & APP_FLAGS);
		filter = RevFilter.MERGE_BASE;
		treeFilter = TreeFilter.ALL;
		markStart(tip);
		markStart(base);
		RevCommit mergeBase;
		while ((mergeBase = next()) != null) {
			if (References.isSameObject(mergeBase, base)) {
				return true;
			}
		}
		return false;
	} finally {
		filter = oldRF;
		treeFilter = oldTF;
	}
}
 
Example #22
Source File: RecursiveMerger.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Get a single base commit for two given commits. If the two source commits
 * have more than one base commit recursively merge the base commits
 * together until a virtual common base commit has been found.
 *
 * @param a
 *            the first commit to be merged
 * @param b
 *            the second commit to be merged
 * @param callDepth
 *            the callDepth when this method is called recursively
 * @return the merge base of two commits. If a criss-cross merge required a
 *         synthetic merge base this commit is visible only the merger's
 *         RevWalk and will not be in the repository.
 * @throws java.io.IOException
 * @throws IncorrectObjectTypeException
 *             one of the input objects is not a commit.
 * @throws NoMergeBaseException
 *             too many merge bases are found or the computation of a common
 *             merge base failed (e.g. because of a conflict).
 */
protected RevCommit getBaseCommit(RevCommit a, RevCommit b, int callDepth)
		throws IOException {
	ArrayList<RevCommit> baseCommits = new ArrayList<>();
	walk.reset();
	walk.setRevFilter(RevFilter.MERGE_BASE);
	walk.markStart(a);
	walk.markStart(b);
	RevCommit c;
	while ((c = walk.next()) != null)
		baseCommits.add(c);

	if (baseCommits.isEmpty())
		return null;
	if (baseCommits.size() == 1)
		return baseCommits.get(0);
	if (baseCommits.size() >= MAX_BASES)
		throw new NoMergeBaseException(NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES, MessageFormat.format(
				JGitText.get().mergeRecursiveTooManyMergeBasesFor,
				Integer.valueOf(MAX_BASES), a.name(), b.name(),
						Integer.valueOf(baseCommits.size())));

	// We know we have more than one base commit. We have to do merges now
	// to determine a single base commit. We don't want to spoil the current
	// dircache and working tree with the results of this intermediate
	// merges. Therefore set the dircache to a new in-memory dircache and
	// disable that we update the working-tree. We set this back to the
	// original values once a single base commit is created.
	RevCommit currentBase = baseCommits.get(0);
	DirCache oldDircache = dircache;
	boolean oldIncore = inCore;
	WorkingTreeIterator oldWTreeIt = workingTreeIterator;
	workingTreeIterator = null;
	try {
		dircache = DirCache.read(reader, currentBase.getTree());
		inCore = true;

		List<RevCommit> parents = new ArrayList<>();
		parents.add(currentBase);
		for (int commitIdx = 1; commitIdx < baseCommits.size(); commitIdx++) {
			RevCommit nextBase = baseCommits.get(commitIdx);
			if (commitIdx >= MAX_BASES)
				throw new NoMergeBaseException(
						NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES,
						MessageFormat.format(
						JGitText.get().mergeRecursiveTooManyMergeBasesFor,
						Integer.valueOf(MAX_BASES), a.name(), b.name(),
								Integer.valueOf(baseCommits.size())));
			parents.add(nextBase);
			RevCommit bc = getBaseCommit(currentBase, nextBase,
					callDepth + 1);
			AbstractTreeIterator bcTree = (bc == null) ? new EmptyTreeIterator()
					: openTree(bc.getTree());
			if (mergeTrees(bcTree, currentBase.getTree(),
					nextBase.getTree(), true))
				currentBase = createCommitForTree(resultTree, parents);
			else
				throw new NoMergeBaseException(
						NoMergeBaseException.MergeBaseFailureReason.CONFLICTS_DURING_MERGE_BASE_CALCULATION,
						MessageFormat.format(
								JGitText.get().mergeRecursiveConflictsWhenMergingCommonAncestors,
								currentBase.getName(), nextBase.getName()));
		}
	} finally {
		inCore = oldIncore;
		dircache = oldDircache;
		workingTreeIterator = oldWTreeIt;
		toBeCheckedOut.clear();
		toBeDeleted.clear();
		modifiedFiles.clear();
		unmergedPaths.clear();
		mergeResults.clear();
		failingPaths.clear();
	}
	return currentBase;
}
 
Example #23
Source File: SHA1RevFilter.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RevFilter clone() {
	return this;
}
 
Example #24
Source File: SHA1RevFilter.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public static RevFilter create(String pattern) {
	if (pattern.length() == 0)
		throw new IllegalArgumentException();
	return new SHA1RevFilter(pattern);
}
 
Example #25
Source File: CancelRevFilter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public RevFilter clone () {
    return this;
}
 
Example #26
Source File: LogCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void applyCriteria (RevWalk walk, SearchCriteria criteria,
        final RevFlag partOfResultFlag, DiffConfig diffConfig) {
    File[] files = criteria.getFiles();
    if (files.length > 0) {
        Collection<PathFilter> pathFilters = Utils.getPathFilters(getRepository().getWorkTree(), files);
        if (!pathFilters.isEmpty()) {
            if (criteria.isFollow() && pathFilters.size() == 1) {
                walk.setTreeFilter(FollowFilter.create(pathFilters.iterator().next().getPath(), diffConfig));
            } else {
                walk.setTreeFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilterGroup.create(pathFilters)));
            }
        }
    }
    RevFilter filter;
    if (criteria.isIncludeMerges()) {
        filter = RevFilter.ALL;
    } else {
        filter = RevFilter.NO_MERGES;
    }
    filter = AndRevFilter.create(filter, new CancelRevFilter(monitor));
    filter = AndRevFilter.create(filter, new RevFilter() {

        @Override
        public boolean include (RevWalk walker, RevCommit cmit) {
            return cmit.has(partOfResultFlag);
        }

        @Override
        public RevFilter clone () {
            return this;
        }

        @Override
        public boolean requiresCommitBody () {
            return false;
        }
    });

    String username = criteria.getUsername();
    if (username != null && !(username = username.trim()).isEmpty()) {
        filter = AndRevFilter.create(filter, OrRevFilter.create(CommitterRevFilter.create(username), AuthorRevFilter.create(username)));
    }
    String message = criteria.getMessage();
    if (message != null && !(message = message.trim()).isEmpty()) {
        filter = AndRevFilter.create(filter, MessageRevFilter.create(message));
    }
    Date from  = criteria.getFrom();
    Date to  = criteria.getTo();
    if (from != null && to != null) {
        filter = AndRevFilter.create(filter, CommitTimeRevFilter.between(from, to));
    } else if (from != null) {
        filter = AndRevFilter.create(filter, CommitTimeRevFilter.after(from));
    } else if (to != null) {
        filter = AndRevFilter.create(filter, CommitTimeRevFilter.before(to));
    }
    // this must be at the end, limit filter must apply as the last
    if (criteria.getLimit() != -1) {
        filter = AndRevFilter.create(filter, MaxCountRevFilter.create(criteria.getLimit()));
    }
    walk.setRevFilter(filter);
}
 
Example #27
Source File: RevCommitList.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Apply a flag to all commits matching the specified filter.
 * <p>
 * This version allows incremental testing and application, such as from a
 * background thread that needs to periodically halt processing and send
 * updates to the UI.
 *
 * @param matching
 *            the filter to test commits with. If the filter includes a
 *            commit it will have the flag set; if the filter does not
 *            include the commit the flag will be unset.
 * @param flag
 *            the flag to apply (or remove). Applications are responsible
 *            for allocating this flag from the source RevWalk.
 * @param rangeBegin
 *            first commit within the list to begin testing at, inclusive.
 *            Must not be negative, but may be beyond the end of the list.
 * @param rangeEnd
 *            last commit within the list to end testing at, exclusive. If
 *            smaller than or equal to <code>rangeBegin</code> then no
 *            commits will be tested.
 * @throws java.io.IOException
 *             revision filter needed to read additional objects, but an
 *             error occurred while reading the pack files or loose objects
 *             of the repository.
 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
 *             revision filter needed to read additional objects, but an
 *             object was not of the correct type. Repository corruption may
 *             have occurred.
 * @throws org.eclipse.jgit.errors.MissingObjectException
 *             revision filter needed to read additional objects, but an
 *             object that should be present was not found. Repository
 *             corruption may have occurred.
 */
public void applyFlag(final RevFilter matching, final RevFlag flag,
		int rangeBegin, int rangeEnd) throws MissingObjectException,
		IncorrectObjectTypeException, IOException {
	final RevWalk w = flag.getRevWalk();
	rangeEnd = Math.min(rangeEnd, size());
	while (rangeBegin < rangeEnd) {
		int index = rangeBegin;
		Block s = contents;
		while (s.shift > 0) {
			final int i = index >> s.shift;
			index -= i << s.shift;
			s = (Block) s.contents[i];
		}

		while (rangeBegin++ < rangeEnd && index < BLOCK_SIZE) {
			final RevCommit c = (RevCommit) s.contents[index++];
			if (matching.include(w, c))
				c.add(flag);
			else
				c.remove(flag);
		}
	}
}
 
Example #28
Source File: GitServiceImpl.java    From apidiff with MIT License 4 votes vote down vote up
@Override
public final RevFilter clone() {
	return this;
}
 
Example #29
Source File: BitmappedReachabilityChecker.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public final RevFilter clone() {
	throw new UnsupportedOperationException();
}
 
Example #30
Source File: RevCommitList.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Remove the given flag from all commits.
 * <p>
 * This method is actually implemented in terms of:
 * <code>applyFlag(RevFilter.NONE, flag, rangeBegin, rangeEnd)</code>.
 *
 * @param flag
 *            the flag to remove. Applications are responsible for
 *            allocating this flag from the source RevWalk.
 * @param rangeBegin
 *            first commit within the list to begin testing at, inclusive.
 *            Must not be negative, but may be beyond the end of the list.
 * @param rangeEnd
 *            last commit within the list to end testing at, exclusive. If
 *            smaller than or equal to <code>rangeBegin</code> then no
 *            commits will be tested.
 */
public void clearFlag(final RevFlag flag, final int rangeBegin,
		final int rangeEnd) {
	try {
		applyFlag(RevFilter.NONE, flag, rangeBegin, rangeEnd);
	} catch (IOException e) {
		// Never happen. The filter we use does not throw any
		// exceptions, for any reason.
	}
}