Example usage for org.eclipse.jgit.treewalk TreeWalk getRawMode

List of usage examples for org.eclipse.jgit.treewalk TreeWalk getRawMode

Introduction

In this page you can find the example usage for org.eclipse.jgit.treewalk TreeWalk getRawMode.

Prototype

public int getRawMode(int nth) 

Source Link

Document

Obtain the raw org.eclipse.jgit.lib.FileMode bits for the current entry.

Usage

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

License:Apache License

/**
 * Returns the list of files changed in a specified commit. If the
 * repository does not exist or is empty, an empty list is returned.
 *
 * @param repository/*from  w w w  .  j  ava 2s  . c  o  m*/
 * @param commit
 *            if null, HEAD is assumed.
 * @param calculateDiffStat
 *            if true, each PathChangeModel will have insertions/deletions
 * @return list of files changed in a commit
 */
public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit,
        boolean calculateDiffStat) {
    List<PathChangeModel> list = new ArrayList<PathChangeModel>();
    if (!hasCommits(repository)) {
        return list;
    }
    RevWalk rw = new RevWalk(repository);
    try {
        if (commit == null) {
            ObjectId object = getDefaultBranch(repository);
            commit = rw.parseCommit(object);
        }

        if (commit.getParentCount() == 0) {
            TreeWalk tw = new TreeWalk(repository);
            tw.reset();
            tw.setRecursive(true);
            tw.addTree(commit.getTree());
            while (tw.next()) {
                long size = 0;
                FilestoreModel filestoreItem = null;
                ObjectId objectId = tw.getObjectId(0);

                try {
                    if (!tw.isSubtree() && (tw.getFileMode(0) != FileMode.GITLINK)) {

                        size = tw.getObjectReader().getObjectSize(objectId, Constants.OBJ_BLOB);

                        if (isPossibleFilestoreItem(size)) {
                            filestoreItem = getFilestoreItem(tw.getObjectReader().open(objectId));
                        }
                    }
                } catch (Throwable t) {
                    error(t, null, "failed to retrieve blob size for " + tw.getPathString());
                }

                list.add(new PathChangeModel(tw.getPathString(), tw.getPathString(), filestoreItem, size,
                        tw.getRawMode(0), objectId.getName(), commit.getId().getName(), ChangeType.ADD));
            }
            tw.close();
        } else {
            RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
            DiffStatFormatter df = new DiffStatFormatter(commit.getName(), repository);
            df.setRepository(repository);
            df.setDiffComparator(RawTextComparator.DEFAULT);
            df.setDetectRenames(true);
            List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
            for (DiffEntry diff : diffs) {
                // create the path change model
                PathChangeModel pcm = PathChangeModel.from(diff, commit.getName(), repository);

                if (calculateDiffStat) {
                    // update file diffstats
                    df.format(diff);
                    PathChangeModel pathStat = df.getDiffStat().getPath(pcm.path);
                    if (pathStat != null) {
                        pcm.insertions = pathStat.insertions;
                        pcm.deletions = pathStat.deletions;
                    }
                }
                list.add(pcm);
            }
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to determine files in commit!");
    } finally {
        rw.dispose();
    }
    return list;
}

From source file:com.gitblit.wicket.panels.HistoryPanel.java

License:Apache License

public HistoryPanel(String wicketId, final String repositoryName, final String objectId, final String path,
        Repository r, int limit, int pageOffset, boolean showRemoteRefs) {
    super(wicketId);
    boolean pageResults = limit <= 0;
    int itemsPerPage = app().settings().getInteger(Keys.web.itemsPerPage, 50);
    if (itemsPerPage <= 1) {
        itemsPerPage = 50;/*from w w w  . j ava2 s . c  o  m*/
    }

    RevCommit commit = JGitUtils.getCommit(r, objectId);
    PathModel matchingPath = null;
    Map<String, SubmoduleModel> submodules = new HashMap<String, SubmoduleModel>();

    if (commit == null) {
        // commit missing
        String msg = MessageFormat.format("Failed to find history of **{0}** *{1}*", path, objectId);
        logger().error(msg + " " + repositoryName);
        add(new Label("commitHeader", MarkdownUtils.transformMarkdown(msg)).setEscapeModelStrings(false));
        add(new Label("breadcrumbs"));
    } else {
        // commit found
        List<PathChangeModel> paths = JGitUtils.getFilesInCommit(r, commit);
        add(new CommitHeaderPanel("commitHeader", repositoryName, commit));
        add(new PathBreadcrumbsPanel("breadcrumbs", repositoryName, path, objectId));
        for (SubmoduleModel model : JGitUtils.getSubmodules(r, commit.getTree())) {
            submodules.put(model.path, model);
        }

        for (PathModel p : paths) {
            if (p.path.equals(path)) {
                matchingPath = p;
                break;
            }
        }
        if (matchingPath == null) {
            // path not in commit
            // manually locate path in tree
            TreeWalk tw = new TreeWalk(r);
            tw.reset();
            tw.setRecursive(true);
            try {
                tw.addTree(commit.getTree());
                tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
                while (tw.next()) {
                    if (tw.getPathString().equals(path)) {
                        matchingPath = new PathChangeModel(tw.getPathString(), tw.getPathString(), null, 0,
                                tw.getRawMode(0), tw.getObjectId(0).getName(), commit.getId().getName(),
                                ChangeType.MODIFY);
                    }
                }
            } catch (Exception e) {
            } finally {
                tw.close();
            }
        }
    }

    final boolean isTree = matchingPath == null ? true : matchingPath.isTree();
    final boolean isSubmodule = matchingPath == null ? false : matchingPath.isSubmodule();

    // submodule
    final String submodulePath;
    final boolean hasSubmodule;
    if (isSubmodule) {
        SubmoduleModel submodule = getSubmodule(submodules, repositoryName,
                matchingPath == null ? null : matchingPath.path);
        submodulePath = submodule.gitblitPath;
        hasSubmodule = submodule.hasSubmodule;
    } else {
        submodulePath = "";
        hasSubmodule = false;
    }

    final Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(r, showRemoteRefs);
    List<RevCommit> commits;
    if (pageResults) {
        // Paging result set
        commits = JGitUtils.getRevLog(r, objectId, path, pageOffset * itemsPerPage, itemsPerPage);
    } else {
        // Fixed size result set
        commits = JGitUtils.getRevLog(r, objectId, path, 0, limit);
    }

    // inaccurate way to determine if there are more commits.
    // works unless commits.size() represents the exact end.
    hasMore = commits.size() >= itemsPerPage;

    final int hashLen = app().settings().getInteger(Keys.web.shortCommitIdLength, 6);
    ListDataProvider<RevCommit> dp = new ListDataProvider<RevCommit>(commits);
    DataView<RevCommit> logView = new DataView<RevCommit>("commit", dp) {
        private static final long serialVersionUID = 1L;
        int counter;

        @Override
        public void populateItem(final Item<RevCommit> item) {
            final RevCommit entry = item.getModelObject();
            final Date date = JGitUtils.getAuthorDate(entry);

            item.add(WicketUtils.createDateLabel("commitDate", date, getTimeZone(), getTimeUtils()));

            // author search link
            String author = entry.getAuthorIdent().getName();
            LinkPanel authorLink = new LinkPanel("commitAuthor", "list", author, GitSearchPage.class,
                    WicketUtils.newSearchParameter(repositoryName, null, author, Constants.SearchType.AUTHOR));
            setPersonSearchTooltip(authorLink, author, Constants.SearchType.AUTHOR);
            item.add(authorLink);

            // merge icon
            if (entry.getParentCount() > 1) {
                item.add(WicketUtils.newImage("commitIcon", "commit_merge_16x16.png"));
            } else {
                item.add(WicketUtils.newBlankImage("commitIcon"));
            }

            String shortMessage = entry.getShortMessage();
            String trimmedMessage = shortMessage;
            if (allRefs.containsKey(entry.getId())) {
                trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG_REFS);
            } else {
                trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG);
            }
            LinkPanel shortlog = new LinkPanel("commitShortMessage", "list subject", trimmedMessage,
                    CommitPage.class, WicketUtils.newObjectParameter(repositoryName, entry.getName()));
            if (!shortMessage.equals(trimmedMessage)) {
                WicketUtils.setHtmlTooltip(shortlog, shortMessage);
            }
            item.add(shortlog);

            item.add(new RefsPanel("commitRefs", repositoryName, entry, allRefs));

            if (isTree) {
                // tree
                item.add(new Label("hashLabel", getString("gb.tree") + "@"));
                LinkPanel commitHash = new LinkPanel("hashLink", null, entry.getName().substring(0, hashLen),
                        TreePage.class, WicketUtils.newObjectParameter(repositoryName, entry.getName()));
                WicketUtils.setCssClass(commitHash, "shortsha1");
                WicketUtils.setHtmlTooltip(commitHash, entry.getName());
                item.add(commitHash);

                Fragment links = new Fragment("historyLinks", "treeLinks", HistoryPanel.this);
                links.add(new BookmarkablePageLink<Void>("commitdiff", CommitDiffPage.class,
                        WicketUtils.newObjectParameter(repositoryName, entry.getName())));
                item.add(links);
            } else if (isSubmodule) {
                // submodule
                Repository repository = app().repositories().getRepository(repositoryName);
                String submoduleId = JGitUtils.getSubmoduleCommitId(repository, path, entry);
                repository.close();
                if (StringUtils.isEmpty(submoduleId)) {
                    // not a submodule at this commit, just a matching path
                    item.add(new Label("hashLabel").setVisible(false));
                    item.add(new Label("hashLink").setVisible(false));
                } else {
                    // really a submodule
                    item.add(new Label("hashLabel", submodulePath + "@"));
                    LinkPanel commitHash = new LinkPanel("hashLink", null, submoduleId.substring(0, hashLen),
                            TreePage.class, WicketUtils.newObjectParameter(submodulePath, submoduleId));
                    WicketUtils.setCssClass(commitHash, "shortsha1");
                    WicketUtils.setHtmlTooltip(commitHash, submoduleId);
                    item.add(commitHash.setEnabled(hasSubmodule));
                }
                Fragment links = new Fragment("historyLinks", "treeLinks", HistoryPanel.this);
                links.add(new BookmarkablePageLink<Void>("commitdiff", CommitDiffPage.class,
                        WicketUtils.newObjectParameter(repositoryName, entry.getName())));
                item.add(links);
            } else {
                // commit
                item.add(new Label("hashLabel", getString("gb.blob") + "@"));
                LinkPanel commitHash = new LinkPanel("hashLink", null, entry.getName().substring(0, hashLen),
                        BlobPage.class, WicketUtils.newPathParameter(repositoryName, entry.getName(), path));
                WicketUtils.setCssClass(commitHash, "sha1");
                WicketUtils.setHtmlTooltip(commitHash, entry.getName());
                item.add(commitHash);

                Fragment links = new Fragment("historyLinks", "blobLinks", HistoryPanel.this);
                links.add(new BookmarkablePageLink<Void>("commitdiff", CommitDiffPage.class,
                        WicketUtils.newObjectParameter(repositoryName, entry.getName())));
                links.add(new BookmarkablePageLink<Void>("difftocurrent", BlobDiffPage.class,
                        WicketUtils.newBlobDiffParameter(repositoryName, entry.getName(), objectId, path))
                                .setEnabled(counter > 0));
                item.add(links);
            }

            WicketUtils.setAlternatingBackground(item, counter);
            counter++;
        }
    };
    add(logView);

    // determine to show pager, more, or neither
    if (limit <= 0) {
        // no display limit
        add(new Label("moreHistory", "").setVisible(false));
    } else {
        if (pageResults) {
            // paging
            add(new Label("moreHistory", "").setVisible(false));
        } else {
            // more
            if (commits.size() == limit) {
                // show more
                add(new LinkPanel("moreHistory", "link", new StringResourceModel("gb.moreHistory", this, null),
                        HistoryPage.class, WicketUtils.newPathParameter(repositoryName, objectId, path)));
            } else {
                // no more
                add(new Label("moreHistory", "").setVisible(false));
            }
        }
    }
}

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

