Fix image urls.
[amitay/build-farm.git] / buildfarm / web / __init__.py
index 5f3b727659ec49da63bbd846b226024395c7b88b..f58cb9a699cb98ee8a3066a93870706c4975cde8 100755 (executable)
 #   along with this program; if not, write to the Free Software
 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
+"""Buildfarm web frontend."""
+
 # TODO: Allow filtering of the "Recent builds" list to show
 # e.g. only broken builds or only builds that you care about.
 
+from collections import defaultdict
 import os
 
 from buildfarm import (
-    data,
     hostdb,
     util,
     )
-from buildfarm.filecache import (
-    CachingBuildFarm,
+from buildfarm.build import (
+    LogFileMissing,
+    NoSuchBuildError,
+    NoTestOutput,
     )
 
 import cgi
+from pygments import highlight
+from pygments.lexers.text import DiffLexer
+from pygments.formatters import HtmlFormatter
 import re
 import time
 
 import wsgiref.util
 webdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "web"))
 
-
 GITWEB_BASE = "http://gitweb.samba.org"
 HISTORY_HORIZON = 1000
 
 # this is automatically filled in
 deadhosts = []
 
+def select(name, values, default=None):
+    yield "<select name='%s'>" % name
+    for key in sorted(values):
+        if key == default:
+            yield "<option selected value='%s'>%s</option>" % (key, values[key])
+        else:
+            yield "<option value='%s'>%s</option>" % (key, values[key])
+    yield "</select>"
+
+
 def get_param(form, param):
     """get a param from the request, after sanitizing it"""
     if param not in form:
@@ -68,15 +84,6 @@ def get_param(form, param):
     return result[0]
 
 
-def build_link(myself, tree, host, compiler, rev, status):
-    if rev:
-        opt_rev = ';revision=%s' % rev
-    else:
-        opt_rev = ''
-    return "<a href='%s?function=View+Build;host=%s;tree=%s;compiler=%s%s'>%s</a>" % (
-           myself, host, tree, compiler, opt_rev, status)
-
-
 def html_build_status(status):
     def span(classname, contents):
         return "<span class=\"%s\">%s</span>" % (classname, contents)
@@ -95,50 +102,58 @@ def html_build_status(status):
         else:
             return span("status failed", stage.result)
 
-    ostatus = ""
+    ostatus = []
     if "panic" in status.other_failures:
-        ostatus += "/"+span("status panic", "PANIC")
+        ostatus.append(span("status panic", "PANIC"))
     if "disk full" in status.other_failures:
-        ostatus += "/"+span("status failed", "disk full")
+        ostatus.append(span("status failed", "disk full"))
     if "timeout" in status.other_failures:
-        ostatus += "/"+span("status failed", "timeout")
+        ostatus.append(span("status failed", "timeout"))
     if "inconsistent test result" in status.other_failures:
-        ostatus += "/"+span("status failed", "unexpected return code")
+        ostatus.append(span("status failed", "unexpected return code"))
     bstatus = "/".join([span_status(s) for s in status.stages])
-    if bstatus == "":
-        bstatus = "?"
-    return bstatus + ostatus
+    ret = bstatus
+    if ostatus:
+        ret += "(%s)" % ",".join(ostatus)
+    if ret == "":
+        ret = "?"
+    return ret
+
 
+def build_uri(myself, build):
+    return "%s/build/%s" % (myself, build.log_checksum())
 
-def build_status_html(myself, build):
-    status = html_build_status(build.status())
-    return build_link(myself, build.tree, build.host, build.compiler, build.revision, status)
 
+def build_link(myself, build):
+    return "<a href='%s'>%s</a>" % (build_uri(myself, build), html_build_status(build.status()))
 
-def build_status_vals(status):
-    """translate a status into a set of int representing status"""
-    status = util.strip_html(status)
 
-    status = status.replace("ok", "0")
-    status = status.replace("-", "0")
-    status = status.replace("?", "0.1")
-    status = status.replace("PANIC", "1")
+def tree_uri(myself, tree):
+    return "%s/tree/%s" % (myself, tree.name)
 
-    return status.split("/")
+
+def tree_link(myself, tree):
+    """return a link to a particular tree"""
+    return "<a href='%s' title='View recent builds for %s'>%s:%s</a>" % (tree_uri(myself, tree), tree.name, tree.name, tree.branch)
+
+
+def host_uri(myself, host):
+    return "%s/host/%s" % (myself, host)
+
+def host_link(myself, host):
+    return "<a href='%s'>%s</a>" % (host_uri(myself, host), host)
+
+
+def revision_uri(myself, revision, tree):
+    return "%s?function=diff;tree=%s;revision=%s" % (myself, tree, revision)
 
 
 def revision_link(myself, revision, tree):
     """return a link to a particular revision"""
-
     if revision is None:
         return "unknown"
-
-    revision = revision.lstrip()
-    rev_short = revision
-    if len(revision) == 40:
-        rev_short = re.sub("(^.{7}).*", "\\1(git)", rev_short)
-
-    return "<a href='%s?function=diff;tree=%s;revision=%s' title='View Diff for %s'>%s</a>" % (myself, tree, revision, revision, rev_short)
+    return "<a href='%s' title='View Diff for %s'>%s</a>" % (
+        revision_uri(myself, revision, tree), revision, revision[:7])
 
 
 def subunit_to_buildfarm_result(subunit_result):
@@ -155,6 +170,7 @@ def subunit_to_buildfarm_result(subunit_result):
     else:
         return "unknown"
 
+
 def format_subunit_reason(reason):
     reason = re.sub("^\[\n+(.*?)\n+\]$", "\\1", reason)
     return "<div class=\"reason\">%s</div>" % reason
@@ -174,16 +190,16 @@ class LogPrettyPrinter(object):
              output = print_log_cc_checker(output)
 
         self.indice += 1
-        return make_collapsible_html('action', actionName, output, self.indice, status)
+        return "".join(make_collapsible_html('action', actionName, output, self.indice, status))
 
     # log is already CGI-escaped, so handle '>' in test name by handling &gt
     def _format_stage(self, m):
         self.indice += 1
-        return make_collapsible_html('test', m.group(1), m.group(2), self.indice, m.group(3))
+        return "".join(make_collapsible_html('test', m.group(1), m.group(2), self.indice, m.group(3)))
 
     def _format_skip_testsuite(self, m):
         self.indice += 1
-        return make_collapsible_html('test', m.group(1), '', self.indice, 'skipped')
+        return "".join(make_collapsible_html('test', m.group(1), '', self.indice, 'skipped'))
 
     def _format_testsuite(self, m):
         testName = m.group(1)
@@ -194,11 +210,11 @@ class LogPrettyPrinter(object):
         else:
             errorReason = ""
         self.indice += 1
-        return make_collapsible_html('test', testName, content+errorReason, self.indice, status)
+        return "".join(make_collapsible_html('test', testName, content+errorReason, self.indice, status))
 
     def _format_test(self, m):
         self.indice += 1
