List of usage examples for org.eclipse.jgit.lib Repository open
@NonNull public ObjectLoader open(AnyObjectId objectId) throws MissingObjectException, IOException
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
/** * loads all patches of from the given list of {@link DiffEntry}s. * /* w w w.ja v a 2s .c om*/ * @param patchSet * the patchSet to add the patches to. * @param ref * the ref to the commit of the patch set. * @param repository * the git repository instance * @throws RepositoryIOException */ private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException { EList<Patch> patches = patchSet.getPatches(); Repository repository = git.getRepository(); try { RevWalk revWalk = new RevWalk(repository); RevCommit newCommit = revWalk.parseCommit(ref.getObjectId()); RevCommit oldCommit = newCommit.getParent(0); revWalk.parseHeaders(oldCommit); ObjectReader objectReader = repository.newObjectReader(); revWalk.close(); CanonicalTreeParser newTreeIterator = new CanonicalTreeParser(); newTreeIterator.reset(objectReader, newCommit.getTree().getId()); CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser(); oldTreeIterator.reset(objectReader, oldCommit.getTree().getId()); List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call(); for (DiffEntry diff : diffs) { String newPath = diff.getNewPath(); String oldPath = diff.getOldPath(); Patch patch = null; /* * only papyrus diagrams are supported for now, so models are in * .uml files, diagrams in .notation files */ if (diff.getChangeType() != ChangeType.DELETE) { if (newPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (newPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } else { if (oldPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (oldPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } switch (diff.getChangeType()) { case ADD: patch.setChangeType(PatchChangeType.ADD); break; case COPY: patch.setChangeType(PatchChangeType.COPY); break; case DELETE: patch.setChangeType(PatchChangeType.DELETE); break; case MODIFY: patch.setChangeType(PatchChangeType.MODIFY); break; case RENAME: patch.setChangeType(PatchChangeType.RENAME); break; } patch.setNewPath(newPath); patch.setOldPath(oldPath); if (diff.getChangeType() != ChangeType.DELETE) { ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId()); patch.setNewContent(objectLoader.getBytes()); } if (diff.getChangeType() != ChangeType.ADD) { ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId()); patch.setOldContent(objectLoader.getBytes()); } patches.add(patch); } } catch (IOException e) { throw new RepositoryIOException(MessageFormat.format( "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } catch (GitAPIException e) { throw new RepositoryIOException( MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } }
From source file:co.bledo.gitmin.servlet.Review.java
License:Apache License
private String getFileContent(Repository repo, RevCommit commit, String path) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { // and using commit's tree find the path RevTree tree = commit.getTree();//from w w w .j a va2 s.com TreeWalk treeWalk = new TreeWalk(repo); treeWalk.addTree(tree); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(path)); if (!treeWalk.next()) { return ""; } ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = repo.open(objectId); // and then one can use either //InputStream in = loader.openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); loader.copyTo(out); return out.toString(); }
From source file:com.buildautomation.jgit.api.GetFileAttributes.java
License:Apache License
private static void printFile(Repository repository, RevTree tree) throws IOException { // now try to find a specific file try (TreeWalk treeWalk = new TreeWalk(repository)) { treeWalk.addTree(tree);/*from w w w . ja va 2 s . c o m*/ treeWalk.setRecursive(false); treeWalk.setFilter(PathFilter.create("README.md")); if (!treeWalk.next()) { throw new IllegalStateException("Did not find expected file 'README.md'"); } // FileMode specifies the type of file, FileMode.REGULAR_FILE for normal file, FileMode.EXECUTABLE_FILE for executable bit // set FileMode fileMode = treeWalk.getFileMode(0); ObjectLoader loader = repository.open(treeWalk.getObjectId(0)); System.out.println("README.md: " + getFileMode(fileMode) + ", type: " + fileMode.getObjectType() + ", mode: " + fileMode + " size: " + loader.getSize()); } }
From source file:com.buildautomation.jgit.api.ShowBlame.java
License:Apache License
private static int countFiles(Repository repository, ObjectId commitID, String name) throws IOException { try (RevWalk revWalk = new RevWalk(repository)) { RevCommit commit = revWalk.parseCommit(commitID); RevTree tree = commit.getTree(); System.out.println("Having tree: " + tree); // now try to find a specific file try (TreeWalk treeWalk = new TreeWalk(repository)) { treeWalk.addTree(tree);//from w ww .j a va2s. co m treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(name)); if (!treeWalk.next()) { throw new IllegalStateException("Did not find expected file 'README.md'"); } ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = repository.open(objectId); ByteArrayOutputStream stream = new ByteArrayOutputStream(); // and then one can the loader to read the file loader.copyTo(stream); revWalk.dispose(); return IOUtils.readLines(new ByteArrayInputStream(stream.toByteArray())).size(); } } }
From source file:com.chungkwong.jgitgui.CommitTreeItem.java
License:Open Source License
@Override public Node getContentPage() { RevCommit rev = (RevCommit) getValue(); Repository repository = ((Git) getParent().getParent().getValue()).getRepository(); SplitPane page = new SplitPane(); page.setOrientation(Orientation.VERTICAL); StringBuilder buf = new StringBuilder(); buf.append(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("PARENTS:")); for (int i = 0; i < rev.getParentCount(); i++) buf.append(rev.getParent(i)).append('\n'); buf.append(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("MESSAGE:")); buf.append(rev.getFullMessage());//from www .j av a 2s . c o m TextArea msg = new TextArea(buf.toString()); msg.setEditable(false); page.getItems().add(msg); SplitPane fileViewer = new SplitPane(); fileViewer.setOrientation(Orientation.HORIZONTAL); TreeView tree = new TreeView(new TreeItem()); tree.setShowRoot(false); TextArea content = new TextArea(); content.setEditable(false); try (TreeWalk walk = new TreeWalk(repository)) { walk.addTree(rev.getTree()); walk.setRecursive(true); LinkedList<TreeItem> items = new LinkedList<>(); items.add(tree.getRoot()); while (walk.next()) { TreeItem item = new FileTreeItem(walk.getObjectId(0), walk.getPathString()); /*while(walk.getDepth()<items.size()-1) items.removeLast(); if(walk.getDepth()>items.size()-1) items.addLast(item);*/ items.getLast().getChildren().add(item); } } catch (Exception ex) { Logger.getLogger(CommitTreeItem.class.getName()).log(Level.SEVERE, null, ex); Util.informUser(ex); } tree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { if (t1 != null) { try { ObjectLoader obj = repository.open(((FileTreeItem) t1).getId()); if (obj.getType() != Constants.OBJ_TREE) { StringBuilder buf = new StringBuilder(); BufferedReader in = new BufferedReader( new InputStreamReader(obj.openStream(), rev.getEncoding())); content.setText(in.lines().collect(Collectors.joining("\n"))); } } catch (Exception ex) { Logger.getLogger(CommitTreeItem.class.getName()).log(Level.SEVERE, null, ex); Util.informUser(ex); } } } }); fileViewer.getItems().add(tree); fileViewer.getItems().add(content); page.getItems().add(fileViewer); page.setDividerPositions(0.2, 0.8); return page; }
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 {/* w w w. j a va 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 w w . jav a 2 s .c om * @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 www. j ava2 s.c om * * @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.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java
License:Open Source License
/** * Utility method that converts a note to a string (assuming it's UTF-8). *//* w w w .ja v a 2s .c o m*/ private String noteToString(Repository repo, Note note) throws MissingObjectException, IOException, UnsupportedEncodingException { ObjectLoader loader = repo.open(note.getData()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); loader.copyTo(baos); return new String(baos.toByteArray(), "UTF-8"); }
From source file:com.googlesource.gerrit.plugins.xdocs.XDocLoader.java
License:Apache License
private String loadHtml(FormatterProvider formatter, Repository repo, RevWalk rw, XDocResourceKey key, ObjectId revId)/* w ww. j a va2s. co m*/ throws IOException, ResourceNotFoundException, MethodNotAllowedException, GitAPIException { RevCommit commit = rw.parseCommit(revId); RevTree tree = commit.getTree(); try (TreeWalk tw = new TreeWalk(repo)) { tw.addTree(tree); tw.setRecursive(true); tw.setFilter(PathFilter.create(key.getResource())); if (!tw.next()) { return null; } ObjectId objectId = tw.getObjectId(0); ObjectLoader loader = repo.open(objectId); return getHtml(formatter, repo, loader, key.getProject(), key.getResource(), revId); } }