List of usage examples for org.eclipse.jgit.revwalk RevWalk dispose
public void dispose()
From source file:ShowFileDiff.java
License:Apache License
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException, MissingObjectException, IncorrectObjectTypeException { // from the commit we can build the tree which allows us to construct the TreeParser RevWalk walk = new RevWalk(repository); RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId)); RevTree tree = walk.parseTree(commit.getTree().getId()); CanonicalTreeParser oldTreeParser = new CanonicalTreeParser(); ObjectReader oldReader = repository.newObjectReader(); try {/*from w w w. j av a 2 s.c o m*/ oldTreeParser.reset(oldReader, tree.getId()); } finally { oldReader.release(); } walk.dispose(); return oldTreeParser; }
From source file:actors.PostReceiveActor.java
License:Apache License
protected Collection<? extends RevCommit> parseCommitsFrom(ReceiveCommand command, Project project) { Repository repository = GitRepository.buildGitRepository(project); List<RevCommit> list = new ArrayList<>(); try {//from www . j a va2 s. c o m ObjectId endRange = command.getNewId(); ObjectId startRange = command.getOldId(); RevWalk rw = new RevWalk(repository); rw.markStart(rw.parseCommit(endRange)); if (startRange.equals(ObjectId.zeroId())) { // maybe this is a tag or an orphan branch list.add(rw.parseCommit(endRange)); rw.dispose(); return list; } else { rw.markUninteresting(rw.parseCommit(startRange)); } for (RevCommit rev : rw) { list.add(rev); } rw.dispose(); } catch (IOException e) { e.printStackTrace(); } return list; }
From source file:am.ik.categolj3.api.git.GitStore.java
License:Apache License
void syncHead() { log.info("Syncing HEAD..."); ObjectId oldHead = this.currentHead.get(); ObjectId newHead = this.head(); try (Repository repository = this.git.getRepository()) { DiffFormatter diffFormatter = new DiffFormatter(System.out); diffFormatter.setRepository(repository); RevWalk walk = new RevWalk(repository); try {/*from www . j a v a 2s. c o m*/ RevCommit fromCommit = walk.parseCommit(oldHead); RevCommit toCommit = walk.parseCommit(newHead); List<DiffEntry> list = diffFormatter.scan(fromCommit.getTree(), toCommit.getTree()); list.forEach(diff -> { log.info("[{}]\tnew={}\told={}", diff.getChangeType(), diff.getNewPath(), diff.getOldPath()); if (diff.getOldPath() != null) { Path path = Paths .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getOldPath()); if (Entry.isPublic(path)) { Long entryId = Entry.parseEntryId(path); log.info("evict Entry({})", entryId); this.entryCache.evict(entryId); } } if (diff.getNewPath() != null) { Path path = Paths .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getNewPath()); this.loadEntry(path).ifPresent(entry -> { log.info("put Entry({})", entry.getEntryId()); this.entryCache.put(entry.getEntryId(), entry); }); } }); } finally { walk.dispose(); } } catch (IOException e) { throw new UncheckedIOException(e); } catch (Exception e) { throw new IllegalStateException(e); } this.currentHead.set(newHead); }
From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java
License:Open Source License
private void _run() throws IOException, MinerException, SQLException { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(new File(settings.srcLocalPath, ".git")).readEnvironment() .findGitDir().build();//from w w w . j a va 2s .c o m /* Map<String,Ref> refs = repository.getAllRefs(); for (Map.Entry<String, Ref> ref : refs.entrySet ()) { System.out.println (ref.getKey ()); } */ Ref head = repository.getRef(startRef); if (head == null) { throw new MinerException("Unknown reference: '" + startRef + "'"); } RevWalk walk = new RevWalk(repository); RevCommit commit = walk.parseCommit(head.getObjectId()); walk.markStart(commit); walk.sort(RevSort.REVERSE); // count commit: (fast) int commitCount = 0; Iterator<RevCommit> iter = walk.iterator(); while (iter.hasNext()) { iter.next(); commitCount++; } emitTasksTotal(commitCount); // process commits: (slow) walk.reset(); walk.markStart(commit); walk.sort(RevSort.REVERSE); Map<String, ManagedFile> fileCache = new HashMap<String, ManagedFile>(); for (RevCommit rev : walk) { if (stopped == true) { break; } processCommit(repository, walk, rev, fileCache); } walk.dispose(); repository.close(); }
From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java
License:Apache License
@Override public ProposedTag fromRef(final Ref gitTag) throws SCMException { notNull(gitTag, "gitTag"); final RevWalk walk = new RevWalk(getGit().getRepository()); final ObjectId tagId = gitTag.getObjectId(); JSONObject message;/*from ww w.ja v a 2 s. c om*/ try { final RevTag tag = walk.parseTag(tagId); message = (JSONObject) JSONValue.parse(tag.getFullMessage()); } catch (final IOException e) { throw new SCMException(e, "Error while looking up tag because RevTag could not be parsed! Object-id was %s", tagId); } finally { walk.dispose(); } if (message == null) { message = new JSONObject(); message.put(VERSION, "0"); message.put(BUILD_NUMBER, "0"); } return new GitProposedTag(getGit(), log, gitTag, stripRefPrefix(gitTag.getName()), message, config.getRemoteUrlOrNull()); }
From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java
License:Apache License
@Override public boolean hasChangedSince(final String modulePath, final List<String> childModules, final Collection<ProposedTag> tags) throws SCMException { final RevWalk walk = new RevWalk(getGit().getRepository()); try {//from w w w . j ava2 s. c om walk.setRetainBody(false); walk.markStart(walk.parseCommit(getGit().getRepository().findRef("HEAD").getObjectId())); filterOutOtherModulesChanges(modulePath, childModules, walk); stopWalkingWhenTheTagsAreHit(tags, walk); final Iterator<RevCommit> it = walk.iterator(); boolean changed = it.hasNext(); if (config.isIncrementSnapshotVersionAfterRelease() && changed) { final RevCommit commit = it.next(); walk.parseBody(commit); changed = !SNAPSHOT_COMMIT_MESSAGE.equals(commit.getShortMessage()) || it.hasNext(); } return changed; } catch (final IOException e) { throw new SCMException(e, "Diff detector could not determine whether module %s has been changed!", modulePath); } finally { walk.dispose(); } }
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 {//from w w w .ja v a 2 s .c o m 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.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/* w ww.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.//from ww w . j a va 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.DiffUtils.java
License:Apache License
/** * Returns the diff between two commits for the specified file. * * @param repository//from w ww. j a v a2s . c om * @param baseCommit * if base commit is null the diff is to the primary parent of * the commit. * @param commit * @param path * if the path is specified, the diff is restricted to that file * or folder. if unspecified, the diff is for the entire commit. * @param comparator * @param outputType * @param handler * to use for rendering binary diffs if {@code outputType} is {@link DiffOutputType#HTML HTML}. * May be {@code null}, resulting in the default behavior. * @param tabLength * @return the diff */ public static DiffOutput getDiff(Repository repository, RevCommit baseCommit, RevCommit commit, String path, DiffComparator comparator, DiffOutputType outputType, final BinaryDiffHandler handler, int tabLength) { DiffStat stat = null; String diff = null; try { ByteArrayOutputStream os = null; DiffFormatter df; switch (outputType) { case HTML: df = new GitBlitDiffFormatter(commit.getName(), repository, path, handler, tabLength); break; case PLAIN: default: os = new ByteArrayOutputStream(); df = new DiffFormatter(os); break; } df.setRepository(repository); df.setDiffComparator((comparator == null ? DiffComparator.SHOW_WHITESPACE : comparator).textComparator); df.setDetectRenames(true); RevTree commitTree = commit.getTree(); RevTree baseTree; if (baseCommit == null) { if (commit.getParentCount() > 0) { final RevWalk rw = new RevWalk(repository); RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); rw.dispose(); baseTree = parent.getTree(); } else { // FIXME initial commit. no parent?! baseTree = commitTree; } } else { baseTree = baseCommit.getTree(); } List<DiffEntry> diffEntries = df.scan(baseTree, commitTree); if (path != null && path.length() > 0) { for (DiffEntry diffEntry : diffEntries) { if (diffEntry.getNewPath().equalsIgnoreCase(path)) { df.format(diffEntry); break; } } } else { df.format(diffEntries); } df.flush(); if (df instanceof GitBlitDiffFormatter) { // workaround for complex private methods in DiffFormatter diff = ((GitBlitDiffFormatter) df).getHtml(); stat = ((GitBlitDiffFormatter) df).getDiffStat(); } else { diff = os.toString(); } } catch (Throwable t) { LOGGER.error("failed to generate commit diff!", t); } return new DiffOutput(outputType, diff, stat); }