-        return make_collapsible_html('test', m.group(1), m.group(2)+format_subunit_reason(m.group(4)), self.indice, subunit_to_buildfarm_result(m.group(3)))
+        return "".join(make_collapsible_html('test', m.group(1), m.group(2)+format_subunit_reason(m.group(4)), self.indice, subunit_to_buildfarm_result(m.group(3))))
 
     def pretty_print(self, log):
         # do some pretty printing for the actions
@@ -254,7 +270,7 @@ def print_log_cc_checker(input):
         if line.startswith("-- "):
             # got a new entry
             if inEntry:
-                output += make_collapsible_html('cc_checker', title, content, id, status)
+                output += "".join(make_collapsible_html('cc_checker', title, content, id, status))
             else:
                 output += content
 
@@ -268,7 +284,7 @@ def print_log_cc_checker(input):
             (title, status, id) = ("%s %s" % (m.group(1), m.group(4)), m.group(2), m.group(3))
         elif line.startswith("CC_CHECKER STATUS"):
             if inEntry:
-                output += make_collapsible_html('cc_checker', title, content, id, status)
+                output += "".join(make_collapsible_html('cc_checker', title, content, id, status))
 
             inEntry = False
             content = ""
@@ -296,53 +312,25 @@ def make_collapsible_html(type, title, output, id, status=""):
     :param type: the logical type of it. e.g. "test" or "action"
     :param title: the title to be displayed
     """
-    if ((status == "" or "failed" == status.lower())):
-        icon = 'icon_hide_16.png'
+    if status.lower() in ("", "failed"):
+        icon = '/icon_hide_16.png'
     else:
-        icon = 'icon_unhide_16.png'
+        icon = '/icon_unhide_16.png'
 
     # trim leading and trailing whitespace
     output = output.strip()
 
     # note that we may be inside a <pre>, so we don't put any extra whitespace
     # in this html
-    ret = "<div class='%s unit %s' id='%s-%s'>" % (type, status, type, id)
-    ret += "<a href=\"javascript:handle('%s');\">" % id
-    ret += "<img id='img-%s' name='img-%s' alt='%s' src='%s' />" %(id, id, status, icon)
-    ret += "<div class='%s title'>%s</div></a>" % (type, title)
-    #ret += " "
-    ret += "<div class='%s status %s'>%s</div>" % (type, status, status)
-    ret += "<div class='%s output' id='output-%s'>" % (type, id)
-    if output and len(output):
-        ret += "<pre>%s</pre>>" % (output)
-    ret += "</div></div>"
-    return ret
-
-
-def diff_pretty(diff):
-    """pretty up a diff -u"""
-    # FIXME: JRV 20101109 Use pygments for this
-    ret = ""
-    lines = diff.splitlines()
-
-    line_types = {
-            'diff': 'diff_diff',
-            '=': 'diff_separator',
-            'Index:': 'diff_index',
-            'index': 'diff_index',
-            '-': 'diff_removed',
-            '+': 'diff_added',
-            '@@': 'diff_fragment_header'
-            }
-
-    for line in lines:
-        for r, cls in line_types.iteritems():
-            if line.startswith(r):
-                line = "<span class=\"%s\">%s</span>" % (cls, line)
-                continue
-        ret += line + "\n"
-
-    return ret
+    yield "<div class='%s unit %s' id='%s-%s'>" % (type, status, type, id)
+    yield "<a href=\"javascript:handle('%s');\">" % id
+    yield "<img id='img-%s' name='img-%s' alt='%s' src='%s' />" % (id, id, status, icon)
+    yield "<div class='%s title'>%s</div></a>" % (type, title)
+    yield "<div class='%s status %s'>%s</div>" % (type, status, status)
+    yield "<div class='%s output' id='output-%s'>" % (type, id)
+    if output:
+        yield "<pre>%s</pre>" % (output,)
+    yield "</div></div>"
 
 
 def web_paths(t, paths):
@@ -356,60 +344,6 @@ def web_paths(t, paths):
         raise Exception("Unknown scm %s" % t.scm)
 
 
-def history_row_html(myself, entry, tree, changes):
-    """show one row of history table"""
-    msg = cgi.escape(entry.message)
-    t = time.asctime(time.gmtime(entry.date))
-    age = util.dhm_time(time.time()-entry.date)
-
-    t = t.replace(" ", "&nbsp;")
-
-    yield """
-<div class=\"history_row\">
-    <div class=\"datetime\">
-        <span class=\"date\">%s</span><br />
-        <span class=\"age\">%s ago</span>""" % (t, age)
-    if entry.revision:
-        yield " - <span class=\"revision\">%s</span><br/>" % entry.revision
-        revision_url = "revision=%s" % entry.revision
-    else:
-        revision_url = "author=%s" % entry.author
-    yield """    </div>
-    <div class=\"diff\">
-        <span class=\"html\"><a href=\"%s?function=diff;tree=%s;date=%s;%s\">show diffs</a></span>
-    <br />
-        <span class=\"text\"><a href=\"%s?function=text_diff;tree=%s;date=%s;%s\">download diffs</a></span>
-        <br />
-        <div class=\"history_log_message\">
-            <pre>%s</pre>
-        </div>
-    </div>
-    <div class=\"author\">
-    <span class=\"label\">Author: </span>%s
-    </div>""" % (myself, tree.name, entry.date, revision_url,
-                 myself, tree.name, entry.date, revision_url,
-                 msg, entry.author)
-
-    (added, modified, removed) = changes
-
-    if modified:
-        yield "<div class=\"files\"><span class=\"label\">Modified: </span>"
-        yield web_paths(tree, modified)
-        yield "</div>\n"
-
-    if added:
-        yield "<div class=\"files\"><span class=\"label\">Added: </span>"
-        yield web_paths(tree, added)
-        yield "</div>\n"
-
-    if removed:
-        yield "<div class=\"files\"><span class=\"label\">Removed: </span>"
-        yield web_paths(tree, removed)
-        yield "</div>\n"
-
-    yield "</div>\n"
-
-
 def history_row_text(entry, tree, changes):
     """show one row of history table"""
     msg = cgi.escape(entry.message)
@@ -426,15 +360,6 @@ def history_row_text(entry, tree, changes):
     yield "\n\n%s\n\n\n" % msg
 
 
-def show_diff(diff, text_html):
-    if text_html == "html":
-        diff = cgi.escape(diff)
-        diff = diff_pretty(diff)
-        return "<pre>%s</pre>\n" % diff
-    else:
-        return "%s\n" % diff
-
-
 class BuildFarmPage(object):
 
     def __init__(self, buildfarm):
@@ -443,16 +368,9 @@ class BuildFarmPage(object):
     def red_age(self, age):
         """show an age as a string"""
         if age > self.buildfarm.OLDAGE:
-            return "<span clsas='old'>%s</span>" % util.dhm_time(age)
+            return "<span class='old'>%s</span>" % util.dhm_time(age)
         return util.dhm_time(age)
 
