List of usage examples for org.eclipse.jgit.treewalk TreeWalk close
@Override public void close()
Release any resources used by this walker's reader.
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
/** * builds a dir cache by copying entries from an existing tree, skipping * files if specified./*from ww w. ja v a 2 s. c o m*/ * * @param tree * the tree to copy from. * @param repository * the repository to work upon. * @param dirCacheBuilder * the dir builder instance used to add entries to the dir cache. * @param ignoredFilePaths * a list of file paths to ignore during copying. * @throws MissingObjectException * @throws IncorrectObjectTypeException * @throws CorruptObjectException * @throws IOException */ private void buildDirCacheFromTree(RevTree tree, Repository repository, DirCacheBuilder dirCacheBuilder, List<String> ignoredFilePaths) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { // TODO improve exception handling TreeWalk treeWalk = new TreeWalk(repository); int treeId = treeWalk.addTree(tree); treeWalk.setRecursive(true); while (treeWalk.next()) { String path = treeWalk.getPathString(); CanonicalTreeParser prevTreeParser = treeWalk.getTree(treeId, CanonicalTreeParser.class); if (prevTreeParser != null && !ignoredFilePaths.contains(path)) { // create a new DirCacheEntry with data from the previous commit final DirCacheEntry dcEntry = new DirCacheEntry(path); dcEntry.setObjectId(prevTreeParser.getEntryObjectId()); dcEntry.setFileMode(prevTreeParser.getEntryFileMode()); dirCacheBuilder.add(dcEntry); } } treeWalk.close(); }
From source file:com.gitblit.servlet.RawServlet.java
License:Apache License
protected boolean streamFromRepo(HttpServletRequest request, HttpServletResponse response, Repository repository, RevCommit commit, String requestedPath) throws IOException { boolean served = false; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); try {/* www . j a v a 2s . c om*/ tw.reset(); tw.addTree(commit.getTree()); PathFilter f = PathFilter.create(requestedPath); tw.setFilter(f); tw.setRecursive(true); MutableObjectId id = new MutableObjectId(); ObjectReader reader = tw.getObjectReader(); while (tw.next()) { FileMode mode = tw.getFileMode(0); if (mode == FileMode.GITLINK || mode == FileMode.TREE) { continue; } tw.getObjectId(id, 0); String filename = StringUtils.getLastPathElement(requestedPath); try { String userAgent = request.getHeader("User-Agent"); if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) { response.setHeader("Content-Disposition", "filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\""); } else if (userAgent != null && userAgent.indexOf("MSIE") > -1) { response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\""); } else { response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes(Constants.ENCODING), "latin1") + "\""); } } catch (UnsupportedEncodingException e) { response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); } long len = reader.getObjectSize(id, org.eclipse.jgit.lib.Constants.OBJ_BLOB); setContentType(response, "application/octet-stream"); response.setIntHeader("Content-Length", (int) len); ObjectLoader ldr = repository.open(id); ldr.copyTo(response.getOutputStream()); served = true; } } finally { tw.close(); rw.dispose(); } response.flushBuffer(); return served; }
From source file:com.gitblit.tickets.BranchTicketService.java
License:Apache License
/** * Deletes a ticket from the repository. * * @param ticket//from www . j a v a 2 s . com * @return true if successful */ @Override protected synchronized boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket, String deletedBy) { if (ticket == null) { throw new RuntimeException("must specify a ticket!"); } boolean success = false; Repository db = repositoryManager.getRepository(ticket.repository); try { RefModel ticketsBranch = getTicketsBranch(db); if (ticketsBranch == null) { throw new RuntimeException(BRANCH + " does not exist!"); } String ticketPath = toTicketPath(ticket.number); TreeWalk treeWalk = null; try { ObjectId treeId = db.resolve(BRANCH + "^{tree}"); // Create the in-memory index of the new/updated ticket DirCache index = DirCache.newInCore(); DirCacheBuilder builder = index.builder(); // Traverse HEAD to add all other paths treeWalk = new TreeWalk(db); int hIdx = -1; if (treeId != null) { hIdx = treeWalk.addTree(treeId); } treeWalk.setRecursive(true); while (treeWalk.next()) { String path = treeWalk.getPathString(); CanonicalTreeParser hTree = null; if (hIdx != -1) { hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class); } if (!path.startsWith(ticketPath)) { // add entries from HEAD for all other paths if (hTree != null) { final DirCacheEntry entry = new DirCacheEntry(path); entry.setObjectId(hTree.getEntryObjectId()); entry.setFileMode(hTree.getEntryFileMode()); // add to temporary in-core index builder.add(entry); } } } // finish temporary in-core index used for this commit builder.finish(); success = commitIndex(db, index, deletedBy, "- " + ticket.number); } catch (Throwable t) { log.error(MessageFormat.format("Failed to delete ticket {0,number,0} from {1}", ticket.number, db.getDirectory()), t); } finally { // release the treewalk if (treeWalk != null) { treeWalk.close(); } } } finally { db.close(); } return success; }
From source file:com.gitblit.utils.CompressionUtils.java
License:Apache License
/** * Zips the contents of the tree at the (optionally) specified revision and * the (optionally) specified basepath to the supplied outputstream. * * @param repository/* www . jav a 2 s . c o m*/ * @param basePath * if unspecified, entire repository is assumed. * @param objectId * if unspecified, HEAD is assumed. * @param os * @return true if repository was successfully zipped to supplied output * stream */ public static boolean zip(Repository repository, IFilestoreManager filestoreManager, String basePath, String objectId, OutputStream os) { RevCommit commit = JGitUtils.getCommit(repository, objectId); if (commit == null) { return false; } boolean success = false; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); try { tw.reset(); tw.addTree(commit.getTree()); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setComment("Generated by Gitblit"); if (!StringUtils.isEmpty(basePath)) { PathFilter f = PathFilter.create(basePath); tw.setFilter(f); } tw.setRecursive(true); MutableObjectId id = new MutableObjectId(); ObjectReader reader = tw.getObjectReader(); long modified = commit.getAuthorIdent().getWhen().getTime(); while (tw.next()) { FileMode mode = tw.getFileMode(0); if (mode == FileMode.GITLINK || mode == FileMode.TREE) { continue; } tw.getObjectId(id, 0); ObjectLoader loader = repository.open(id); ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString()); FilestoreModel filestoreItem = null; if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) { filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id)); } final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize(); entry.setSize(size); entry.setComment(commit.getName()); entry.setUnixMode(mode.getBits()); entry.setTime(modified); zos.putArchiveEntry(entry); if (filestoreItem == null) { //Copy repository stored file loader.copyTo(zos); } else { //Copy filestore file try (FileInputStream streamIn = new FileInputStream( filestoreManager.getStoragePath(filestoreItem.oid))) { IOUtils.copyLarge(streamIn, zos); } catch (Throwable e) { LOGGER.error( MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e); //Handle as per other errors throw e; } } zos.closeArchiveEntry(); } zos.finish(); success = true; } catch (IOException e) { error(e, repository, "{0} failed to zip files from commit {1}", commit.getName()); } finally { tw.close(); rw.dispose(); } return success; }
From source file:com.gitblit.utils.CompressionUtils.java
License:Apache License
/** * Compresses/archives the contents of the tree at the (optionally) * specified revision and the (optionally) specified basepath to the * supplied outputstream.// ww w. jav a 2s .c o m * * @param algorithm * compression algorithm for tar (optional) * @param repository * @param basePath * if unspecified, entire repository is assumed. * @param objectId * if unspecified, HEAD is assumed. * @param os * @return true if repository was successfully zipped to supplied output * stream */ private static boolean tar(String algorithm, Repository repository, IFilestoreManager filestoreManager, String basePath, String objectId, OutputStream os) { RevCommit commit = JGitUtils.getCommit(repository, objectId); if (commit == null) { return false; } OutputStream cos = os; if (!StringUtils.isEmpty(algorithm)) { try { cos = new CompressorStreamFactory().createCompressorOutputStream(algorithm, os); } catch (CompressorException e1) { error(e1, repository, "{0} failed to open {1} stream", algorithm); } } boolean success = false; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); try { tw.reset(); tw.addTree(commit.getTree()); TarArchiveOutputStream tos = new TarArchiveOutputStream(cos); tos.setAddPaxHeadersForNonAsciiNames(true); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); if (!StringUtils.isEmpty(basePath)) { PathFilter f = PathFilter.create(basePath); tw.setFilter(f); } tw.setRecursive(true); MutableObjectId id = new MutableObjectId(); long modified = commit.getAuthorIdent().getWhen().getTime(); while (tw.next()) { FileMode mode = tw.getFileMode(0); if (mode == FileMode.GITLINK || mode == FileMode.TREE) { continue; } tw.getObjectId(id, 0); ObjectLoader loader = repository.open(id); if (FileMode.SYMLINK == mode) { TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString(), TarArchiveEntry.LF_SYMLINK); ByteArrayOutputStream bos = new ByteArrayOutputStream(); loader.copyTo(bos); entry.setLinkName(bos.toString()); entry.setModTime(modified); tos.putArchiveEntry(entry); tos.closeArchiveEntry(); } else { TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString()); entry.setMode(mode.getBits()); entry.setModTime(modified); FilestoreModel filestoreItem = null; if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) { filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id)); } final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize(); entry.setSize(size); tos.putArchiveEntry(entry); if (filestoreItem == null) { //Copy repository stored file loader.copyTo(tos); } else { //Copy filestore file try (FileInputStream streamIn = new FileInputStream( filestoreManager.getStoragePath(filestoreItem.oid))) { IOUtils.copyLarge(streamIn, tos); } catch (Throwable e) { LOGGER.error( MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e); //Handle as per other errors throw e; } } tos.closeArchiveEntry(); } } tos.finish(); tos.close(); cos.close(); success = true; } catch (IOException e) { error(e, repository, "{0} failed to {1} stream files from commit {2}", algorithm, commit.getName()); } finally { tw.close(); rw.dispose(); } return success; }
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 www.j av 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.//from w w w . ja v a 2s . 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
/** * 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 . jav a 2 s . c o m*/ * * This is modified version that implements path compression feature. * * @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> getFilesInPath2(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()); final boolean isPathEmpty = Strings.isNullOrEmpty(path); if (!isPathEmpty) { PathFilter f = PathFilter.create(path); tw.setFilter(f); } tw.setRecursive(true); List<String> paths = new ArrayList<>(); while (tw.next()) { String child = isPathEmpty ? tw.getPathString() : tw.getPathString().replaceFirst(String.format("%s/", path), ""); paths.add(child); } for (String p : PathUtils.compressPaths(paths)) { String pathString = isPathEmpty ? p : String.format("%s/%s", path, p); list.add(getPathModel(repository, pathString, path, 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/*w w w. j a v a 2 s. co 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.utils.JGitUtils.java
License:Apache License
/** * Returns the list of files in the repository in the specified commit that * match one of the specified extensions. This is a CASE-SENSITIVE search. * If the repository does not exist or is empty, an empty list is returned. * * @param repository//from w ww. ja va 2 s . c o m * @param extensions * @param objectId * @return list of files in repository with a matching extension */ public static List<PathModel> getDocuments(Repository repository, List<String> extensions, String objectId) { List<PathModel> list = new ArrayList<PathModel>(); if (!hasCommits(repository)) { return list; } RevCommit commit = getCommit(repository, objectId); final TreeWalk tw = new TreeWalk(repository); try { tw.addTree(commit.getTree()); if (extensions != null && extensions.size() > 0) { List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>(); for (String extension : extensions) { if (extension.charAt(0) == '.') { suffixFilters.add(PathSuffixFilter.create(extension)); } else { // escape the . since this is a regexp filter suffixFilters.add(PathSuffixFilter.create("." + extension)); } } TreeFilter filter; if (suffixFilters.size() == 1) { filter = suffixFilters.get(0); } else { filter = OrTreeFilter.create(suffixFilters); } tw.setFilter(filter); tw.setRecursive(true); } while (tw.next()) { list.add(getPathModel(tw, null, commit)); } } catch (IOException e) { error(e, repository, "{0} failed to get documents for commit {1}", commit.getName()); } finally { tw.close(); } Collections.sort(list); return list; }