List of usage examples for org.eclipse.jgit.treewalk TreeWalk isSubtree
public boolean isSubtree()
From source file:au.id.soundadvice.systemdesign.versioning.jgit.GitVersionControl.java
License:Open Source License
/** * Find the tree that contains the required identity. * * @return The ObjectId of the tree (directory) that contains the matching * identity within the supplied hierarchy. */// ww w . j a v a 2 s . co m private ObjectId findMatchingIdentity(IdentityValidator identityValidator, ObjectId tree) throws IOException { TreeWalk treeWalk = new TreeWalk(repo.getRepository()); try { treeWalk.setRecursive(false); treeWalk.addTree(tree); while (treeWalk.next()) { if (treeWalk.isSubtree()) { ObjectId candidateId = findMatchingIdentity(identityValidator, treeWalk.getObjectId(0)); if (ObjectId.zeroId().equals(candidateId)) { // Keep searching } else { return candidateId; } } else if (identityValidator.getIdentityFileName().equals(treeWalk.getNameString())) { // Read the identity file ObjectLoader loader = repo.getRepository().open(treeWalk.getObjectId(0)); ObjectStream stream = loader.openStream(); InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); if (identityValidator.isIdentityMatched(new BufferedReader(reader))) { // We found it return tree; } } } return ObjectId.zeroId(); } finally { treeWalk.release(); } }
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 w w . java 2 s .c om*/ * @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/* ww w . j a v a 2 s .c o m*/ * @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 ww. ja v a 2s. c om * * @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
/** * 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/* ww w.j a v a2s. c om*/ * @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.utils.JGitUtils.java
License:Apache License
/** * Returns a path model of the current file in the treewalk. * * @param tw//from ww w .j av a 2 s .co m * @param basePath * @param commit * @return a path model of the current file in the treewalk */ private static PathModel getPathModel(TreeWalk tw, String basePath, RevCommit commit) { String name; long size = 0; if (StringUtils.isEmpty(basePath)) { name = tw.getPathString(); } else { name = tw.getPathString().substring(basePath.length() + 1); } ObjectId objectId = tw.getObjectId(0); FilestoreModel filestoreItem = null; 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()); } return new PathModel(name, tw.getPathString(), filestoreItem, size, tw.getFileMode(0).getBits(), objectId.getName(), commit.getName()); }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Returns a path model by path string//from ww w. j a va2s . co m * * @param repo * @param path * @param filter * @param commit * @return a path model of the specified object */ private static PathModel getPathModel(Repository repo, String path, String filter, RevCommit commit) throws IOException { long size = 0; FilestoreModel filestoreItem = null; TreeWalk tw = TreeWalk.forPath(repo, path, commit.getTree()); String pathString = path; if (!tw.isSubtree() && (tw.getFileMode(0) != FileMode.GITLINK)) { pathString = PathUtils.getLastPathComponent(pathString); size = tw.getObjectReader().getObjectSize(tw.getObjectId(0), Constants.OBJ_BLOB); if (isPossibleFilestoreItem(size)) { filestoreItem = getFilestoreItem(tw.getObjectReader().open(tw.getObjectId(0))); } } else if (tw.isSubtree()) { // do not display dirs that are behind in the path if (!Strings.isNullOrEmpty(filter)) { pathString = path.replaceFirst(filter + "/", ""); } // remove the last slash from path in displayed link if (pathString != null && pathString.charAt(pathString.length() - 1) == '/') { pathString = pathString.substring(0, pathString.length() - 1); } } return new PathModel(pathString, tw.getPathString(), filestoreItem, size, tw.getFileMode(0).getBits(), tw.getObjectId(0).getName(), commit.getName()); }
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 ww w . j a va 2s .c o 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.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; }//from w ww . ja v a 2 s . co 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 www.j a va 2 s.co 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; }