-    def tree_link(self, myself, tree):
-        # return a link to a particular tree
-        branch = ""
-        if tree in self.buildfarm.trees:
-            branch = ":%s" % self.buildfarm.trees[tree].branch
-
-        return "<a href='%s?function=Recent+Builds;tree=%s' title='View recent builds for %s'>%s%s</a>" % (myself, tree, tree, tree, branch)
 
     def render(self, output_type):
         raise NotImplementedError(self.render)
@@ -462,52 +380,40 @@ class ViewBuildPage(BuildFarmPage):
 
     def show_oldrevs(self, myself, tree, host, compiler):
         """show the available old revisions, if any"""
-        old_rev_builds  = self.buildfarm.builds.get_old_revs(tree, host, compiler)
+        old_builds = self.buildfarm.builds.get_old_builds(tree, host, compiler)
 
-        if len(old_rev_builds) == 0:
+        if not old_builds:
             return
 
-        yield "<h2>Older builds:</h2>"
+        yield "<h2>Older builds:</h2>\n"
 
-        yield "<table class='real'>"
-        yield "<thead><tr><th>Revision</th><th>Status</th></tr></thead>"
-        yield "<tbody>"
+        yield "<table class='real'>\n"
+        yield "<thead><tr><th>Revision</th><th>Status</th><th>Age</th></tr></thead>\n"
+        yield "<tbody>\n"
 
-        for build in old_rev_builds:
-            yield "<tr><td>%s</td><td>%s</td></tr>" % (
-                revision_link(myself, build.revision, tree),
-                build_link(myself, tree, host, compiler, build.revision,
-                    html_build_status(build.status())))
+        for old_build in old_builds:
+            yield "<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n" % (
+                revision_link(myself, old_build.revision, tree),
+                build_link(myself, old_build),
+                util.dhm_time(old_build.age))
 
-        yield "</tbody></table>"
+        yield "</tbody></table>\n"
 
-    def render(self, myself, tree, host, compiler, rev, plain_logs=False):
+    def render(self, myself, build, plain_logs=False):
         """view one build in detail"""
-        # ensure the params are valid before using them
-        self.buildfarm.hostdb.host(host)
-        assert compiler in self.buildfarm.compilers, "unknown compiler %s" % compiler
-        assert tree in self.buildfarm.trees, "not a build tree %s" % tree
-
-        uname = ""
-        cflags = ""
-        config = ""
-        build = buildfarm.get_build(tree, host, compiler, rev)
-        age_mtime = build.age_mtime()
-        try:
-            (revision, revision_time) = build.revision_details()
-        except data.MissingRevisionInfo:
-            revision = None
-
-        status = build_status_html(myself, build)
 
-        if rev:
-            assert re.match("^[0-9a-fA-F]*$", rev)
+        uname = None
+        cflags = None
+        config = None
 
-        f = build.read_log()
         try:
-            log = f.read()
-        finally:
-            f.close()
+            f = build.read_log()
+            try:
+                log = f.read()
+            finally:
+                f.close()
+        except LogFileMissing:
+            log = None
         f = build.read_err()
         try:
             err = f.read()
@@ -527,41 +433,48 @@ class ViewBuildPage(BuildFarmPage):
             if m:
                 config = m.group(1)
 
-        if err:
-            err = cgi.escape(err)
+        err = cgi.escape(err)
         yield '<h2>Host information:</h2>'
 
-        host_web_file = "../web/%s.html" % host
+        host_web_file = "../web/%s.html" % build.host
         if os.path.exists(host_web_file):
             yield util.FileLoad(host_web_file)
 
         yield "<table class='real'>\n"
         yield "<tr><td>Host:</td><td><a href='%s?function=View+Host;host=%s;tree=%s;"\
               "compiler=%s#'>%s</a> - %s</td></tr>\n" %\
-                (myself, host, tree, compiler, host, self.buildfarm.hostdb.host(host).platform.encode("utf-8"))
-        yield "<tr><td>Uname:</td><td>%s</td></tr>\n" % uname
-        yield "<tr><td>Tree:</td><td>%s</td></tr>\n" % self.tree_link(myself, tree)
-        yield "<tr><td>Build Revision:</td><td>%s</td></tr>\n" % revision_link(myself, revision, tree)
-        yield "<tr><td>Build age:</td><td><div class='age'>%s</div></td></tr>\n" % self.red_age(age_mtime)
-        yield "<tr><td>Status:</td><td>%s</td></tr>\n" % status
-        yield "<tr><td>Compiler:</td><td>%s</td></tr>\n" % compiler
-        yield "<tr><td>CFLAGS:</td><td>%s</td></tr>\n" % cflags
-        yield "<tr><td>configure options:</td><td>%s</td></tr>\n" % config
+                (myself, build.host, build.tree, build.compiler, build.host, self.buildfarm.hostdb[build.host].platform.encode("utf-8"))
+        if uname is not None:
+            yield "<tr><td>Uname:</td><td>%s</td></tr>\n" % uname
+        yield "<tr><td>Tree:</td><td>%s</td></tr>\n" % tree_link(myself, self.buildfarm.trees[build.tree])
+        yield "<tr><td>Build Revision:</td><td>%s</td></tr>\n" % revision_link(myself, build.revision, build.tree)
+        yield "<tr><td>Build age:</td><td><div class='age'>%s</div></td></tr>\n" % self.red_age(build.age)
+        yield "<tr><td>Status:</td><td>%s</td></tr>\n" % build_link(myself, build)
+        yield "<tr><td>Compiler:</td><td>%s</td></tr>\n" % build.compiler
+        if cflags is not None:
+            yield "<tr><td>CFLAGS:</td><td>%s</td></tr>\n" % cflags
+        if config is not None:
+            yield "<tr><td>configure options:</td><td>%s</td></tr>\n" % config
         yield "</table>\n"
 
-        yield "".join(self.show_oldrevs(myself, tree, host, compiler))
+        yield "".join(self.show_oldrevs(myself, build.tree, build.host, build.compiler))
 
         # check the head of the output for our magic string
         rev_var = ""
-        if rev:
-            rev_var = ";revision=%s" % rev
+        if build.revision:
+            rev_var = ";revision=%s" % build.revision
 
         yield "<div id='log'>"
 
+        yield "<p><a href='%s/+subunit'>Subunit output</a></p>" % build_uri(myself, build)
+        yield "<p><a href='%s/+stdout'>Standard output (as plain text)</a>, " % build_uri(myself, build)
+        yield "<a href='%s/+stderr'>Standard error (as plain text)</a>" % build_uri(myself, build)
+        yield "</p>"
+
         if not plain_logs:
             yield "<p>Switch to the <a href='%s?function=View+Build;host=%s;tree=%s"\
                   ";compiler=%s%s;plain=true' title='Switch to bland, non-javascript,"\
-                  " unstyled view'>Plain View</a></p>" % (myself, host, tree, compiler, rev_var)
+                  " unstyled view'>Plain View</a></p>" % (myself, build.host, build.tree, build.compiler, rev_var)
 
             yield "<div id='actionList'>"
             # These can be pretty wide -- perhaps we need to
