aboutsummaryrefslogtreecommitdiff
path: root/crosperf/table.py
blob: 84eb21ae1b6b3f3628c56109ead426749a16667a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/python

# Copyright 2011 Google Inc. All Rights Reserved.

import math


class Table(object):
  class Cell(object):
    def __init__(self, value, colspan=1, hidden=False, header=False):
      self.value = value
      self.colspan = colspan
      self.hidden = hidden
      self.header = header

  def __init__(self, table_id):
    self.table_id = table_id
    self.rows = []

  def AddRow(self, row):
    self.rows.append(row)

  def ToHTML(self):
    res = "<table id='%s'>\n" % self.table_id
    for row in self.rows:
      res += "<tr>"
      for cell in row:
        if cell.header:
          tag = "th"
        else:
          tag = "td"
        cell_class = ""
        if cell.hidden:
          cell_class = "class='hidden'"
        res += "<%s colspan='%s' %s>%s</%s>" % (tag, cell.colspan, cell_class,
                                                cell.value, tag)
      res += "</tr>\n"
    res += "</table>"
    return res

  def ToText(self, max_column_width=None):
    col_spacing = 2
    max_widths = []
    for row in self.rows:
      column = 0
      for cell in row:
        text_width = len(str(cell.value))
        per_column_width = int(math.ceil(float(text_width) / cell.colspan))
        if max_column_width:
          per_column_width = min(max_column_width, per_column_width)
        for i in range(column, column + cell.colspan):
          while i >= len(max_widths):
            max_widths.append(0)
          max_widths[i] = max(per_column_width, max_widths[i])
        column += cell.colspan

    res = ""
    for row in self.rows:
      column = 0
      for cell in row:
        val = str(cell.value)
        if max_column_width:
          if len(val) > max_column_width:
            val = val[:2] + ".." + val[len(val) - (max_column_width - 4):]
        res += val
        space_to_use = (sum(max_widths[column:column + cell.colspan]) +
                        (cell.colspan * col_spacing))
        whitespace_length = space_to_use - len(val)
        res += " " * whitespace_length
        # Add space b/w columns
        column += cell.colspan
      res += "\n"
    return res

  def ToTSV(self):
    res = ""
    column = 0
    for row in self.rows:
      for cell in row:
        res += str(cell.value).replace("\t", "    ")
        for _ in range(column, column + cell.colspan):
          res += "\t"
      res += "\n"
    return res