List of usage examples for org.eclipse.jgit.treewalk TreeWalk enterSubtree
public void enterSubtree() throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException
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. * /*ww w . j av a2 s .c o m*/ * @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//from w w w . j a va 2 s.com * @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 the list of files in the specified folder at the specified * commit. If the repository does not exist or is empty, an empty list is * returned./* w w w .j a va2 s .co m*/ * * @param repository * @param path * if unspecified, root folder is assumed. * @param commit * if null, HEAD is assumed. * @return list of files in specified path */ public static List<PathModel> getFilesInPath(Repository repository, String path, RevCommit commit) { List<PathModel> list = new ArrayList<PathModel>(); if (!hasCommits(repository)) { return list; } if (commit == null) { commit = getCommit(repository, null); } final TreeWalk tw = new TreeWalk(repository); try { tw.addTree(commit.getTree()); if (!StringUtils.isEmpty(path)) { PathFilter f = PathFilter.create(path); tw.setFilter(f); tw.setRecursive(false); boolean foundFolder = false; while (tw.next()) { if (!foundFolder && tw.isSubtree()) { tw.enterSubtree(); } if (tw.getPathString().equals(path)) { foundFolder = true; continue; } if (foundFolder) { list.add(getPathModel(tw, path, commit)); } } } else { tw.setRecursive(false); while (tw.next()) { list.add(getPathModel(tw, null, commit)); } } } catch (IOException e) { error(e, repository, "{0} failed to get files for commit {1}", commit.getName()); } finally { tw.close(); } Collections.sort(list); 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 a2 s. 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.google.gitiles.doc.DocServlet.java
License:Open Source License
private static boolean findIndexFile(TreeWalk tw) throws IOException { tw.enterSubtree(); while (tw.next()) { if ((tw.getRawMode(0) & TYPE_MASK) == TYPE_FILE && INDEX_MD.equals(tw.getNameString())) { return true; }// w w w . ja v a2 s . co m } return false; }
From source file:com.google.gitiles.PathServlet.java
License:Open Source License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { GitilesView view = ViewFilter.getView(req); Repository repo = ServletUtils.getRepository(req); RevWalk rw = new RevWalk(repo); try {//ww w. ja va 2 s. c o m RevObject obj = rw.peel(rw.parseAny(view.getRevision().getId())); RevTree root; switch (obj.getType()) { case OBJ_COMMIT: root = ((RevCommit) obj).getTree(); break; case OBJ_TREE: root = (RevTree) obj; break; default: res.setStatus(SC_NOT_FOUND); return; } TreeWalk tw; FileType type; String path = view.getTreePath(); if (path.isEmpty()) { tw = new TreeWalk(rw.getObjectReader()); tw.addTree(root); tw.setRecursive(false); type = FileType.TREE; } else { tw = TreeWalk.forPath(rw.getObjectReader(), path, root); if (tw == null) { res.setStatus(SC_NOT_FOUND); return; } type = FileType.forEntry(tw); if (type == FileType.TREE) { tw.enterSubtree(); tw.setRecursive(false); } } switch (type) { case TREE: showTree(req, res, rw, tw, obj); break; case SYMLINK: showSymlink(req, res, rw, tw); break; case REGULAR_FILE: case EXECUTABLE_FILE: showFile(req, res, rw, tw); break; case GITLINK: showGitlink(req, res, rw, tw, root); break; default: log.error("Bad file type: %s", type); res.setStatus(SC_NOT_FOUND); break; } } catch (LargeObjectException e) { res.setStatus(SC_INTERNAL_SERVER_ERROR); } finally { rw.release(); } }
From source file:com.googlesource.gerrit.plugins.uploadvalidator.DuplicatePathnameValidator.java
License:Apache License
@VisibleForTesting void checkForDuplicatesAgainstTheWholeTree(TreeWalk tw, Set<String> changed, List<CommitValidationMessage> messages) throws IOException { Map<String, String> all = allPaths(changed); while (tw.next()) { String currentPath = tw.getPathString(); if (isDeleted(tw)) { continue; }// ww w. j av a 2s.c o m String potentialDuplicate = all.get(currentPath.toLowerCase(locale)); if (potentialDuplicate == null) { continue; } else if (potentialDuplicate.equals(currentPath)) { if (tw.isSubtree()) { tw.enterSubtree(); } continue; } else { messages.add(conflict(potentialDuplicate, currentPath)); } } }
From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java
License:Eclipse Distribution License
/** * Process the given TreeWalk's entries. * * @param treeWalk//from w w w . j av a2 s .c o m * The walk to iterate over. * @param ignoreConflicts * see * {@link UnleashGitMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)} * @return Whether the trees merged cleanly. * @throws IOException * @since 3.5 */ @Override protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts) throws IOException { boolean hasWorkingTreeIterator = this.tw.getTreeCount() > T_FILE; while (treeWalk.next()) { if (!processEntry(treeWalk.getTree(T_BASE, CanonicalTreeParser.class), treeWalk.getTree(T_OURS, CanonicalTreeParser.class), treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class), treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class), hasWorkingTreeIterator ? treeWalk.getTree(T_FILE, WorkingTreeIterator.class) : null, ignoreConflicts)) { cleanUp(); return false; } if (treeWalk.isSubtree() && this.enterSubtree) { treeWalk.enterSubtree(); } } return true; }
From source file:com.microsoft.gittf.core.tasks.pendDiff.PendDifferenceTask.java
License:Open Source License
/** * Validates that the commit tree does not have the any item twice with the * same name only different in case. TFS does not support having the same * item with different case so we should not allow that. * //from ww w . j a va 2 s . com * @param commit * @throws Exception */ private void validateCaseSensitivityRequirements(RevCommit commit) throws Exception { /* Create a tree walker */ RevTree tree = commit.getTree(); final TreeWalk treeWalker = new NameConflictTreeWalk(repository); try { treeWalker.addTree(tree); treeWalker.setFilter(TreeFilter.ALL); /* * Build a list of items in the tree in a hash set for quicker * lookup */ Set<String> existingTreeItems = new HashSet<String>(); /* Walk the tree looking for duplicates in the tree */ while (treeWalker.next()) { String pathString = treeWalker.getPathString().toLowerCase(); if (existingTreeItems.contains(pathString)) { throw new Exception( Messages.formatString("PendDifferenceTask.SimilarItemWithDifferentCaseInCommitFormat", //$NON-NLS-1$ pathString, ObjectIdUtil.abbreviate(repository, commit.getId()))); } existingTreeItems.add(pathString); int objectType = treeWalker.getFileMode(0).getObjectType(); if (objectType == OBJ_TREE) { treeWalker.enterSubtree(); } } } finally { if (treeWalker != null) { treeWalker.release(); } } }
From source file:com.nlbhub.nlb.vcs.GitAdapter.java
License:Open Source License
private List<String> listRepositoryContents() throws IOException, NLBVCSException { List<String> result = new ArrayList<>(); Ref head = m_localRepo.getRef(Constants.HEAD); // head can be null if repo is broken (for example, .git directory was deleted) if (head == null) { throw new NLBVCSException( "Your Git repository is broken.\nPlease either properly clone it (using 'git clone' command) or use 'runlight' command to run the program."); }//from w ww . ja va 2s. com // head.getObjectId() can be null, for example, if repository was never committed. final ObjectId objectId = head.getObjectId(); if (objectId != null) { // a RevWalk allows to walk over commits based on some filtering that is defined RevWalk walk = new RevWalk(m_localRepo); RevCommit commit = walk.parseCommit(objectId); RevTree tree = commit.getTree(); // now use a TreeWalk to iterate over all files in the Tree recursively // you can set Filters to narrow down the results if needed TreeWalk treeWalk = new TreeWalk(m_localRepo); treeWalk.addTree(tree); treeWalk.setRecursive(false); while (treeWalk.next()) { if (treeWalk.isSubtree()) { //System.out.println("dir: " + treeWalk.getPathString()); treeWalk.enterSubtree(); } else { //System.out.println("file: " + treeWalk.getPathString()); result.add(treeWalk.getPathString()); } } } return result; }