@@ -570,9 +483,9 @@ class ViewBuildPage(BuildFarmPage):
                 yield "<h2>No error log available</h2>\n"
             else:
                 yield "<h2>Error log:</h2>"
-                yield make_collapsible_html('action', "Error Output", "\n%s" % err, "stderr-0", "errorlog")
+                yield "".join(make_collapsible_html('action', "Error Output", "\n%s" % err, "stderr-0", "errorlog"))
 
-            if log == "":
+            if log is None:
                 yield "<h2>No build log available</h2>"
             else:
                 yield "<h2>Build log:</h2>\n"
@@ -583,7 +496,7 @@ class ViewBuildPage(BuildFarmPage):
         else:
             yield "<p>Switch to the <a href='%s?function=View+Build;host=%s;tree=%s;"\
                   "compiler=%s%s' title='Switch to colourful, javascript-enabled, styled"\
-                  " view'>Enhanced View</a></p>" % (myself, host, tree, compiler, rev_var)
+                  " view'>Enhanced View</a></p>" % (myself, build.host, build.tree, build.compiler, rev_var)
             if err == "":
                 yield "<h2>No error log available</h2>"
             else:
@@ -600,56 +513,40 @@ class ViewBuildPage(BuildFarmPage):
 
 class ViewRecentBuildsPage(BuildFarmPage):
 
-    def render(self, myself, tree, sort_by):
+    def render(self, myself, tree, sort_by=None):
         """Draw the "recent builds" view"""
-        i = 0
-        cols = 2
-        broken = 0
-        last_host = ""
         all_builds = []
 
+        def build_platform(build):
+            try:
+                host = self.buildfarm.hostdb[build.host]
+            except hostdb.NoSuchHost:
+                return "UNKNOWN"
+            else:
+                return host.platform.encode("utf-8")
+
         cmp_funcs = {
-            "revision": lambda a, b: cmp(a[7], b[7]),
-            "age": lambda a, b: cmp(a[0], b[0]),
-            "host": lambda a, b: cmp(a[2], b[2]),
-            "platform": lambda a, b: cmp(a[1], b[1]),
-            "compiler": lambda a, b: cmp(a[3], b[3]),
-            "status": lambda a, b: cmp(a[6], b[6]),
+            "revision": lambda a, b: cmp(a.revision, b.revision),
+            "age": lambda a, b: cmp(a.age, b.age),
+            "host": lambda a, b: cmp(a.host, b.host),
+            "platform": lambda a, b: cmp(build_platform(a), build_platform(b)),
+            "compiler": lambda a, b: cmp(a.compiler, b.compiler),
+            "status": lambda a, b: cmp(a.status(), b.status()),
             }
 
-        assert tree in self.buildfarm.trees, "not a build tree"
-        assert sort_by in cmp_funcs, "not a valid sort"
+        if sort_by is None:
+            sort_by = "age"
 
-        t = self.buildfarm.trees[tree]
+        if sort_by not in cmp_funcs:
+            yield "not a valid sort mechanism: %r" % sort_by
+            return
 
-        for host in self.buildfarm.hostdb.hosts():
-            for compiler in self.buildfarm.compilers:
-                try:
-                    build = buildfarm.get_build(tree, host.name.encode("utf-8"), compiler)
-                    status = build_status_html(myself, build)
-                except data.NoSuchBuildError:
-                    pass
-                else:
-                    age_mtime = build.age_mtime()
-                    age_ctime = build.age_ctime()
-                    try:
-                        (revision, revision_time) = build.revision_details()
-                    except data.MissingRevisionInfo:
-                        pass
-                    else:
-                        all_builds.append([
-                            age_ctime,
-                            host.platform.encode("utf-8"),
-                            "<a href='%s?function=View+Host;host=%s;tree=%s;compiler=%s#%s'>%s</a>"
-                                % (myself, host.name.encode("utf-8"),
-                                   tree, compiler, host.name.encode("utf-8"),
-                                   host.name.encode("utf-8")),
-                            compiler, tree, status, build.status(),
-                            revision_link(myself, revision, tree),
-                            revision_time])
+        all_builds = list(self.buildfarm.get_tree_builds(tree))
 
         all_builds.sort(cmp_funcs[sort_by])
 
+        t = self.buildfarm.trees[tree]
+
         sorturl = "%s?tree=%s;function=Recent+Builds" % (myself, tree)
 
         yield "<div id='recent-builds' class='build-section'>"
@@ -668,13 +565,13 @@ class ViewRecentBuildsPage(BuildFarmPage):
 
         for build in all_builds:
             yield "<tr>"
-            yield "<td>%s</td>" % util.dhm_time(build[0])
-            yield "<td>%s</td>" % build[7]
-            yield "<td>%s</td>" % build[4]
-            yield "<td>%s</td>" % build[1]
-            yield "<td>%s</td>" % build[2]
-            yield "<td>%s</td>" % build[3]
-            yield "<td>%s</td>" % build[5]
+            yield "<td>%s</td>" % util.dhm_time(build.age)
+            yield "<td>%s</td>" % revision_link(myself, build.revision, build.tree)
+            yield "<td>%s</td>" % build.tree
+            yield "<td>%s</td>" % build_platform(build)
+            yield "<td>%s</td>" % host_link(myself, build.host)
+            yield "<td>%s</td>" % build.compiler
+            yield "<td>%s</td>" % build_link(myself, build)
             yield "</tr>"
         yield "</tbody></table>"
         yield "</div>"
@@ -682,76 +579,67 @@ class ViewRecentBuildsPage(BuildFarmPage):
 
 class ViewHostPage(BuildFarmPage):
 
-    def render(self, myself, output_type, *requested_hosts):
-        """print the host's table of information"""
+    def _render_build_list_header(self, host):
+        yield "<div class='host summary'>"
+        yield "<a id='host' name='host'/>"
+        yield "<h3>%s - %s</h3>" % (host.name, host.platform.encode("utf-8"))
+        yield "<table class='real'>"
+        yield "<thead><tr><th>Target</th><th>Build<br/>Revision</th><th>Build<br />Age</th><th>Status<br />config/build<br />install/test</th><th>Warnings</th></tr></thead>"
+        yield "<tbody>"
 
