List of usage examples for org.eclipse.jgit.treewalk.filter PathFilterGroup createFromStrings
public static TreeFilter createFromStrings(String... paths)
From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java
License:Apache License
public boolean isTracked(String path) throws IOException { ObjectId objectId = localRepo.resolve(Constants.HEAD); RevTree tree;//w w w. j ava 2s. co m RevWalk walk = null; if (objectId != null) { walk = new RevWalk(localRepo); tree = walk.parseTree(objectId); } else { tree = null; } try (TreeWalk treeWalk = new TreeWalk(localRepo)) { treeWalk.setRecursive(true); if (tree != null) treeWalk.addTree(tree); else treeWalk.addTree(new EmptyTreeIterator()); treeWalk.addTree(new DirCacheIterator(localRepo.readDirCache())); treeWalk.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); return treeWalk.next(); } finally { if (walk != null) walk.close(); } }
From source file:com.gitblit.utils.IssueUtils.java
License:Apache License
/** * Returns all the issues in the repository. Querying issues from the * repository requires deserializing all changes for all issues. This is an * expensive process and not recommended. Issues should be indexed by Lucene * and queries should be executed against that index. * // w ww.ja v a2 s.com * @param repository * @param filter * optional issue filter to only return matching results * @return a list of issues */ public static List<IssueModel> getIssues(Repository repository, IssueFilter filter) { List<IssueModel> list = new ArrayList<IssueModel>(); RefModel issuesBranch = getIssuesBranch(repository); if (issuesBranch == null) { return list; } // Collect the set of all issue paths Set<String> issuePaths = new HashSet<String>(); final TreeWalk tw = new TreeWalk(repository); try { RevCommit head = JGitUtils.getCommit(repository, GB_ISSUES); tw.addTree(head.getTree()); tw.setRecursive(false); while (tw.next()) { if (tw.getDepth() < 2 && tw.isSubtree()) { tw.enterSubtree(); if (tw.getDepth() == 2) { issuePaths.add(tw.getPathString()); } } } } catch (IOException e) { error(e, repository, "{0} failed to query issues"); } finally { tw.release(); } // Build each issue and optionally filter out unwanted issues for (String issuePath : issuePaths) { RevWalk rw = new RevWalk(repository); try { RevCommit start = rw.parseCommit(repository.resolve(GB_ISSUES)); rw.markStart(start); } catch (Exception e) { error(e, repository, "Failed to find {1} in {0}", GB_ISSUES); } TreeFilter treeFilter = AndTreeFilter.create(PathFilterGroup.createFromStrings(issuePath), TreeFilter.ANY_DIFF); rw.setTreeFilter(treeFilter); Iterator<RevCommit> revlog = rw.iterator(); List<RevCommit> commits = new ArrayList<RevCommit>(); while (revlog.hasNext()) { commits.add(revlog.next()); } // release the revwalk rw.release(); if (commits.size() == 0) { LOGGER.warn("Failed to find changes for issue " + issuePath); continue; } // sort by commit order, first commit first Collections.reverse(commits); StringBuilder sb = new StringBuilder("["); boolean first = true; for (RevCommit commit : commits) { if (!first) { sb.append(','); } String message = commit.getFullMessage(); // commit message is formatted: C ISSUEID\n\nJSON // C is an single char commit code // ISSUEID is an SHA-1 hash String json = message.substring(43); sb.append(json); first = false; } sb.append(']'); // Deserialize the JSON array as a Collection<Change>, this seems // slightly faster than deserializing each change by itself. Collection<Change> changes = JsonUtils.fromJsonString(sb.toString(), new TypeToken<Collection<Change>>() { }.getType()); // create an issue object form the changes IssueModel issue = buildIssue(changes, true); // add the issue, conditionally, to the list if (filter == null) { list.add(issue); } else { if (filter.accept(issue)) { list.add(issue); } } } // sort the issues by creation Collections.sort(list); return list; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Retrieves the raw byte content of a file in the specified tree. * * @param repository// www . ja v a 2 s.c om * @param tree * if null, the RevTree from HEAD is assumed. * @param path * @return content as a byte [] */ public static byte[] getByteContent(Repository repository, RevTree tree, final String path, boolean throwError) { RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); byte[] content = null; try { if (tree == null) { ObjectId object = getDefaultBranch(repository); if (object == null) return null; RevCommit commit = rw.parseCommit(object); tree = commit.getTree(); } tw.reset(tree); while (tw.next()) { if (tw.isSubtree() && !path.equals(tw.getPathString())) { tw.enterSubtree(); continue; } ObjectId entid = tw.getObjectId(0); FileMode entmode = tw.getFileMode(0); if (entmode != FileMode.GITLINK) { ObjectLoader ldr = repository.open(entid, Constants.OBJ_BLOB); content = ldr.getCachedBytes(); } } } catch (Throwable t) { if (throwError) { error(t, repository, "{0} can't find {1} in tree {2}", path, tree.name()); } } finally { rw.dispose(); tw.close(); } return content; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Returns a list of commits for the repository or a path within the * repository. Caller may specify ending revision with objectId. Caller may * specify offset and maxCount to achieve pagination of results. If the * repository does not exist or is empty, an empty list is returned. * * @param repository/*from w ww . ja v a 2 s .c om*/ * @param objectId * if unspecified, HEAD is assumed. * @param path * if unspecified, commits for repository are returned. If * specified, commits for the path are returned. * @param offset * @param maxCount * if < 0, all commits are returned. * @return a paged list of commits */ public static List<RevCommit> getRevLog(Repository repository, String objectId, String path, int offset, int maxCount) { List<RevCommit> list = new ArrayList<RevCommit>(); if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } try { // resolve branch ObjectId startRange = null; ObjectId endRange; if (StringUtils.isEmpty(objectId)) { endRange = getDefaultBranch(repository); } else { if (objectId.contains("..")) { // range expression String[] parts = objectId.split("\\.\\."); startRange = repository.resolve(parts[0]); endRange = repository.resolve(parts[1]); } else { // objectid endRange = repository.resolve(objectId); } } if (endRange == null) { return list; } RevWalk rw = new RevWalk(repository); rw.markStart(rw.parseCommit(endRange)); if (startRange != null) { rw.markUninteresting(rw.parseCommit(startRange)); } if (!StringUtils.isEmpty(path)) { TreeFilter filter = AndTreeFilter.create( PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF); rw.setTreeFilter(filter); } Iterable<RevCommit> revlog = rw; if (offset > 0) { int count = 0; for (RevCommit rev : revlog) { count++; if (count > offset) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } } else { for (RevCommit rev : revlog) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to get {1} revlog for path {2}", objectId, path); } return list; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
public static String getSubmoduleCommitId(Repository repository, String path, RevCommit commit) { String commitId = null;//from w w w .j a v a 2s . co m RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); try { tw.reset(commit.getTree()); while (tw.next()) { if (tw.isSubtree() && !path.equals(tw.getPathString())) { tw.enterSubtree(); continue; } if (FileMode.GITLINK == tw.getFileMode(0)) { commitId = tw.getObjectId(0).getName(); break; } } } catch (Throwable t) { error(t, repository, "{0} can't find {1} in commit {2}", path, commit.name()); } finally { rw.dispose(); tw.close(); } return commitId; }
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 a v a 2s .c om } 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.gitiles.blame.BlameCacheImpl.java
License:Open Source License
@Override public ObjectId findLastCommit(Repository repo, ObjectId commitId, String path) throws IOException { // Default implementation does no caching. RevWalk rw = new RevWalk(repo); try {//w w w .ja v a 2 s . c om rw.markStart(rw.parseCommit(commitId)); rw.setRewriteParents(false); // Don't use rename detection, even though BlameGenerator does. It is not // possible for a commit to modify a path when not doing rename detection // but to not modify the same path when taking renames into account. rw.setTreeFilter(AndTreeFilter.create(PathFilterGroup.createFromStrings(path), TreeFilter.ANY_DIFF)); return rw.next(); } finally { rw.release(); } }
From source file:com.googlesource.gerrit.plugins.findowners.FindOwnersIT.java
License:Apache License
private org.eclipse.jgit.lib.Config readProjectConfig() throws Exception { git().fetch().setRefSpecs(new RefSpec(REFS_CONFIG + ":" + REFS_CONFIG)).call(); testRepo.reset(RefNames.REFS_CONFIG); RevWalk rw = testRepo.getRevWalk();//from w w w. j a va 2s .com RevTree tree = rw.parseTree(testRepo.getRepository().resolve("HEAD")); try (TreeWalk treeWalk = new TreeWalk(rw.getObjectReader())) { treeWalk.setFilter(PathFilterGroup.createFromStrings("project.config")); treeWalk.reset(tree); boolean hasProjectConfig = treeWalk.next(); if (!hasProjectConfig) { return new org.eclipse.jgit.lib.Config(); } } RevObject obj = rw.parseAny(testRepo.get(tree, "project.config")); ObjectLoader loader = rw.getObjectReader().open(obj); String text = new String(loader.getCachedBytes(), UTF_8); org.eclipse.jgit.lib.Config cfg = new org.eclipse.jgit.lib.Config(); cfg.fromText(text); return cfg; }
From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareAddCommand.java
@Override public DirCache call() throws GitAPIException { if (filepatterns.isEmpty()) { throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired); }//from w ww . j a v a2 s . c o m checkCallable(); boolean addAll = filepatterns.contains("."); //$NON-NLS-1$ try (ObjectInserter inserter = repo.newObjectInserter(); NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) { tw.setOperationType(OperationType.CHECKIN_OP); dirCache.lock(); DirCacheBuilder builder = dirCache.builder(); tw.addTree(new DirCacheBuildIterator(builder)); if (workingTreeIterator == null) workingTreeIterator = new FileTreeIterator(repo); workingTreeIterator.setDirCacheIterator(tw, 0); tw.addTree(workingTreeIterator); if (!addAll) { tw.setFilter(PathFilterGroup.createFromStrings(filepatterns)); } byte[] lastAdded = null; while (tw.next()) { DirCacheIterator c = tw.getTree(0, DirCacheIterator.class); WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class); if (c == null && f != null && f.isEntryIgnored()) { // file is not in index but is ignored, do nothing continue; } else if (c == null && update) { // Only update of existing entries was requested. continue; } DirCacheEntry entry = c != null ? c.getDirCacheEntry() : null; if (entry != null && entry.getStage() > 0 && lastAdded != null && lastAdded.length == tw.getPathLength() && tw.isPathPrefix(lastAdded, lastAdded.length) == 0) { // In case of an existing merge conflict the // DirCacheBuildIterator iterates over all stages of // this path, we however want to add only one // new DirCacheEntry per path. continue; } if (tw.isSubtree() && !tw.isDirectoryFileConflict()) { tw.enterSubtree(); continue; } if (f == null) { // working tree file does not exist if (entry != null && (!update || GITLINK == entry.getFileMode())) { builder.add(entry); } continue; } if (entry != null && entry.isAssumeValid()) { // Index entry is marked assume valid. Even though // the user specified the file to be added JGit does // not consider the file for addition. builder.add(entry); continue; } if ((f.getEntryRawMode() == TYPE_TREE && f.getIndexFileMode(c) != FileMode.GITLINK) || (f.getEntryRawMode() == TYPE_GITLINK && f.getIndexFileMode(c) == FileMode.TREE)) { // Index entry exists and is symlink, gitlink or file, // otherwise the tree would have been entered above. // Replace the index entry by diving into tree of files. tw.enterSubtree(); continue; } byte[] path = tw.getRawPath(); if (entry == null || entry.getStage() > 0) { entry = new DirCacheEntry(path); } FileMode mode = f.getIndexFileMode(c); entry.setFileMode(mode); if (GITLINK != mode) { entry.setLength(f.getEntryLength()); entry.setLastModified(f.getEntryLastModified()); long len = f.getEntryContentLength(); try (InputStream in = f.openEntryStream()) { ObjectId id = inserter.insert(OBJ_BLOB, len, in); entry.setObjectId(id); } } else { entry.setLength(0); entry.setLastModified(0); entry.setObjectId(f.getEntryObjectId()); } builder.add(entry); lastAdded = path; } inserter.flush(); builder.commit(); setCallable(false); } catch (IOException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof FilterFailedException) throw (FilterFailedException) cause; throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e); } finally { if (dirCache != null) { dirCache.unlock(); } } return dirCache; }
From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareRmCommand.java
/** * Executes the {@code Rm} command. Each instance of this class should only * be used for one invocation of the command. Don't call this method twice * on an instance.//from w w w. j av a2 s .c o m * * @return the DirCache after Rm */ public DirCache call() throws GitAPIException, NoFilepatternException { if (filepatterns.isEmpty()) { throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired); } checkCallable(); try (final TreeWalk tw = new TreeWalk(repo)) { index.lock(); DirCacheBuilder builder = index.builder(); tw.reset(); // drop the first empty tree, which we do not need here tw.setRecursive(true); tw.setFilter(PathFilterGroup.createFromStrings(filepatterns)); tw.addTree(new DirCacheBuildIterator(builder)); while (tw.next()) { if (!cached) { final FileMode mode = tw.getFileMode(0); if (mode.getObjectType() == Constants.OBJ_BLOB) { final File path = new File(repo.getWorkTree(), tw.getPathString()); // Deleting a blob is simply a matter of removing // the file or symlink named by the tree entry. delete(path); } } } builder.commit(); setCallable(false); } catch (IOException e) { throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfRmCommand, e); } finally { if (index != null) { index.unlock(); } } return index; }