License:Apache License

void load() throws IOException {
    Project.NameKey project = branch.getParentKey();
    logDebug("Loading .gitmodules of {} for project {}", branch, project);
    try {//from ww w  .j  av  a  2s.  co  m
        orm.openRepo(project, false);
    } catch (NoSuchProjectException e) {
        throw new IOException(e);
    }
    OpenRepo or = orm.getRepo(project);

    ObjectId id = or.repo.resolve(branch.get());
    if (id == null) {
        throw new IOException("Cannot open branch " + branch.get());
    }
    RevCommit commit = or.rw.parseCommit(id);

    TreeWalk tw = TreeWalk.forPath(or.repo, GIT_MODULES, commit.getTree());
    if (tw == null || (tw.getRawMode(0) & FileMode.TYPE_MASK) != FileMode.TYPE_FILE) {
        return;
    }
    try {
        BlobBasedConfig bbc = new BlobBasedConfig(null, or.repo, commit, GIT_MODULES);
        subscriptions = subSecParserFactory.create(bbc, thisServer, branch).parseAllSections();
    } catch (ConfigInvalidException e) {
        throw new IOException("Could not read .gitmodule file of super project: " + branch.getParentKey(), e);
    }
}

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

License:Apache License

void updateSubmoduleSubscriptions(ReviewDb db, Branch.NameKey destBranch) throws SubmoduleException {
    if (urlProvider.get() == null) {
        logAndThrowSubmoduleException("Cannot establish canonical web url used "
                + "to access gerrit. It should be provided in gerrit.config file.");
    }// ww  w .ja v  a  2 s.  co m
    try (Repository repo = repoManager.openRepository(destBranch.getParentKey());
            RevWalk rw = new RevWalk(repo)) {

        ObjectId id = repo.resolve(destBranch.get());
        if (id == null) {
            logAndThrowSubmoduleException("Cannot resolve submodule destination branch " + destBranch);
        }
        RevCommit commit = rw.parseCommit(id);

        Set<SubmoduleSubscription> oldSubscriptions = Sets
                .newHashSet(db.submoduleSubscriptions().bySuperProject(destBranch));

        Set<SubmoduleSubscription> newSubscriptions;
        TreeWalk tw = TreeWalk.forPath(repo, GIT_MODULES, commit.getTree());
        if (tw != null && (FileMode.REGULAR_FILE.equals(tw.getRawMode(0))
                || FileMode.EXECUTABLE_FILE.equals(tw.getRawMode(0)))) {
            BlobBasedConfig bbc = new BlobBasedConfig(null, repo, commit, GIT_MODULES);

            String thisServer = new URI(urlProvider.get()).getHost();

            newSubscriptions = subSecParserFactory.create(bbc, thisServer, destBranch).parseAllSections();
        } else {
            newSubscriptions = Collections.emptySet();
        }

        Set<SubmoduleSubscription> alreadySubscribeds = new HashSet<>();
        for (SubmoduleSubscription s : newSubscriptions) {
            if (oldSubscriptions.contains(s)) {
                alreadySubscribeds.add(s);
            }
        }

        oldSubscriptions.removeAll(newSubscriptions);
        newSubscriptions.removeAll(alreadySubscribeds);

        if (!oldSubscriptions.isEmpty()) {
            db.submoduleSubscriptions().delete(oldSubscriptions);
        }
        if (!newSubscriptions.isEmpty()) {
            db.submoduleSubscriptions().insert(newSubscriptions);
        }

    } catch (OrmException e) {
        logAndThrowSubmoduleException(
                "Database problem at update of subscriptions table from " + GIT_MODULES + " file.", e);
    } catch (ConfigInvalidException e) {
        logAndThrowSubmoduleException(
                "Problem at update of subscriptions table: " + GIT_MODULES + " config file is invalid.", e);
    } catch (IOException e) {
        logAndThrowSubmoduleException("Problem at update of subscriptions table from " + GIT_MODULES + ".", e);
    } catch (URISyntaxException e) {
        logAndThrowSubmoduleException("Incorrect gerrit canonical web url provided in gerrit.config file.", e);
    }
}