-        if output_type == 'text':
-            yield "Host summary:\n"
-        else:
-            yield "<div class='build-section' id='build-summary'>"
-            yield '<h2>Host summary:</h2>'
+    def _render_build_html(self, myself, build):
+        warnings = build.err_count()
+        yield "<tr>"
+        yield "<td><span class='tree'>" + tree_link(myself, self.buildfarm.trees[build.tree]) +"</span>/" + build.compiler + "</td>"
+        yield "<td>" + revision_link(myself, build.revision, build.tree) + "</td>"
+        yield "<td><div class='age'>" + self.red_age(build.age) + "</div></td>"
+        yield "<td><div class='status'>%s</div></td>" % build_link(myself, build)
+        yield "<td>%s</td>" % warnings
+        yield "</tr>"
+
+    def render_html(self, myself, *requested_hosts):
+        yield "<div class='build-section' id='build-summary'>"
+        yield '<h2>Host summary:</h2>'
+        for hostname in requested_hosts:
+            try:
+                host = self.buildfarm.hostdb[hostname]
+            except hostdb.NoSuchHost:
+                deadhosts.append(hostname)
+                continue
+            builds = list(self.buildfarm.get_host_builds(hostname))
+            if len(builds) > 0:
+                yield "".join(self._render_build_list_header(host))
+                for build in builds:
+                    yield "".join(self._render_build_html(myself, build))
+                yield "</tbody></table>"
+                yield "</div>"
+            else:
+                deadhosts.append(hostname)
+
+        yield "</div>"
+        yield "".join(self.draw_dead_hosts(*deadhosts))
+
+    def render_text(self, myself, *requested_hosts):
+        """print the host's table of information"""
+        yield "Host summary:\n"
 
         for host in requested_hosts:
             # make sure we have some data from it
             try:
-                self.buildfarm.hostdb.host(host)
+                self.buildfarm.hostdb[host]
             except hostdb.NoSuchHost:
                 continue
 
-            row = 0
-
-            for compiler in self.buildfarm.compilers:
-                for tree in sorted(self.buildfarm.trees.keys()):
-                    try:
-                        build = buildfarm.get_build(tree, host, compiler)
-                    except data.NoSuchBuildError:
-                        pass
-                    else:
-                        try:
-                            (revision, revision_time) = build.revision_details()
-                        except data.MissingRevisionInfo:
-                            revision = None
-                        age_mtime = build.age_mtime()
-                        age_ctime = build.age_ctime()
-                        warnings = build.err_count()
-                        status = build_status_html(myself, build)
-                        if row == 0:
-                            if output_type == 'text':
-                                yield "%-12s %-10s %-10s %-10s %-10s\n" % (
-                                        "Tree", "Compiler", "Build Age", "Status", "Warnings")
-                            else:
-                                yield "<div class='host summary'>"
-                                yield "<a id='host' name='host'/>"
-                                yield "<h3>%s - %s</h3>" % (host, self.buildfarm.hostdb.host(host).platform.encode("utf-8"))
-                                yield "<table class='real'>"
-                                yield "<thead><tr><th>Target</th><th>Build<br/>Revision</th><th>Build<br />Age</th><th>Status<br />config/build<br />install/test</th><th>Warnings</th></tr></thead>"
-                                yield "<tbody>"
-
-                        if output_type == 'text':
-                            yield "%-12s %-10s %-10s %-10s %-10s\n" % (
-                                    tree, compiler, util.dhm_time(age_mtime),
-                                    util.strip_html(status), warnings)
-                        else:
-                            yield "<tr>"
-                            yield "<td><span class='tree'>" + self.tree_link(myself, tree) +"</span>/" + compiler + "</td>"
-                            yield "<td>" + revision_link(myself, revision, tree) + "</td>"
-                            yield "<td><div class='age'>" + self.red_age(age_mtime) + "</div></td>"
-                            yield "<td><div class='status'>%s</div></td>" % status
-                            yield "<td>%s</td>" % warnings
-                            yield "</tr>"
-                        row+=1
-            if row != 0:
-                if output_type == 'text':
-                    yield "\n"
-                else:
-                    yield "</tbody></table>"
-                    yield "</div>"
-            else:
-                deadhosts.append(host)
-
-        if output_type != 'text':
-            yield "</div>"
-            yield "".join(self.draw_dead_hosts(*deadhosts))
+            builds = list(self.buildfarm.get_host_builds(host))
+            if len(builds) > 0:
+                yield "%-12s %-10s %-10s %-10s %-10s\n" % (
+                        "Tree", "Compiler", "Build Age", "Status", "Warnings")
+                for build in builds:
+                    yield "%-12s %-10s %-10s %-10s %-10s\n" % (
+                            build.tree, build.compiler,
+                            util.dhm_time(build.age),
+                            str(build.status()), build.err_count())
+                yield "\n"
 
     def draw_dead_hosts(self, *deadhosts):
         """Draw the "dead hosts" table"""
@@ -767,10 +655,14 @@ class ViewHostPage(BuildFarmPage):
         yield "<tbody>"
 
         for host in deadhosts:
-            age_ctime = self.buildfarm.hostdb.host_age(host)
+            last_build = self.buildfarm.host_last_build(host)
+            age = time.time() - last_build
+            try:
+                platform = self.buildfarm.hostdb[host].platform.encode("utf-8")
+            except hostdb.NoSuchHost:
+                platform = "UNKNOWN"
             yield "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %\
-                    (host, self.buildfarm.hostdb.host(host).platform.encode("utf-8"),
-                     util.dhm_time(age_ctime))
+                    (host, platform, util.dhm_time(age))
 
         yield "</tbody></table>"
         yield "</div>"
@@ -778,90 +670,141 @@ class ViewHostPage(BuildFarmPage):
 
 class ViewSummaryPage(BuildFarmPage):
 
-    def render(self, myself, output_type):
-        """view build summary"""
-        i = 0
-        cols = 2
-        broken = 0
-        broken_count = {}
-        panic_count = {}
-        host_count = {}
-
-        # zero broken and panic counters
-        for tree in self.buildfarm.trees:
-            broken_count[tree] = 0
-            panic_count[tree] = 0
-            host_count[tree] = 0
+    def _get_counts(self):
+        broken_count = defaultdict(lambda: 0)
+        panic_count = defaultdict(lambda: 0)
+        host_count = defaultdict(lambda: 0)
 
         # set up a variable to store the broken builds table's code, so we can
         # output when we want
         broken_table = ""
-        last_host = ""
 
+        builds = self.buildfarm.get_last_builds()
+
+        for build in builds:
+            host_count[build.tree]+=1
+            status = build.status()
+
+            if status.failed:
+                broken_count[build.tree]+=1
+                if "panic" in status.other_failures:
+                    panic_count[build.tree]+=1
+        return (host_count, broken_count, panic_count)
+
+    def render_text(self, myself):
+        (host_count, broken_count, panic_count) = self._get_counts()
         # for the text report, include the current time
-        if output_type == 'text':
-            t = time.gmtime()
-            yield "Build status as of %s\n\n" % t
+        yield "Build status as of %s\n\n" % time.asctime()
 
