# Path: ansi2html.py
# def ansi2html(text, palette='solarized'):
#     def _ansi2html(m):
#         if m.group(2) != 'm':
#             return ''
#         import sys
#         state = None
#         sub = ''
#         cs = m.group(1)
#         cs = cs.strip() if cs else ''
#         for c in cs.split(';'):
#             c = c.strip().lstrip('0') or '0'
#             if c == '0':
#                 while stack:
#                     sub += '</span>'
#                     stack.pop()
#             elif c in ('38', '48'):
#                 extra = [c]
#                 state = 'extra'
#             elif state == 'extra':
#                 if c == '5':
#                     state = 'idx'
#                 elif c == '2':
#                     state = 'r'
#             elif state:
#                 if state == 'idx':
#                     extra.append(c)
#                     state = None
#                     # 256 colors
#                     color = indexed_style.get(c)  # TODO: convert index to RGB!
#                     if color is not None:
#                         sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color)
#                         stack.append(extra)
#                 elif state in ('r', 'g', 'b'):
#                     extra.append(c)
#                     if state == 'r':
#                         state = 'g'
#                     elif state == 'g':
#                         state = 'b'
#                     else:
#                         state = None
#                         try:
#                             color = '#' + ''.join('%02X' % c if 0 <= c <= 255 else None for x in extra for c in [int(x)])
#                         except (ValueError, TypeError):
#                             pass
#                         else:
#                             sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color)
#                             stack.append(extra)
#             else:
#                 if '1' in stack:
#                     style = bold_style.get(c)
#                 else:
#                     style = regular_style.get(c)
#                 if style is not None:
#                     sub += '<span style="%s">' % style
#                     stack.append(c)  # Still needs to be added to the stack even if style is empty (so it can check '1' in stack above, for example)
#         return sub
#     stack = []
#     regular_style, bold_style, indexed_style = _ansi2html_get_styles(palette)
#     sub = ANSI2HTML_CODES_RE.sub(_ansi2html, text)
#     while stack:
#         sub += '</span>'
#         stack.pop()
#     return sub
# 
# Path: database.py
# def init_db():


import os
import uuid
import json
import functools
import StringIO
import settings, utils
from datetime import datetime
from collections import namedtuple
from ansi2html import ansi2html
from flask import request, redirect, session, url_for, flash, render_template, jsonify, abort, send_file, Response
from web import app
from models import *
from database import db_session
    ls = db_session.query(BuildLog).filter(BuildLog.version_id == id).order_by(BuildLog.id.desc()).all()
    rs = db_session.query(TestRun).filter(TestRun.version_id == id).order_by(TestRun.id.desc()).all()
    ts = {t.id: t for t in db_session.query(Testcase)}
    count = get_build_phase_count(rs)
    watch_list = [r.id for r in rs if r.status not in ['passed', 'failed', 'timeout']]
    auto_refresh = v.status not in ['passed', 'failed']
    return render_template('build.html', compiler=c, version=v, build_logs=ls, 
        testruns=rs, testcases=ts, phase_count=count, auto_refresh=auto_refresh,
        watch_list=watch_list)


@app.route(settings.WEBROOT + '/ajax/build.json')
def ajax_build():
    try:
        stamp = int(request.args['stamp'])
        latest_id = int(request.args['latest_id'])
        id = int(request.args['build_id'])
        v = db_session.query(Version).filter(Version.id == id).first()
        if not v:
            return abort(404)

        lim = 10
        stamp = int(request.args['stamp'])
        qs = request.args.get('q', '').strip()
        qs = map(lambda q: int(q.strip()), qs.split(',')) if qs else []
        qs = sorted(qs)[:lim]
        watch = []
        for testrun_id in qs:
            r = db_session.query(TestRun).filter(TestRun.id == testrun_id).one()
            v = db_session.query(Version).filter(Version.id == r.version_id).one()