From source file:com.google.gitiles.blame.BlameServlet.java

License:Open Source License

private static ObjectId resolveBlob(GitilesView view, RevWalk rw, ObjectId commitId) throws IOException {
    try {//from  w  w w .jav  a2 s  .co  m
        if (commitId == null || Strings.isNullOrEmpty(view.getPathPart())) {
            return null;
        }
        RevTree tree = rw.parseTree(commitId);
        TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), view.getPathPart(), tree);
        if (tw == null || (tw.getRawMode(0) & FileMode.TYPE_FILE) == 0) {
            return null;
        }
        return tw.getObjectId(0);
    } catch (IncorrectObjectTypeException e) {
        return null;
    }
}

From source file:com.google.gitiles.BlameServlet.java

License:Open Source License

private static ObjectId resolveBlob(GitilesView view, RevWalk rw, RevCommit commit) throws IOException {
    try {//from   ww  w  .j a  v a  2  s . c  o  m
        TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), view.getPathPart(), commit.getTree());
        if ((tw.getRawMode(0) & FileMode.TYPE_FILE) == 0) {
            return null;
        }
        return tw.getObjectId(0);
    } catch (IncorrectObjectTypeException e) {
        return null;
    }
}

From source file:com.google.gitiles.doc.DocServlet.java