-        for host in self.buildfarm.hostdb.hosts():
-            for compiler in self.buildfarm.compilers:
-                for tree in self.buildfarm.trees:
-                    try:
-                        build = buildfarm.get_build(tree, host.name.encode("utf-8"), compiler)
-                        status = build_status_html(myself, build)
-                    except data.NoSuchBuildError:
-                        continue
-                    age_mtime = build.age_mtime()
-                    host_count[tree]+=1
-
-                    if "status failed" in status:
-                        broken_count[tree]+=1
-                        if "PANIC" in status:
-                            panic_count[tree]+=1
-
-        if output_type == 'text':
-            yield "Build counts:\n"
-            yield "%-12s %-6s %-6s %-6s\n" % ("Tree", "Total", "Broken", "Panic")
-        else:
-            yield "<div id='build-counts' class='build-section'>"
-            yield "<h2>Build counts:</h2>"
-            yield "<table class='real'>"
-            yield "<thead><tr><th>Tree</th><th>Total</th><th>Broken</th><th>Panic</th><th>Test coverage</th></tr></thead>"
-            yield "<tbody>"
+        yield "Build counts:\n"
+        yield "%-12s %-6s %-6s %-6s\n" % ("Tree", "Total", "Broken", "Panic")
+
+        for tree in sorted(self.buildfarm.trees.keys()):
+            yield "%-12s %-6s %-6s %-6s\n" % (tree, host_count[tree],
+                    broken_count[tree], panic_count[tree])
+        yield "\n"
+
+    def render_html(self, myself):
+        """view build summary"""
+
+        (host_count, broken_count, panic_count) = self._get_counts()
+
+        yield "<div id='build-counts' class='build-section'>"
+        yield "<h2>Build counts:</h2>"
+        yield "<table class='real'>"
+        yield "<thead><tr><th>Tree</th><th>Total</th><th>Broken</th><th>Panic</th><th>Test coverage</th></tr></thead>"
+        yield "<tbody>"
 
         for tree in sorted(self.buildfarm.trees.keys()):
-            if output_type == 'text':
-                yield "%-12s %-6s %-6s %-6s\n" % (tree, host_count[tree],
-                        broken_count[tree], panic_count[tree])
+            yield "<tr>"
+            yield "<td>%s</td>" % tree_link(myself, self.buildfarm.trees[tree])
+            yield "<td>%s</td>" % host_count[tree]
+            yield "<td>%s</td>" % broken_count[tree]
+            if panic_count[tree]:
+                    yield "<td class='panic'>"
             else:
-                yield "<tr>"
-                yield "<td>%s</td>" % self.tree_link(myself, tree)
-                yield "<td>%s</td>" % host_count[tree]
-                yield "<td>%s</td>" % broken_count[tree]
-                if panic_count[tree]:
-                        yield "<td class='panic'>"
+                    yield "<td>"
+            yield "%d</td>" % panic_count[tree]
+            try:
+                lcov_status = self.buildfarm.lcov_status(tree)
+            except NoSuchBuildError:
+                yield "<td></td>"
+            else:
+                if lcov_status is not None:
+                    yield "<td><a href=\"/lcov/data/%s/%s\">%s %%</a></td>" % (
+                        self.buildfarm.LCOVHOST, tree, lcov_status)
                 else:
-                        yield "<td>"
-                yield "%d</td>" % panic_count[tree]
-                try:
-                    lcov_status = buildfarm.lcov_status(tree)
-                except data.NoSuchBuildError:
                     yield "<td></td>"
-                else:
-                    if lcov_status is not None:
-                        yield "<td><a href=\"/lcov/data/%s/%s\">%s %%</a></td>" % (buildfarm.LCOVHOST, tree, lcov_status)
-                    else:
-                        yield "<td></td>"
-                yield "</tr>"
-
-        if output_type == 'text':
-            yield "\n"
+            yield "</tr>"
+
+        yield "</tbody></table>"
+        yield "</div>"
+
+
+class HistoryPage(BuildFarmPage):
+
+    def history_row_html(self, myself, entry, tree, changes):
+        """show one row of history table"""
+        msg = cgi.escape(entry.message)
+        t = time.asctime(time.gmtime(entry.date))
+        age = util.dhm_time(time.time()-entry.date)
+
+        t = t.replace(" ", "&nbsp;")
+
+        yield """
+    <div class=\"history_row\">
+        <div class=\"datetime\">
+            <span class=\"date\">%s</span><br />
+            <span class=\"age\">%s ago</span>""" % (t, age)
+        if entry.revision:
+            yield " - <span class=\"revision\">%s</span><br/>" % entry.revision
+            revision_url = "revision=%s" % entry.revision
         else:
-            yield "</tbody></table>"
-            yield "</div>"
+            revision_url = "author=%s" % entry.author
+        yield """    </div>
+        <div class=\"diff\">
+            <span class=\"html\"><a href=\"%s?function=diff;tree=%s;date=%s;%s\">show diffs</a></span>
+        <br />
+            <span class=\"text\"><a href=\"%s?function=text_diff;tree=%s;date=%s;%s\">download diffs</a></span>
+            <br />
+            <div class=\"history_log_message\">
+                <pre>%s</pre>
+            </div>
+        </div>
+        <div class=\"author\">
+        <span class=\"label\">Author: </span>%s
+        </div>""" % (myself, tree.name, entry.date, revision_url,
+                     myself, tree.name, entry.date, revision_url,
+                     msg, entry.author)
+
+        (added, modified, removed) = changes
+
+        if modified:
+            yield "<div class=\"files\"><span class=\"label\">Modified: </span>"
+            yield web_paths(tree, modified)
+            yield "</div>\n"
+
+        if added:
+            yield "<div class=\"files\"><span class=\"label\">Added: </span>"
+            yield web_paths(tree, added)
+            yield "</div>\n"
+
+        if removed:
+            yield "<div class=\"files\"><span class=\"label\">Removed: </span>"
+            yield web_paths(tree, removed)
+            yield "</div>\n"
+
+        builds = list(self.buildfarm.get_revision_builds(tree.name, entry.revision))
+        if builds:
+            yield "<div class=\"builds\">\n"
+            yield "<span class=\"label\">Builds: </span>\n"
+            for build in builds:
+                yield "%s(%s) " % (build_link(myself, build), host_link(myself, build.host))
+            yield "</div>\n"
+        yield "</div>\n"
 
 
-class DiffPage(BuildFarmPage):
+class DiffPage(HistoryPage):
 
     def render(self, myself, tree, revision):
         t = self.buildfarm.trees[tree]
@@ -872,11 +815,12 @@ class DiffPage(BuildFarmPage):
             tree, t.branch, revision)
         yield "<h2>%s</h2>" % title
         changes = branch.changes_summary(revision)
-        yield "".join(history_row_html(myself, entry, t, changes))
-        yield show_diff(diff, "html")
+        yield "".join(self.history_row_html(myself, entry, t, changes))
+        diff = highlight(diff, DiffLexer(), HtmlFormatter())
+        yield "<pre>%s</pre>\n" % diff.encode("utf-8")
 
 
-class RecentCheckinsPage(BuildFarmPage):
+class RecentCheckinsPage(HistoryPage):
 
     limit = 40
 
@@ -889,17 +833,14 @@ class RecentCheckinsPage(BuildFarmPage):
         for entry in branch.log(limit=HISTORY_HORIZON):
             m = re_author.match(entry.author)
             authors[m.group(2)] = m.group(1)
-            if author in ("ALL", "", m.group(2)):
+            if author in (None, "ALL", m.group(2)):
                 interesting.append(entry)
 
         yield "<h2>Recent checkins for %s (%s branch %s)</h2>\n" % (
             tree, t.scm, t.branch)
         yield "<form method='GET'>"
         yield "Select Author: "
