List<Branch> branches = new ArrayList<Branch>(branchRefs.size());
for (Ref ref : branchRefs) {
if (nameFilter != null && !nameFilter.equals("")) {
String shortName = Repository.shortenRefName(ref.getName());
if (shortName.toLowerCase().contains(nameFilter.toLowerCase())) {
branches.add(new Branch(cloneLocation, db, ref));
}
} else {
branches.add(new Branch(cloneLocation, db, ref));
}
}
Collections.sort(branches, Branch.COMPARATOR);
JSONObject result = new JSONObject();
JSONArray children = new JSONArray();
int firstBranch = pageSize > 0 ? pageSize * (pageNo - 1) : 0;
int lastBranch = pageSize > 0 ? firstBranch + pageSize - 1 : branches.size() - 1;
lastBranch = lastBranch > branches.size() - 1 ? branches.size() - 1 : lastBranch;
if (pageNo > 1 && baseLocation != null) {
String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize;
if (nameFilter != null && !nameFilter.equals("")) {
prev += "&filter=" + GitUtils.encode(nameFilter);
}
if (commitsSize > 0) {
prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
}
result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev);
}
if (lastBranch < branches.size() - 1) {
String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize;
if (nameFilter != null && !nameFilter.equals("")) {
next += "&filter=" + GitUtils.encode(nameFilter);
}
if (commitsSize > 0) {
next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
}
result.put(ProtocolConstants.KEY_NEXT_LOCATION, next);
}
for (int i = firstBranch; i <= lastBranch; i++) {
Branch branch = branches.get(i);
if (commitsSize == 0) {
children.put(branch.toJSON());
} else {
String branchName = branch.getName(true, false);
ObjectId toObjectId = db.resolve(branchName);
Ref toRefId = db.getRef(branchName);
if (toObjectId == null) {
String msg = NLS.bind("No ref or commit found: {0}", branchName);
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null);
}
toObjectId = getCommitObjectId(db, toObjectId);
Log log = null;
// single commit is requested and we already know it, no need for LogCommand
if (commitsSize == 1 && toObjectId instanceof RevCommit) {
log = new Log(cloneLocation, db, Collections.singleton((RevCommit) toObjectId), null, null, toRefId);
} else {
LogCommand lc = git.log();
// set the commit range
lc.add(toObjectId);
lc.setMaxCount(this.commitsSize);
Iterable<RevCommit> commits = lc.call();
log = new Log(cloneLocation, db, commits, null, null, toRefId);
}
log.setPaging(1, commitsSize);
children.put(branch.toJSON(log.toJSON()));
}
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
result.put(ProtocolConstants.KEY_TYPE, Branch.TYPE);
return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);