License:Open Source License

private static SourceFile findFile(RevWalk rw, RevTree root, String path) throws IOException {
    if (Strings.isNullOrEmpty(path)) {
        path = INDEX_MD;//  www  . j a  v a 2s  .  co m
    }

    ObjectReader reader = rw.getObjectReader();
    TreeWalk tw = TreeWalk.forPath(reader, path, root);
    if (tw == null) {
        return null;
    }
    if ((tw.getRawMode(0) & TYPE_MASK) == TYPE_TREE) {
        if (findIndexFile(tw)) {
            path = tw.getPathString();
        } else {
            return null;
        }
    }
    if ((tw.getRawMode(0) & TYPE_MASK) == TYPE_FILE) {
        if (!path.endsWith(".md")) {
            return null;
        }
        return new SourceFile(path, tw.getObjectId(0));
    }
    return null;
}

From source file:com.google.gitiles.doc.DocServlet.java

License:Open Source License

private static boolean findIndexFile(TreeWalk tw) throws IOException {
    tw.enterSubtree();//w ww .  j  a va  2  s. c o  m
    while (tw.next()) {
        if ((tw.getRawMode(0) & TYPE_MASK) == TYPE_FILE && INDEX_MD.equals(tw.getNameString())) {
            return true;
        }
    }
    return false;
}

From source file:com.google.gitiles.ReadmeHelper.java

License:Open Source License

void considerEntry(TreeWalk tw) {
    if (render && FileMode.REGULAR_FILE.equals(tw.getRawMode(0)) && isReadmeFile(tw.getNameString())) {
        readmePath = tw.getPathString();
        readmeId = tw.getObjectId(0);//from www.ja  v  a2  s . c om
    }
}

From source file:com.googlesource.gerrit.plugins.findowners.OwnersValidator.java

License:Apache License

private static boolean isFile(TreeWalk tw) {
    return FileMode.EXECUTABLE_FILE.equals(tw.getRawMode(0)) || FileMode.REGULAR_FILE.equals(tw.getRawMode(0));
}