-        yield "<select name='author'>"
-        for email in sorted(authors):
-            yield "<option value='%s'>%s</option>" % (email, authors[email])
-        yield "</select>"
+        yield "".join(select(name="author", values=authors, default=author))
         yield "<input type='submit' name='sub_function' value='Refresh'/>"
         yield "<input type='hidden' name='tree' value='%s'/>" % tree
         yield "<input type='hidden' name='function', value='Recent Checkins'/>"
@@ -907,7 +848,7 @@ class RecentCheckinsPage(BuildFarmPage):
 
         for entry in interesting[:self.limit]:
             changes = branch.changes_summary(entry.revision)
-            yield "".join(history_row_html(myself, entry, t, changes))
+            yield "".join(self.history_row_html(myself, entry, t, changes))
         yield "\n"
 
 
@@ -916,34 +857,54 @@ class BuildFarmApp(object):
     def __init__(self, buildfarm):
         self.buildfarm = buildfarm
 
-        # host.properties are unicode object and the framework expect string object
-        self.hosts = dict([(host.name.encode("utf-8"), host) for host in self.buildfarm.hostdb.hosts()])
-
-    def main_menu(self):
+    def main_menu(self, tree, host, compiler):
         """main page"""
 
-        yield "<form method='GET'>"
-        yield "<div id='build-menu'>"
-        yield "<select name='host'>"
-        for name, host in self.hosts.iteritems():
-            yield "<option value='%s'>%s -- %s</option>\n" % (name, host.platform.encode("utf-8"), name)
-        yield "</select>"
-        yield "<select name='tree'>"
-        for tree, t in self.buildfarm.trees.iteritems():
-            yield "<option value='%s'>%s:%s</option>\n" % (tree, tree, t.branch)
-        yield "</select>"
-        yield "<select name='compiler'>"
-        for compiler in self.buildfarm.compilers:
-            yield "<option>%s</option>\n" % compiler
-        yield "</select>"
-        yield "<br/>"
-        yield "<input type='submit' name='function' value='View Build'/>"
-        yield "<input type='submit' name='function' value='View Host'/>"
-        yield "<input type='submit' name='function' value='Recent Checkins'/>"
-        yield "<input type='submit' name='function' value='Summary'/>"
-        yield "<input type='submit' name='function' value='Recent Builds'/>"
-        yield "</div>"
-        yield "</form>"
+        yield "<form method='GET'>\n"
+        yield "<div id='build-menu'>\n"
+        host_dict = {}
+        for h in self.buildfarm.hostdb.hosts():
+            host_dict[h.name] = "%s -- %s" % (h.platform.encode("utf-8"), h.name)
+        yield "".join(select("host", host_dict, default=host))
+        tree_dict = {}
+        for t in self.buildfarm.trees.values():
+            tree_dict[t.name] = "%s:%s" % (t.name, t.branch)
+        yield "".join(select("tree", tree_dict, default=tree))
+        yield "".join(select("compiler", dict(zip(self.buildfarm.compilers, self.buildfarm.compilers)), default=compiler))
+        yield "<br/>\n"
+        yield "<input type='submit' name='function' value='View Build'/>\n"
+        yield "<input type='submit' name='function' value='View Host'/>\n"
+        yield "<input type='submit' name='function' value='Recent Checkins'/>\n"
+        yield "<input type='submit' name='function' value='Summary'/>\n"
+        yield "<input type='submit' name='function' value='Recent Builds'/>\n"
+        yield "</div>\n"
+        yield "</form>\n"
+
+    def html_page(self, form, lines):
+        yield "<html>\n"
+        yield "  <head>\n"
+        yield "    <title>samba.org build farm</title>\n"
+        yield "    <script language='javascript' src='/build_farm.js'></script>\n"
+        yield "    <meta name='keywords' contents='Samba SMB CIFS Build Farm'/>\n"
+        yield "    <meta name='description' contents='Home of the Samba Build Farm, the automated testing facility.'/>\n"
+        yield "    <meta name='robots' contents='noindex'/>"
+        yield "    <link rel='stylesheet' href='/build_farm.css' type='text/css' media='all'/>"
+        yield "    <link rel='stylesheet' href='http://master.samba.org/samba/style/common.css' type='text/css' media='all'/>"
+        yield "    <link rel='shortcut icon' href='http://www.samba.org/samba/images/favicon.ico'/>"
+        yield "  </head>"
+        yield "<body>"
+
+        yield util.FileLoad(os.path.join(webdir, "header2.html"))
+
+        tree = get_param(form, "tree")
+        host = get_param(form, "host")
+        compiler = get_param(form, "compiler")
+        yield "".join(self.main_menu(tree, host, compiler))
+        yield util.FileLoad(os.path.join(webdir, "header3.html"))
+        yield "".join(lines)
+        yield util.FileLoad(os.path.join(webdir, "footer.html"))
+        yield "</body>"
+        yield "</html>"
 
     def __call__(self, environ, start_response):
         form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
@@ -959,77 +920,120 @@ class BuildFarmApp(object):
             (entry, diff) = branch.diff(revision)
             changes = branch.changes_summary(revision)
             yield "".join(history_row_text(entry, tree, changes))
-            yield show_diff(diff, "text")
+            yield "%s\n" % diff
         elif fn_name == 'Text_Summary':
             start_response('200 OK', [('Content-type', 'text/plain')])
             page = ViewSummaryPage(self.buildfarm)
-            yield "".join(page.render(myself, 'text'))
-        else:
-            start_response('200 OK', [('Content-type', 'text/html')])
-
-            yield "<html>\n"
-            yield "  <head>\n"
-            yield "    <title>samba.org build farm</title>\n"
-            yield "    <script language='javascript' src='/build_farm.js'></script>\n"
-            yield "    <meta name='keywords' contents='Samba SMB CIFS Build Farm'/>\n"
-            yield "    <meta name='description' contents='Home of the Samba Build Farm, the automated testing facility.'/>\n"
-            yield "    <meta name='robots' contents='noindex'/>"
-            yield "    <link rel='stylesheet' href='/build_farm.css' type='text/css' media='all'/>"
-            yield "    <link rel='stylesheet' href='http://master.samba.org/samba/style/common.css' type='text/css' media='all'/>"
-            yield "    <link rel='shortcut icon' href='http://www.samba.org/samba/images/favicon.ico'/>"
-            yield "  </head>"
-            yield "<body>"
-
-            yield util.FileLoad(os.path.join(webdir, "header2.html"))
-            yield "".join(self.main_menu())
-            yield util.FileLoad(os.path.join(webdir, "header3.html"))
+            yield "".join(page.render_text(myself))
+        elif fn_name:
+            start_response('200 OK', [
+                ('Content-type', 'text/html; charset=utf-8')])
+
+            tree = get_param(form, "tree")
+            host = get_param(form, "host")
+            compiler = get_param(form, "compiler")
+
             if fn_name == "View_Build":
                 plain_logs = (get_param(form, "plain") is not None and get_param(form, "plain").lower() in ("yes", "1", "on", "true", "y"))
