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

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

Introduction

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

Prototype

public void setRetainBody(boolean retain) 

Source Link

Document

Set whether or not the body of a commit or tag is retained.

Usage

From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java

License:Apache License

@Override
public boolean hasChangedSince(final String modulePath, final List<String> childModules,
        final Collection<ProposedTag> tags) throws SCMException {
    final RevWalk walk = new RevWalk(getGit().getRepository());
    try {//from www .  j  a va 2  s  .  co 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.github.pascalgn.maven.properties.GitProperties.java

License:Apache License

private void addProperties(Map<String, String> map) throws IOException {
    Repository repository = new FileRepositoryBuilder().setWorkTree(new File(".")).readEnvironment()
            .findGitDir().setMustExist(true).build();
    logger.debug("Using git repository: " + repository.getDirectory());

    ObjectId head = repository.resolve("HEAD");
    if (head == null) {
        throw new IllegalStateException("No such revision: HEAD");
    }/*ww w.  ja v  a 2 s.c o m*/

    String branch = nullToEmpty(repository.getBranch());
    map.put("git.branch", branch);

    String commitId = head.name();
    map.put("git.commit.id", commitId);

    String commitIdAbbrev = repository.newObjectReader().abbreviate(head).name();
    map.put("git.commit.id.abbrev", commitIdAbbrev);

    RevWalk walk = new RevWalk(repository);
    walk.setRetainBody(false);
    RevCommit headCommit = walk.parseCommit(head);
    int count = RevWalkUtils.count(walk, headCommit, null);
    map.put("git.count", Integer.toString(count));

    String color = commitId.substring(0, 6);
    map.put("git.commit.color.value", color);
    map.put("git.commit.color.name", ColorHelper.getColorName(color));
    map.put("git.commit.color.lightness", Integer.toString(ColorHelper.getLightness(color)));
    map.put("git.commit.color.foreground", ColorHelper.getForeground(color));

    map.put("git.build.datetime.simple", getFormattedDate());
}

From source file:com.google.gerrit.httpd.rpc.changedetail.IncludedInDetailFactory.java

License:Apache License

@Override
public IncludedInDetail call()
        throws OrmException, NoSuchChangeException, IOException, InvalidRevisionException {
    control = changeControlFactory.validateFor(changeId);

    final PatchSet patch = db.patchSets().get(control.getChange().currentPatchSetId());
    final Repository repo = repoManager.openRepository(control.getProject().getNameKey());
    try {/*from   w  ww.  j av a2s .  c  o m*/
        final RevWalk rw = new RevWalk(repo);
        try {
            rw.setRetainBody(false);

            final RevCommit rev;
            try {
                rev = rw.parseCommit(ObjectId.fromString(patch.getRevision().get()));
            } catch (IncorrectObjectTypeException err) {
                throw new InvalidRevisionException();
            } catch (MissingObjectException err) {
                throw new InvalidRevisionException();
            }

            detail = new IncludedInDetail();
            detail.setBranches(includedIn(repo, rw, rev, Constants.R_HEADS));
            detail.setTags(includedIn(repo, rw, rev, Constants.R_TAGS));

            return detail;
        } finally {
            rw.release();
        }
    } finally {
        repo.close();
    }
}

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

License:Apache License

void prepare(TagMatcher m) {
    @SuppressWarnings("resource")
    RevWalk rw = null;/*from   w  w  w  .  j  ava 2 s . c om*/
    try {
        for (Ref currentRef : m.include) {
            if (currentRef.isSymbolic()) {
                continue;
            }
            if (currentRef.getObjectId() == null) {
                continue;
            }

            CachedRef savedRef = refs.get(currentRef.getName());
            if (savedRef == null) {
                // If the reference isn't known to the set, return null
                // and force the caller to rebuild the set in a new copy.
                m.newRefs.add(currentRef);
                continue;
            }

            // The reference has not been moved. It can be used as-is.
            ObjectId savedObjectId = savedRef.get();
            if (currentRef.getObjectId().equals(savedObjectId)) {
                m.mask.set(savedRef.flag);
                continue;
            }

            // Check on-the-fly to see if the branch still reaches the tag.
            // This is very likely for a branch that fast-forwarded.
            try {
                if (rw == null) {
                    rw = new RevWalk(m.db);
                    rw.setRetainBody(false);
                }

                RevCommit savedCommit = rw.parseCommit(savedObjectId);
                RevCommit currentCommit = rw.parseCommit(currentRef.getObjectId());
                if (rw.isMergedInto(savedCommit, currentCommit)) {
                    // Fast-forward. Safely update the reference in-place.
                    savedRef.compareAndSet(savedObjectId, currentRef.getObjectId());
                    m.mask.set(savedRef.flag);
                    continue;
                }

                // The branch rewound. Walk the list of commits removed from
                // the reference. If any matches to a tag, this has to be removed.
                boolean err = false;
                rw.reset();
                rw.markStart(savedCommit);
                rw.markUninteresting(currentCommit);
                rw.sort(RevSort.TOPO, true);
                RevCommit c;
                while ((c = rw.next()) != null) {
                    Tag tag = tags.get(c);
                    if (tag != null && tag.refFlags.get(savedRef.flag)) {
                        m.lostRefs.add(new TagMatcher.LostRef(tag, savedRef.flag));
                        err = true;
                    }
                }
                if (!err) {
                    // All of the tags are still reachable. Update in-place.
                    savedRef.compareAndSet(savedObjectId, currentRef.getObjectId());
                    m.mask.set(savedRef.flag);
                }

            } catch (IOException err) {
                // Defer a cache update until later. No conclusion can be made
                // based on an exception reading from the repository storage.
                log.warn("Error checking tags of " + projectName, err);
            }
        }
    } finally {
        if (rw != null) {
            rw.close();
        }
    }
}

From source file:com.mooregreatsoftware.gitprocess.lib.Branch.java

License:Apache License

public boolean contains(@NonNull ObjectId oid) {
    LOG.debug("{}.contains({})", this, oid.abbreviate(7).name());
    return Try.of(() -> {
        final RevWalk walk = new RevWalk(gitLib.repository());
        try {/*from   w  w w.  j  ava 2  s . co  m*/
            walk.setRetainBody(false);
            final RevCommit topOfThisBranch = walk.parseCommit(objectId());
            walk.markStart(topOfThisBranch);
            return StreamSupport.stream(walk.spliterator(), false)
                    .anyMatch(commit -> oid.equals(commit.getId()));
        } finally {
            walk.dispose();
        }
    }).getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new);
}

From source file:com.mycila.maven.plugin.license.git.GitLookup.java

License:Apache License

/**
 * Returns the year of the last change of the given {@code file} based on the history of the present git branch. The
 * year is taken either from the committer date or from the author identity depending on how {@link #dateSource} was
 * initialized./* ww  w. j a  v  a 2 s  .  c o  m*/
 * <p>
 * See also the note on time zones in {@link #GitLookup(File, DateSource, TimeZone, int)}.
 *
 * @param file
 * @return
 * @throws NoHeadException
 * @throws GitAPIException
 * @throws IOException
 */
public int getYearOfLastChange(File file) throws NoHeadException, GitAPIException, IOException {
    String repoRelativePath = pathResolver.relativize(file);

    Status status = new Git(repository).status().addPath(repoRelativePath).call();
    if (!status.isClean()) {
        /* Return the current year for modified and unstaged files */
        return toYear(System.currentTimeMillis(), timeZone != null ? timeZone : DEFAULT_ZONE);
    }

    RevWalk walk = new RevWalk(repository);
    walk.markStart(walk.parseCommit(repository.resolve(Constants.HEAD)));
    walk.setTreeFilter(AndTreeFilter.create(PathFilter.create(repoRelativePath), TreeFilter.ANY_DIFF));
    walk.setRevFilter(MaxCountRevFilter.create(checkCommitsCount));
    walk.setRetainBody(false);

    int commitYear = 0;
    for (RevCommit commit : walk) {
        int y;
        switch (dateSource) {
        case COMMITER:
            int epochSeconds = commit.getCommitTime();
            y = toYear(epochSeconds * 1000L, timeZone);
            break;
        case AUTHOR:
            PersonIdent id = commit.getAuthorIdent();
            Date date = id.getWhen();
            y = toYear(date.getTime(), id.getTimeZone());
            break;
        default:
            throw new IllegalStateException("Unexpected " + DateSource.class.getName() + " " + dateSource);
        }
        if (y > commitYear) {
            commitYear = y;
        }
    }
    walk.dispose();
    return commitYear;
}

From source file:de.codesourcery.gittimelapse.GitHelper.java

License:Apache License

protected void visitCommits(File localPath, boolean retainCommitBody, ObjectId startCommit, ICommitVisitor func)
        throws RevisionSyntaxException, AmbiguousObjectException, IncorrectObjectTypeException, IOException {
    if (startCommit == null) {
        throw new RuntimeException("startCommit must not be NULL");
    }//from w  ww .j a v  a  2s. co  m

    final RevWalk walk = new RevWalk(repository);
    try {
        final String path = stripRepoBaseDir(localPath);
        final PathFilter filter = createPathFilter(path);
        TreeFilter group = PathFilterGroup.create(Collections.singleton(filter));

        walk.setTreeFilter(group);
        walk.setRevFilter(new RevFilter() {

            @Override
            public boolean include(RevWalk walker, RevCommit cmit) throws StopWalkException,
                    MissingObjectException, IncorrectObjectTypeException, IOException {
                return commitChangesFile(path, filter, cmit);
            }

            @Override
            public RevFilter clone() {
                return this;
            }
        });
        walk.setRetainBody(retainCommitBody);

        final RevCommit startingCommit = walk.parseCommit(startCommit);
        walk.markStart(startingCommit);
        visitCommits(walk, func);
    } finally {
        walk.dispose();
    }
}

From source file:de.codesourcery.gittimelapse.GitHelper.java

License:Apache License

public void visitSingleCommit(ObjectId id, ICommitVisitor visitor) throws IOException {

    if (id == null) {
        throw new RuntimeException("commit ID must not be NULL");
    }// w ww. j  av a 2  s. c om

    final RevWalk walk = new RevWalk(repository);
    try {
        walk.setRetainBody(true);

        final RevCommit startingCommit = walk.parseCommit(id);
        walk.markStart(startingCommit);

        RevCommit current = walk.next();
        visitor.visit(current);
    } finally {
        walk.dispose();
    }
}

From source file:jenkins.plugins.git.AbstractGitSCMSource.java

License:Open Source License

@NonNull
@Override/*from ww  w.  j a v a2 s .co  m*/
protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    String cacheEntry = getCacheEntry();
    Lock cacheLock = getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
        File cacheDir = getCacheDir(cacheEntry);
        Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir);
        GitClient client = git.getClient();
        client.addDefaultCredentials(getCredentials());
        if (!client.hasGitRepo()) {
            listener.getLogger().println("Creating git repository in " + cacheDir);
            client.init();
        }
        String remoteName = getRemoteName();
        listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
        client.setRemoteUrl(remoteName, getRemote());
        listener.getLogger().println("Fetching " + remoteName + "...");
        List<RefSpec> refSpecs = getRefSpecs();
        client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
        listener.getLogger().println("Pruning stale remotes...");
        final Repository repository = client.getRepository();
        try {
            client.prune(new RemoteConfig(repository.getConfig(), remoteName));
        } catch (UnsupportedOperationException e) {
            e.printStackTrace(listener.error("Could not prune stale remotes"));
        } catch (URISyntaxException e) {
            e.printStackTrace(listener.error("Could not prune stale remotes"));
        }
        listener.getLogger().println("Getting remote branches...");
        SCMSourceCriteria branchCriteria = getCriteria();
        RevWalk walk = new RevWalk(repository);
        try {
            walk.setRetainBody(false);
            for (Branch b : client.getRemoteBranches()) {
                if (!b.getName().startsWith(remoteName + "/")) {
                    continue;
                }
                final String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
                listener.getLogger().println("Checking branch " + branchName);
                if (isExcluded(branchName)) {
                    continue;
                }
                if (branchCriteria != null) {
                    RevCommit commit = walk.parseCommit(b.getSHA1());
                    final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime());
                    final RevTree tree = commit.getTree();
                    SCMSourceCriteria.Probe probe = new SCMSourceCriteria.Probe() {
                        @Override
                        public String name() {
                            return branchName;
                        }

                        @Override
                        public long lastModified() {
                            return lastModified;
                        }

                        @Override
                        public boolean exists(@NonNull String path) throws IOException {
                            TreeWalk tw = TreeWalk.forPath(repository, path, tree);
                            try {
                                return tw != null;
                            } finally {
                                if (tw != null) {
                                    tw.release();
                                }
                            }
                        }
                    };
                    if (branchCriteria.isHead(probe, listener)) {
                        listener.getLogger().println("Met criteria");
                    } else {
                        listener.getLogger().println("Does not meet criteria");
                        continue;
                    }
                }
                SCMHead head = new SCMHead(branchName);
                SCMRevision hash = new SCMRevisionImpl(head, b.getSHA1String());
                observer.observe(head, hash);
                if (!observer.isObserving()) {
                    return;
                }
            }
        } finally {
            walk.dispose();
        }

        listener.getLogger().println("Done.");
    } finally {
        cacheLock.unlock();
    }
}

From source file:org.eclipse.egit.ui.internal.commit.CommitSelectionDialog.java

License:Open Source License

protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter,
        IProgressMonitor progressMonitor) throws CoreException {
    String pattern = itemsFilter.getPattern();
    Repository[] repositories = getRepositories();
    progressMonitor.beginTask(UIText.CommitSelectionDialog_TaskSearching, repositories.length);
    for (Repository repository : repositories) {
        try {/*from ww  w. j  a v a 2  s  .  co  m*/
            ObjectId commitId;
            if (ObjectId.isId(pattern))
                commitId = ObjectId.fromString(pattern);
            else
                commitId = repository.resolve(itemsFilter.getPattern());
            if (commitId != null) {
                RevWalk walk = new RevWalk(repository);
                walk.setRetainBody(true);
                RevCommit commit = walk.parseCommit(commitId);
                contentProvider.add(new RepositoryCommit(repository, commit), itemsFilter);
            }
        } catch (RevisionSyntaxException ignored) {
            // Ignore and advance
        } catch (IOException ignored) {
            // Ignore and advance
        }
        progressMonitor.worked(1);
    }
}