private TreeFormatter createTreeFormatter( Map<SubtreeConfig, RevCommit> parentCommits, String commitMessage) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { TreeWalk treeWalk = new TreeWalk(repository); try { treeWalk.setRecursive(false); addTrees(parentCommits, treeWalk); TreeFormatter treeFormatter = new TreeFormatter(); while (treeWalk.next()) { AbstractTreeIterator iterator = getSingleTreeIterator(treeWalk, commitMessage); if (iterator == null) { throw new IllegalStateException( "Tree walker did not return a single tree (should not happen): " + treeWalk.getPathString()); } treeFormatter.append( iterator.getEntryPathBuffer(), 0, iterator.getEntryPathLength(), iterator.getEntryFileMode(), iterator.getEntryObjectId()); } return treeFormatter; } finally { treeWalk.release(); } }
/** * Update any smudged entries with information from the working tree. * * @throws IOException */ private void updateSmudgedEntries() throws IOException { TreeWalk walk = new TreeWalk(repository); List<String> paths = new ArrayList<String>(128); try { for (int i = 0; i < entryCnt; i++) if (sortedEntries[i].isSmudged()) paths.add(sortedEntries[i].getPathString()); if (paths.isEmpty()) return; walk.setFilter(PathFilterGroup.createFromStrings(paths)); DirCacheIterator iIter = new DirCacheIterator(this); FileTreeIterator fIter = new FileTreeIterator(repository); walk.addTree(iIter); walk.addTree(fIter); walk.setRecursive(true); while (walk.next()) { iIter = walk.getTree(0, DirCacheIterator.class); if (iIter == null) continue; fIter = walk.getTree(1, FileTreeIterator.class); if (fIter == null) continue; DirCacheEntry entry = iIter.getDirCacheEntry(); if (entry.isSmudged() && iIter.idEqual(fIter)) { entry.setLength(fIter.getEntryLength()); entry.setLastModified(fIter.getEntryLastModified()); } } } finally { walk.release(); } }
/** * Checks if a file with the given path exists in the HEAD tree * * @param path * @return true if the file exists * @throws IOException */ private boolean inHead(String path) throws IOException { ObjectId headId = db.resolve(Constants.HEAD); RevWalk rw = new RevWalk(db); TreeWalk tw = null; try { tw = TreeWalk.forPath(db, path, rw.parseTree(headId)); return tw != null; } finally { rw.release(); rw.dispose(); if (tw != null) tw.release(); } }
/** * Compute the current projects that will be missing after the given branch is checked out * * @param branch * @param currentProjects * @return non-null but possibly empty array of missing projects */ private IProject[] getMissingProjects(String branch, IProject[] currentProjects) { if (delete || currentProjects.length == 0) return new IProject[0]; ObjectId targetTreeId; ObjectId currentTreeId; try { targetTreeId = repository.resolve(branch + "^{tree}"); // $NON-NLS-1$ currentTreeId = repository.resolve(Constants.HEAD + "^{tree}"); // $NON-NLS-1$ } catch (IOException e) { return new IProject[0]; } if (targetTreeId == null || currentTreeId == null) return new IProject[0]; Map<File, IProject> locations = new HashMap<File, IProject>(); for (IProject project : currentProjects) { IPath location = project.getLocation(); if (location == null) continue; location = location.append(IProjectDescription.DESCRIPTION_FILE_NAME); locations.put(location.toFile(), project); } List<IProject> toBeClosed = new ArrayList<IProject>(); File root = repository.getWorkTree(); TreeWalk walk = new TreeWalk(repository); try { walk.addTree(targetTreeId); walk.addTree(currentTreeId); walk.addTree(new FileTreeIterator(repository)); walk.setRecursive(true); walk.setFilter( AndTreeFilter.create( PathSuffixFilter.create(IProjectDescription.DESCRIPTION_FILE_NAME), TreeFilter.ANY_DIFF)); while (walk.next()) { AbstractTreeIterator targetIter = walk.getTree(0, AbstractTreeIterator.class); if (targetIter != null) continue; AbstractTreeIterator currentIter = walk.getTree(1, AbstractTreeIterator.class); AbstractTreeIterator workingIter = walk.getTree(2, AbstractTreeIterator.class); if (currentIter == null || workingIter == null) continue; IProject project = locations.get(new File(root, walk.getPathString())); if (project != null) toBeClosed.add(project); } } catch (IOException e) { return new IProject[0]; } finally { walk.release(); } return toBeClosed.toArray(new IProject[toBeClosed.size()]); }
/** * 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. * * @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 (!(path == null)) { 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()); Logger.error(e, e.getMessage()); } finally { tw.release(); } Collections.sort(list); return list; }
/** * Refreshes all resources that changed in the index since the last call to this method. This is * suitable for incremental updates on index changed events * * <p>For bare repositories this does nothing. */ private void refreshIndexDelta() { if (repository.isBare()) return; try { DirCache currentIndex = repository.readDirCache(); DirCache oldIndex = lastIndex; lastIndex = currentIndex; if (oldIndex == null) { refresh(); // full refresh in case we have no data to compare. return; } Set<String> paths = new TreeSet<String>(); TreeWalk walk = new TreeWalk(repository); try { walk.addTree(new DirCacheIterator(oldIndex)); walk.addTree(new DirCacheIterator(currentIndex)); walk.setFilter(new InterIndexDiffFilter()); while (walk.next()) { if (walk.isSubtree()) walk.enterSubtree(); else paths.add(walk.getPathString()); } } finally { walk.release(); } if (!paths.isEmpty()) refreshFiles(paths); } catch (IOException ex) { Activator.error( MessageFormat.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository), ex); scheduleReloadJob( "Exception while calculating index delta, doing full reload instead"); //$NON-NLS-1$ } }
public HistoryPanel( String wicketId, final String repositoryName, final String objectId, final String path, Repository r, int limit, int pageOffset, boolean showRemoteRefs) { super(wicketId); boolean pageResults = limit <= 0; int itemsPerPage = GitBlit.getInteger(Keys.web.itemsPerPage, 50); if (itemsPerPage <= 1) { itemsPerPage = 50; } RevCommit commit = JGitUtils.getCommit(r, objectId); List<PathChangeModel> paths = JGitUtils.getFilesInCommit(r, commit); Map<String, SubmoduleModel> submodules = new HashMap<String, SubmoduleModel>(); for (SubmoduleModel model : JGitUtils.getSubmodules(r, commit.getTree())) { submodules.put(model.path, model); } PathModel matchingPath = null; for (PathModel p : paths) { if (p.path.equals(path)) { matchingPath = p; break; } } if (matchingPath == null) { // path not in commit // manually locate path in tree TreeWalk tw = new TreeWalk(r); tw.reset(); tw.setRecursive(true); try { tw.addTree(commit.getTree()); tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); while (tw.next()) { if (tw.getPathString().equals(path)) { matchingPath = new PathChangeModel( tw.getPathString(), tw.getPathString(), 0, tw.getRawMode(0), tw.getObjectId(0).getName(), commit.getId().getName(), ChangeType.MODIFY); } } } catch (Exception e) { } finally { tw.release(); } } final boolean isTree = matchingPath == null ? true : matchingPath.isTree(); final boolean isSubmodule = matchingPath == null ? true : matchingPath.isSubmodule(); // submodule SubmoduleModel submodule = getSubmodule(submodules, repositoryName, matchingPath.path); final String submodulePath; final boolean hasSubmodule; if (submodule != null) { submodulePath = submodule.gitblitPath; hasSubmodule = submodule.hasSubmodule; } else { submodulePath = ""; hasSubmodule = false; } final Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(r, showRemoteRefs); List<RevCommit> commits; if (pageResults) { // Paging result set commits = JGitUtils.getRevLog(r, objectId, path, pageOffset * itemsPerPage, itemsPerPage); } else { // Fixed size result set commits = JGitUtils.getRevLog(r, objectId, path, 0, limit); } // inaccurate way to determine if there are more commits. // works unless commits.size() represents the exact end. hasMore = commits.size() >= itemsPerPage; add(new CommitHeaderPanel("commitHeader", repositoryName, commit)); // breadcrumbs add(new PathBreadcrumbsPanel("breadcrumbs", repositoryName, path, objectId)); final int hashLen = GitBlit.getInteger(Keys.web.shortCommitIdLength, 6); ListDataProvider<RevCommit> dp = new ListDataProvider<RevCommit>(commits); DataView<RevCommit> logView = new DataView<RevCommit>("commit", dp) { private static final long serialVersionUID = 1L; int counter; public void populateItem(final Item<RevCommit> item) { final RevCommit entry = item.getModelObject(); final Date date = JGitUtils.getCommitDate(entry); item.add( WicketUtils.createDateLabel("commitDate", date, getTimeZone(), getTimeUtils())); // author search link String author = entry.getAuthorIdent().getName(); LinkPanel authorLink = new LinkPanel( "commitAuthor", "list", author, GitSearchPage.class, WicketUtils.newSearchParameter( repositoryName, objectId, author, Constants.SearchType.AUTHOR)); setPersonSearchTooltip(authorLink, author, Constants.SearchType.AUTHOR); item.add(authorLink); // merge icon if (entry.getParentCount() > 1) { item.add(WicketUtils.newImage("commitIcon", "commit_merge_16x16.png")); } else { item.add(WicketUtils.newBlankImage("commitIcon")); } String shortMessage = entry.getShortMessage(); String trimmedMessage = shortMessage; if (allRefs.containsKey(entry.getId())) { trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG_REFS); } else { trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG); } LinkPanel shortlog = new LinkPanel( "commitShortMessage", "list subject", trimmedMessage, CommitPage.class, WicketUtils.newObjectParameter(repositoryName, entry.getName())); if (!shortMessage.equals(trimmedMessage)) { WicketUtils.setHtmlTooltip(shortlog, shortMessage); } item.add(shortlog); item.add(new RefsPanel("commitRefs", repositoryName, entry, allRefs)); if (isTree) { // tree item.add(new Label("hashLabel", getString("gb.tree") + "@")); LinkPanel commitHash = new LinkPanel( "hashLink", null, entry.getName().substring(0, hashLen), TreePage.class, WicketUtils.newObjectParameter(repositoryName, entry.getName())); WicketUtils.setCssClass(commitHash, "shortsha1"); WicketUtils.setHtmlTooltip(commitHash, entry.getName()); item.add(commitHash); Fragment links = new Fragment("historyLinks", "treeLinks", this); links.add( new BookmarkablePageLink<Void>( "commitdiff", CommitDiffPage.class, WicketUtils.newObjectParameter(repositoryName, entry.getName()))); item.add(links); } else if (isSubmodule) { // submodule item.add(new Label("hashLabel", submodulePath + "@")); Repository repository = GitBlit.self().getRepository(repositoryName); String submoduleId = JGitUtils.getSubmoduleCommitId(repository, path, entry); repository.close(); LinkPanel commitHash = new LinkPanel( "hashLink", null, submoduleId.substring(0, hashLen), TreePage.class, WicketUtils.newObjectParameter(submodulePath, submoduleId)); WicketUtils.setCssClass(commitHash, "shortsha1"); WicketUtils.setHtmlTooltip(commitHash, submoduleId); item.add(commitHash.setEnabled(hasSubmodule)); Fragment links = new Fragment("historyLinks", "treeLinks", this); links.add( new BookmarkablePageLink<Void>( "commitdiff", CommitDiffPage.class, WicketUtils.newObjectParameter(repositoryName, entry.getName()))); item.add(links); } else { // commit item.add(new Label("hashLabel", getString("gb.blob") + "@")); LinkPanel commitHash = new LinkPanel( "hashLink", null, entry.getName().substring(0, hashLen), BlobPage.class, WicketUtils.newPathParameter(repositoryName, entry.getName(), path)); WicketUtils.setCssClass(commitHash, "sha1"); WicketUtils.setHtmlTooltip(commitHash, entry.getName()); item.add(commitHash); Fragment links = new Fragment("historyLinks", "blobLinks", this); links.add( new BookmarkablePageLink<Void>( "commitdiff", CommitDiffPage.class, WicketUtils.newObjectParameter(repositoryName, entry.getName()))); links.add( new BookmarkablePageLink<Void>( "difftocurrent", BlobDiffPage.class, WicketUtils.newBlobDiffParameter( repositoryName, entry.getName(), objectId, path)) .setEnabled(counter > 0)); item.add(links); } WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(logView); // determine to show pager, more, or neither if (limit <= 0) { // no display limit add(new Label("moreHistory", "").setVisible(false)); } else { if (pageResults) { // paging add(new Label("moreHistory", "").setVisible(false)); } else { // more if (commits.size() == limit) { // show more add( new LinkPanel( "moreHistory", "link", new StringResourceModel("gb.moreHistory", this, null), HistoryPage.class, WicketUtils.newPathParameter(repositoryName, objectId, path))); } else { // no more add(new Label("moreHistory", "").setVisible(false)); } } } }
public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit) { 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()) { list.add( new PathChangeModel( tw.getPathString(), tw.getPathString(), 0, tw.getRawMode(0), commit.getId().getName(), ChangeType.ADD)); } tw.release(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { if (diff.getChangeType().equals(ChangeType.DELETE)) { list.add( new PathChangeModel( diff.getOldPath(), diff.getOldPath(), 0, diff.getNewMode().getBits(), commit.getId().getName(), diff.getChangeType())); } else { list.add( new PathChangeModel( diff.getNewPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), commit.getId().getName(), diff.getChangeType())); } } } } catch (Throwable t) { // todo Logger.error(t, t.getMessage()); } finally { rw.dispose(); } return list; }
@Override public List<CommitInfo> history( String objectId, String path, int limit, int pageOffset, boolean showRemoteRefs, int itemsPerPage) { try { if (itemsPerPage <= 1) { itemsPerPage = 50; } boolean pageResults = limit <= 0; Repository r = git.getRepository(); // TODO not sure if this is the right String we should use for the sub module stuff... String repositoryName = getConfigDirectory().getPath(); objectId = defaultObjectId(objectId); RevCommit commit = JGitUtils.getCommit(r, objectId); List<PathModel.PathChangeModel> paths = JGitUtils.getFilesInCommit(r, commit); Map<String, SubmoduleModel> submodules = new HashMap<String, SubmoduleModel>(); for (SubmoduleModel model : JGitUtils.getSubmodules(r, commit.getTree())) { submodules.put(model.path, model); } PathModel matchingPath = null; for (PathModel p : paths) { if (p.path.equals(path)) { matchingPath = p; break; } } if (matchingPath == null) { // path not in commit // manually locate path in tree TreeWalk tw = new TreeWalk(r); tw.reset(); tw.setRecursive(true); try { tw.addTree(commit.getTree()); tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); while (tw.next()) { if (tw.getPathString().equals(path)) { matchingPath = new PathModel.PathChangeModel( tw.getPathString(), tw.getPathString(), 0, tw.getRawMode(0), tw.getObjectId(0).getName(), commit.getId().getName(), ChangeType.MODIFY); } } } catch (Exception e) { } finally { tw.release(); } } final boolean isTree = matchingPath == null ? true : matchingPath.isTree(); final boolean isSubmodule = matchingPath == null ? true : matchingPath.isSubmodule(); // submodule SubmoduleModel submodule = null; if (matchingPath != null) { submodule = getSubmodule(submodules, repositoryName, matchingPath.path); } final String submodulePath; final boolean hasSubmodule; if (submodule != null) { submodulePath = submodule.gitblitPath; hasSubmodule = submodule.hasSubmodule; } else { submodulePath = ""; hasSubmodule = false; } final Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(r, showRemoteRefs); List<RevCommit> commits; if (pageResults) { // Paging result set commits = JGitUtils.getRevLog(r, objectId, path, pageOffset * itemsPerPage, itemsPerPage); } else { // Fixed size result set commits = JGitUtils.getRevLog(r, objectId, path, 0, limit); } // inaccurate way to determine if there are more commits. // works unless commits.size() represents the exact end. boolean hasMore = commits.size() >= itemsPerPage; List<CommitInfo> results = new ArrayList<CommitInfo>(); for (RevCommit entry : commits) { final Date date = JGitUtils.getCommitDate(entry); String author = entry.getAuthorIdent().getName(); boolean merge = entry.getParentCount() > 1; String shortMessage = entry.getShortMessage(); String trimmedMessage = shortMessage; if (allRefs.containsKey(entry.getId())) { trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG_REFS); } else { trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG); } String name = entry.getName(); String commitHashText = getShortCommitHash(name); String kind; if (isTree) { kind = "tree"; } else if (isSubmodule) { kind = "submodule"; } else kind = "file"; results.add( new CommitInfo( commitHashText, name, kind, author, date, merge, trimmedMessage, shortMessage)); } return results; } catch (Exception e) { throw new RuntimeIOException(e); } }
private void buildMaps( Repository repository, RevCommit baseCommit, RevCommit compareCommit, IProgressMonitor monitor) throws InterruptedException, IOException { monitor.beginTask(UIText.CompareTreeView_AnalyzingRepositoryTaskText, IProgressMonitor.UNKNOWN); boolean useIndex = compareVersion.equals(INDEX_VERSION); deletedPaths.clear(); equalContentPaths.clear(); baseVersionMap.clear(); compareVersionMap.clear(); compareVersionPathsWithChildren.clear(); addedPaths.clear(); baseVersionPathsWithChildren.clear(); boolean checkIgnored = false; TreeWalk tw = new TreeWalk(repository); try { int baseTreeIndex; if (baseCommit == null) { checkIgnored = true; baseTreeIndex = tw.addTree( new AdaptableFileTreeIterator( repository, ResourcesPlugin.getWorkspace().getRoot())); } else baseTreeIndex = tw.addTree( new CanonicalTreeParser(null, repository.newObjectReader(), baseCommit.getTree())); int compareTreeIndex; if (!useIndex) compareTreeIndex = tw.addTree( new CanonicalTreeParser( null, repository.newObjectReader(), compareCommit.getTree())); else compareTreeIndex = tw.addTree(new DirCacheIterator(repository.readDirCache())); if (input instanceof IResource[]) { IResource[] resources = (IResource[]) input; List<TreeFilter> orFilters = new ArrayList<TreeFilter>(resources.length); for (IResource resource : resources) { String relPath = repositoryMapping.getRepoRelativePath(resource); if (relPath.length() > 0) orFilters.add(PathFilter.create(relPath)); } if (orFilters.size() > 1) tw.setFilter(OrTreeFilter.create(orFilters)); else if (orFilters.size() == 1) tw.setFilter(orFilters.get(0)); } tw.setRecursive(true); if (monitor.isCanceled()) throw new InterruptedException(); while (tw.next()) { if (monitor.isCanceled()) throw new InterruptedException(); AbstractTreeIterator compareVersionIterator = tw.getTree(compareTreeIndex, AbstractTreeIterator.class); AbstractTreeIterator baseVersionIterator = tw.getTree(baseTreeIndex, AbstractTreeIterator.class); if (checkIgnored && baseVersionIterator != null && ((WorkingTreeIterator) baseVersionIterator).isEntryIgnored()) continue; if (compareVersionIterator != null && baseVersionIterator != null) { monitor.setTaskName(baseVersionIterator.getEntryPathString()); IPath currentPath = new Path(baseVersionIterator.getEntryPathString()); if (!useIndex) compareVersionMap.put( currentPath, GitFileRevision.inCommit( repository, compareCommit, baseVersionIterator.getEntryPathString(), tw.getObjectId(compareTreeIndex))); else compareVersionMap.put( currentPath, GitFileRevision.inIndex(repository, baseVersionIterator.getEntryPathString())); if (baseCommit != null) baseVersionMap.put( currentPath, GitFileRevision.inCommit( repository, baseCommit, baseVersionIterator.getEntryPathString(), tw.getObjectId(baseTreeIndex))); boolean equalContent = compareVersionIterator .getEntryObjectId() .equals(baseVersionIterator.getEntryObjectId()); if (equalContent) equalContentPaths.add(currentPath); if (equalContent && !showEquals) continue; while (currentPath.segmentCount() > 0) { currentPath = currentPath.removeLastSegments(1); if (!baseVersionPathsWithChildren.add(currentPath)) break; } } else if (baseVersionIterator != null && compareVersionIterator == null) { monitor.setTaskName(baseVersionIterator.getEntryPathString()); // only on base side IPath currentPath = new Path(baseVersionIterator.getEntryPathString()); addedPaths.add(currentPath); if (baseCommit != null) baseVersionMap.put( currentPath, GitFileRevision.inCommit( repository, baseCommit, baseVersionIterator.getEntryPathString(), tw.getObjectId(baseTreeIndex))); while (currentPath.segmentCount() > 0) { currentPath = currentPath.removeLastSegments(1); if (!baseVersionPathsWithChildren.add(currentPath)) break; } } else if (compareVersionIterator != null && baseVersionIterator == null) { monitor.setTaskName(compareVersionIterator.getEntryPathString()); // only on compare side IPath currentPath = new Path(compareVersionIterator.getEntryPathString()); deletedPaths.add(currentPath); List<PathNodeAdapter> children = compareVersionPathsWithChildren.get(currentPath.removeLastSegments(1)); if (children == null) { children = new ArrayList<PathNodeAdapter>(1); compareVersionPathsWithChildren.put(currentPath.removeLastSegments(1), children); } children.add(new PathNodeAdapter(new PathNode(currentPath, Type.FILE_DELETED))); if (!useIndex) compareVersionMap.put( currentPath, GitFileRevision.inCommit( repository, compareCommit, compareVersionIterator.getEntryPathString(), tw.getObjectId(compareTreeIndex))); else compareVersionMap.put( currentPath, GitFileRevision.inIndex(repository, compareVersionIterator.getEntryPathString())); } } } finally { tw.release(); monitor.done(); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { handleAuth(req); resp.setCharacterEncoding("UTF-8"); final PrintWriter out = resp.getWriter(); try { String pathInfo = req.getPathInfo(); Pattern pattern = Pattern.compile("/([^/]*)(?:/([^/]*)(?:/(.*))?)?"); Matcher matcher = pattern.matcher(pathInfo); matcher.matches(); String projectName = null; String refName = null; String filePath = null; if (matcher.groupCount() > 0) { projectName = matcher.group(1); refName = matcher.group(2); filePath = matcher.group(3); if (projectName == null || projectName.equals("")) { projectName = null; } else { projectName = java.net.URLDecoder.decode(projectName, "UTF-8"); } if (refName == null || refName.equals("")) { refName = null; } else { refName = java.net.URLDecoder.decode(refName, "UTF-8"); } if (filePath == null || filePath.equals("")) { filePath = null; } else { filePath = java.net.URLDecoder.decode(filePath, "UTF-8"); } } if (projectName != null) { if (filePath == null) filePath = ""; NameKey projName = NameKey.parse(projectName); ProjectControl control; try { control = projControlFactory.controlFor(projName); if (!control.isVisible()) { log.debug("Project not visible!"); resp.sendError( HttpServletResponse.SC_UNAUTHORIZED, "You need to be logged in to see private projects"); return; } } catch (NoSuchProjectException e1) { } Repository repo = repoManager.openRepository(projName); if (refName == null) { JSONArray contents = new JSONArray(); List<Ref> call; try { call = new Git(repo).branchList().call(); Git git = new Git(repo); for (Ref ref : call) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("name", ref.getName()); jsonObject.put("type", "ref"); jsonObject.put("size", "0"); jsonObject.put("path", ""); jsonObject.put("project", projectName); jsonObject.put("ref", ref.getName()); lastCommit(git, null, ref.getObjectId(), jsonObject); } catch (JSONException e) { } contents.put(jsonObject); } String response = contents.toString(); resp.setContentType("application/json"); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\""); log.debug(response); out.write(response); } catch (GitAPIException e) { } } else { Ref head = repo.getRef(refName); if (head == null) { JSONArray contents = new JSONArray(); String response = contents.toString(); resp.setContentType("application/json"); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\""); log.debug(response); out.write(response); return; } RevWalk walk = new RevWalk(repo); // add try catch to catch failures Git git = new Git(repo); RevCommit commit = walk.parseCommit(head.getObjectId()); RevTree tree = commit.getTree(); TreeWalk treeWalk = new TreeWalk(repo); treeWalk.addTree(tree); treeWalk.setRecursive(false); if (!filePath.equals("")) { PathFilter pathFilter = PathFilter.create(filePath); treeWalk.setFilter(pathFilter); } if (!treeWalk.next()) { CanonicalTreeParser canonicalTreeParser = treeWalk.getTree(0, CanonicalTreeParser.class); JSONArray contents = new JSONArray(); if (canonicalTreeParser != null) { while (!canonicalTreeParser.eof()) { String path = canonicalTreeParser.getEntryPathString(); FileMode mode = canonicalTreeParser.getEntryFileMode(); listEntry( path, mode.equals(FileMode.TREE) ? "dir" : "file", "0", path, projectName, head.getName(), git, contents); canonicalTreeParser.next(); } } String response = contents.toString(); resp.setContentType("application/json"); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("ETag", "\"" + tree.getId().getName() + "\""); log.debug(response); out.write(response); } else { // if (treeWalk.isSubtree()) { // treeWalk.enterSubtree(); // } JSONArray contents = getListEntries(treeWalk, repo, git, head, filePath, projectName); String response = contents.toString(); resp.setContentType("application/json"); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("ETag", "\"" + tree.getId().getName() + "\""); log.debug(response); out.write(response); } walk.release(); treeWalk.release(); } } } catch (RepositoryNotFoundException e) { handleException(resp, e, 400); } catch (MissingObjectException e) { // example "Missing unknown 7035305927ca125757ecd8407e608f6dcf0bd8a5" // usually indicative of being unable to locate a commit from a submodule log.error(e.getMessage(), e); String msg = e.getMessage() + ". This exception could have been caused by the use of a git submodule, " + "which is currently not supported by the repository browser."; handleException(resp, new Exception(msg), 501); } catch (IOException e) { handleException(resp, e, 500); } finally { out.close(); } }