# Path: ansi2html.py
# def ansi2html(text, palette='solarized'):
#     def _ansi2html(m):
#         if m.group(2) != 'm':
#             return ''
#         import sys
#         state = None
#         sub = ''
#         cs = m.group(1)
#         cs = cs.strip() if cs else ''
#         for c in cs.split(';'):
#             c = c.strip().lstrip('0') or '0'
#             if c == '0':
#                 while stack:
#                     sub += '</span>'
#                     stack.pop()
#             elif c in ('38', '48'):
#                 extra = [c]
#                 state = 'extra'
#             elif state == 'extra':
#                 if c == '5':
#                     state = 'idx'
#                 elif c == '2':
#                     state = 'r'
#             elif state:
#                 if state == 'idx':
#                     extra.append(c)
#                     state = None
#                     # 256 colors
#                     color = indexed_style.get(c)  # TODO: convert index to RGB!
#                     if color is not None:
#                         sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color)
#                         stack.append(extra)
#                 elif state in ('r', 'g', 'b'):
#                     extra.append(c)
#                     if state == 'r':
#                         state = 'g'
#                     elif state == 'g':
#                         state = 'b'
#                     else:
#                         state = None
#                         try:
#                             color = '#' + ''.join('%02X' % c if 0 <= c <= 255 else None for x in extra for c in [int(x)])
#                         except (ValueError, TypeError):
#                             pass
#                         else:
#                             sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color)
#                             stack.append(extra)
#             else:
#                 if '1' in stack:
#                     style = bold_style.get(c)
#                 else:
#                     style = regular_style.get(c)
#                 if style is not None:
#                     sub += '<span style="%s">' % style
#                     stack.append(c)  # Still needs to be added to the stack even if style is empty (so it can check '1' in stack above, for example)
#         return sub
#     stack = []
#     regular_style, bold_style, indexed_style = _ansi2html_get_styles(palette)
#     sub = ANSI2HTML_CODES_RE.sub(_ansi2html, text)
#     while stack:
#         sub += '</span>'
#         stack.pop()
#     return sub
# 
# Path: database.py
# def init_db():


# Path: core/views.py
import os
import uuid
import json
import functools
import StringIO
import settings, utils
from datetime import datetime
from collections import namedtuple
from ansi2html import ansi2html
from flask import request, redirect, session, url_for, flash, render_template, jsonify, abort, send_file, Response
from web import app
from models import *
from database import db_session

    ls = db_session.query(BuildLog).filter(BuildLog.version_id == id).order_by(BuildLog.id.desc()).all()
    rs = db_session.query(TestRun).filter(TestRun.version_id == id).order_by(TestRun.id.desc()).all()
    ts = {t.id: t for t in db_session.query(Testcase)}
    count = get_build_phase_count(rs)
    watch_list = [r.id for r in rs if r.status not in ['passed', 'failed', 'timeout']]
    auto_refresh = v.status not in ['passed', 'failed']
    return render_template('build.html', compiler=c, version=v, build_logs=ls, 
        testruns=rs, testcases=ts, phase_count=count, auto_refresh=auto_refresh,
        watch_list=watch_list)


@app.route(settings.WEBROOT + '/ajax/build.json')
def ajax_build():
    try:
        stamp = int(request.args['stamp'])
        latest_id = int(request.args['latest_id'])
        id = int(request.args['build_id'])
        v = db_session.query(Version).filter(Version.id == id).first()
        if not v:
            return abort(404)

        lim = 10
        stamp = int(request.args['stamp'])
        qs = request.args.get('q', '').strip()
        qs = map(lambda q: int(q.strip()), qs.split(',')) if qs else []
        qs = sorted(qs)[:lim]
        watch = []
        for testrun_id in qs:
            r = db_session.query(TestRun).filter(TestRun.id == testrun_id).one()
            v = db_session.query(Version).filter(Version.id == r.version_id).one()

            c = db_session.query(Compiler).filter(Compiler.id == v.compiler_id).one()