blob: 3fb439c1a45b34eea3f9f3717aa25096e86102a9 [file] [log] [blame] [raw]
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gitiles;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.eclipse.jgit.lib.Constants.OBJ_COMMIT;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gitiles.PathServlet.FileType;
import com.google.gitiles.doc.MarkdownConfig;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.util.RawParseUtils;
/** Soy data converter for git trees. */
public class TreeSoyData {
/**
* Number of characters to display for a symlink target. Targets longer than this are abbreviated
* for display in a tree listing.
*/
private static final int MAX_SYMLINK_TARGET_LENGTH = 72;
/**
* Maximum number of bytes to load from a blob that claims to be a symlink. If the blob is larger
* than this byte limit it will be displayed as a binary file instead of as a symlink.
*/
static final int MAX_SYMLINK_SIZE = 16 << 10;
static String resolveTargetUrl(GitilesView view, String target, String req_path) {
String resolved = PathUtil.simplifyPathUpToRoot(target, view.getPathPart());
if (resolved == null) {
return null;
}
return GitilesView.path().copyFrom(view).setPathPart(resolved).toUrl(req_path);
}
@VisibleForTesting
static String getTargetDisplayName(String target) {
if (target.length() <= MAX_SYMLINK_TARGET_LENGTH) {
return target;
}
int lastSlash = target.lastIndexOf('/');
// TODO(dborowitz): Doesn't abbreviate a long last path component.
return lastSlash >= 0 ? "..." + target.substring(lastSlash) : target;
}
private final ObjectReader reader;
private final GitilesView view;
private final Config cfg;
private final RevTree rootTree;
private final String requestUri;
private final String req_rel_path;
private ArchiveFormat archiveFormat;
public TreeSoyData(
ObjectReader reader, GitilesView view, Config cfg, RevTree rootTree, String requestUri, String req_rel_path) {
this.reader = reader;
this.view = view;
this.cfg = cfg;
this.rootTree = rootTree;
this.requestUri = requestUri;
this.req_rel_path = req_rel_path;
}
public TreeSoyData setArchiveFormat(ArchiveFormat archiveFormat) {
this.archiveFormat = archiveFormat;
return this;
}
private boolean should_autodive_link() {
String value = cfg.getString("gitiles", null, "AutoDivingStyle");
if(value == null) return false;
switch(value.toLowerCase()) {
case "link":
case "both":
return true;
default:
return false;
}
}
private static CanonicalTreeParser getOnlyChildSubtree(ObjectReader reader, ObjectId id, byte[] prefix)
throws IOException {
CanonicalTreeParser p = new CanonicalTreeParser(prefix, reader, id);
if (p.eof() || p.getEntryFileMode() != FileMode.TREE) {
return null;
}
p.next(1);
return p.eof() ? p : null;
}
public static CanonicalTreeParser getFurthestOnlyChildSubtree(ObjectReader reader, ObjectId id, String path_s) throws IOException {
byte[] path = Constants.encode(path_s);
CanonicalTreeParser child = getOnlyChildSubtree(reader, id, path);
if(child == null) return null;
while (true) {
path = new byte[child.getEntryPathLength()];
System.arraycopy(child.getEntryPathBuffer(), 0, path, 0, child.getEntryPathLength());
CanonicalTreeParser next = getOnlyChildSubtree(reader, child.getEntryObjectId(), path);
if (next == null) return child;
child = next;
}
}
public Map<String, Object> toSoyData(ObjectId treeId, TreeWalk tw)
throws MissingObjectException, IOException {
ReadmeHelper readme =
new ReadmeHelper(reader, view, MarkdownConfig.get(cfg), rootTree, requestUri);
List<Object> entries = Lists.newArrayList();
GitilesView.Builder urlBuilder = GitilesView.path().copyFrom(view);
while (tw.next()) {
FileType type = FileType.forEntry(tw);
String name = tw.getNameString();
if (type == FileType.TREE) name += "/";
GitilesView.Type viewType = view.getType();
if (viewType == GitilesView.Type.PATH) {
urlBuilder.setPathPart(view.getPathPart() + "/" + name, true);
} else if (viewType == GitilesView.Type.REVISION) {
// Got here from a tag pointing at a tree.
urlBuilder.setPathPart(name, true);
} else {
throw new IllegalStateException(
String.format("Cannot render TreeSoyData from %s view", viewType));
}
if(type == FileType.TREE && should_autodive_link()) {
CanonicalTreeParser child = getFurthestOnlyChildSubtree(reader, tw.getObjectId(0), urlBuilder.getPathPart());
if(child != null) {
StringBuilder path = new StringBuilder(
RawParseUtils.decode(child.getEntryPathBuffer(), 0, child.getEntryPathLength())
);
path.append('/');
urlBuilder.setPathPart(path.toString(), true);
if(viewType == GitilesView.Type.PATH) {
int strip_len = view.getPathPart().length();
if(strip_len > 0) path.delete(0, strip_len + 1);
}
name = path.toString();
}
}
String url = urlBuilder.toUrl(req_rel_path);
Map<String, String> entry = Maps.newHashMapWithExpectedSize(4);
entry.put("type", type.toString());
entry.put("name", name);
entry.put("url", url);
if (type == FileType.SYMLINK) {
String target = new String(reader.open(tw.getObjectId(0)).getCachedBytes(), UTF_8);
entry.put("targetName", getTargetDisplayName(target));
String targetUrl = resolveTargetUrl(view, target, req_rel_path);
if (targetUrl != null) {
entry.put("targetUrl", targetUrl);
}
}
readme.considerEntry(treeId, tw);
entries.add(entry);
}
Map<String, Object> data = Maps.newHashMapWithExpectedSize(3);
data.put("sha", treeId.name());
data.put("entries", entries);
if (view.getType() == GitilesView.Type.PATH
&& view.getRevision().getPeeledType() == OBJ_COMMIT) {
data.put("logUrl", GitilesView.log().copyFrom(view).toUrl(req_rel_path));
data.put(
"archiveUrl",
GitilesView.archive()
.copyFrom(view)
.setPathPart(Strings.emptyToNull(view.getPathPart()))
.setExtension(archiveFormat.getDefaultSuffix())
.toUrl(req_rel_path));
}
if (readme.isPresent()) {
data.put("readmePath", readme.getPath());
data.put("readmeHtml", readme.render());
}
return data;
}
public Map<String, Object> toSoyData(ObjectId treeId) throws MissingObjectException, IOException {
TreeWalk tw = new TreeWalk(reader);
tw.addTree(treeId);
tw.setRecursive(false);
return toSoyData(treeId, tw);
}
}