-                tree = get_param(form, "tree")
-                host = get_param(form, "host")
-                compiler = get_param(form, "compiler")
-                page = ViewBuildPage(self.buildfarm)
-                yield "".join(page.render(myself, tree, host, compiler, get_param(form, "revision"), plain_logs))
+                revision = get_param(form, "revision")
+                checksum = get_param(form, "checksum")
+                try:
+                    build = self.buildfarm.get_build(tree, host,
+                        compiler, revision, checksum=checksum)
+                except NoSuchBuildError:
+                    yield "No such build: %s on %s with %s, rev %r, checksum %r" % (
+                        tree, host, compiler, revision, checksum)
+                else:
+                    page = ViewBuildPage(self.buildfarm)
+                    plain_logs = (get_param(form, "plain") is not None and get_param(form, "plain").lower() in ("yes", "1", "on", "true", "y"))
+                    yield "".join(self.html_page(form, page.render(myself, build, plain_logs)))
             elif fn_name == "View_Host":
                 page = ViewHostPage(self.buildfarm)
-                yield "".join(page.render(myself, "html", get_param(form, 'host')))
+                yield "".join(self.html_page(form, page.render_html(myself, get_param(form, 'host'))))
             elif fn_name == "Recent_Builds":
                 page = ViewRecentBuildsPage(self.buildfarm)
-                yield "".join(page.render(myself, get_param(form, "tree"), get_param(form, "sortby") or "revision"))
+                yield "".join(self.html_page(form, page.render(myself, get_param(form, "tree"), get_param(form, "sortby") or "age")))
             elif fn_name == "Recent_Checkins":
                 # validate the tree
-                tree =  get_param(form, "tree")
                 author = get_param(form, 'author')
                 page = RecentCheckinsPage(self.buildfarm)
-                yield "".join(page.render(myself, tree, author))
+                yield "".join(self.html_page(form, page.render(myself, tree, author)))
             elif fn_name == "diff":
-                tree =  get_param(form, "tree")
                 revision = get_param(form, 'revision')
                 page = DiffPage(self.buildfarm)
-                yield "".join(page.render(myself, tree, revision))
-            elif os.getenv("PATH_INFO") not in (None, "", "/"):
-                paths = os.getenv("PATH_INFO").split('/')
-                if paths[1] == "recent":
-                    page = ViewRecentBuildsPage(self.buildfarm)
-                    yield "".join(page.render(myself, paths[2], get_param(form, 'sortby') or 'revision'))
-                elif paths[1] == "host":
-                    page = ViewHostPage(self.buildfarm)
-                    yield "".join(page.render(myself, "html", paths[2]))
+                yield "".join(self.html_page(form, page.render(myself, tree, revision)))
+            elif fn_name == "Summary":
+                page = ViewSummaryPage(self.buildfarm)
+                yield "".join(self.html_page(form, page.render_html(myself)))
             else:
+                yield "Unknown function %s" % fn_name
+        else:
+            fn = wsgiref.util.shift_path_info(environ)
+            if fn == "tree":
+                start_response('200 OK', [
+                    ('Content-type', 'text/html; charset=utf-8')])
+                tree = wsgiref.util.shift_path_info(environ)
+                subfn = wsgiref.util.shift_path_info(environ)
+                if subfn in ("", None, "+recent"):
+                    page = ViewRecentBuildsPage(self.buildfarm)
+                    yield "".join(self.html_page(form, page.render(myself, tree, get_param(form, 'sortby') or 'age')))
+                else:
+                    yield "Unknown subfn %s" % subfn
+            elif fn == "host":
+                start_response('200 OK', [
+                    ('Content-type', 'text/html; charset=utf-8')])
+                page = ViewHostPage(self.buildfarm)
+                yield "".join(self.html_page(form, page.render_html(myself, wsgiref.util.shift_path_info(environ))))
+            elif fn == "build":
+                build_checksum = wsgiref.util.shift_path_info(environ)
+                build = self.buildfarm.builds.get_by_checksum(build_checksum)
+                page = ViewBuildPage(self.buildfarm)
+                subfn = wsgiref.util.shift_path_info(environ)
+                if subfn == "+plain":
+                    start_response('200 OK', [
+                        ('Content-type', 'text/html; charset=utf-8')])
+                    yield "".join(page.render(myself, build, True))
+                elif subfn == "+subunit":
+                    start_response('200 OK', [
+                        ('Content-type', 'text/x-subunit; charset=utf-8'),
+                        ('Content-Disposition', 'attachment; filename="%s.%s.%s-%s.subunit"' % (build.tree, build.host, build.compiler, build.revision))])
+                    try:
+                        yield build.read_subunit().read()
+                    except NoTestOutput:
+                        yield "There was no test output"
+                elif subfn == "+stdout":
+                    start_response('200 OK', [
+                        ('Content-type', 'text/plain; charset=utf-8'),
+                        ('Content-Disposition', 'attachment; filename="%s.%s.%s-%s.log"' % (build.tree, build.host, build.compiler, build.revision))])
+                    yield build.read_log().read()
+                elif subfn == "+stderr":
+                    start_response('200 OK', [
+                        ('Content-type', 'text/plain; charset=utf-8'),
+                        ('Content-Disposition', 'attachment; filename="%s.%s.%s-%s.err"' % (build.tree, build.host, build.compiler, build.revision))])
+                    yield build.read_err().read()
+                elif subfn in ("", None):
+                    start_response('200 OK', [
+                        ('Content-type', 'text/html; charset=utf-8')])
+                    yield "".join(self.html_page(form, page.render(myself, build, False)))
+            elif fn in ("", None):
+                start_response('200 OK', [
+                    ('Content-type', 'text/html; charset=utf-8')])
                 page = ViewSummaryPage(self.buildfarm)
-                yield "".join(page.render(myself, 'html'))
-            yield util.FileLoad(os.path.join(webdir, "footer.html"))
-            yield "</body>"
-            yield "</html>"
+                yield "".join(self.html_page(form, page.render_html(myself)))
+            else:
+                start_response('404 Page Not Found', [
+                    ('Content-type', 'text/html; charset=utf-8')])
+                yield "Unknown function %s" % fn
 
 
 if __name__ == '__main__':
     import optparse
     parser = optparse.OptionParser("[options]")
-    parser.add_option("--cachedirname", help="Cache directory name", type=str)
-    parser.add_option("--port", help="Port to listen on [localhost:8000]", default="localhost:8000", type=str)
+    parser.add_option("--port", help="Port to listen on [localhost:8000]",
+        default="localhost:8000", type=str)
     opts, args = parser.parse_args()
-    buildfarm = CachingBuildFarm(cachedirname=opts.cachedirname)
+    from buildfarm import BuildFarm
+    buildfarm = BuildFarm()
     buildApp = BuildFarmApp(buildfarm)
     from wsgiref.simple_server import make_server
     import mimetypes