1import collections, re
2import common
3from autotest_lib.client.common_lib import log
4
5
6statuses = log.job_statuses
7
8
9def is_worse_than(lhs, rhs):
10    """ Compare two statuses and return a boolean indicating if the LHS status
11    is worse than the RHS status."""
12    return (statuses.index(lhs) < statuses.index(rhs))
13
14
15def is_worse_than_or_equal_to(lhs, rhs):
16    """ Compare two statuses and return a boolean indicating if the LHS status
17    is worse than or equal to the RHS status."""
18    if lhs == rhs:
19        return True
20    return is_worse_than(lhs, rhs)
21
22
23DEFAULT_BLACKLIST = ('\r\x00',)
24def clean_raw_line(raw_line, blacklist=DEFAULT_BLACKLIST):
25    """Strip blacklisted characters from raw_line."""
26    return re.sub('|'.join(blacklist), '', raw_line)
27
28
29class status_stack(object):
30    def __init__(self):
31        self.status_stack = [statuses[-1]]
32
33
34    def current_status(self):
35        return self.status_stack[-1]
36
37
38    def update(self, new_status):
39        if new_status not in statuses:
40            return
41        if is_worse_than(new_status, self.current_status()):
42            self.status_stack[-1] = new_status
43
44
45    def start(self):
46        self.status_stack.append(statuses[-1])
47
48
49    def end(self):
50        result = self.status_stack.pop()
51        if len(self.status_stack) == 0:
52            self.status_stack.append(statuses[-1])
53        return result
54
55
56    def size(self):
57        return len(self.status_stack) - 1
58
59
60class line_buffer(object):
61    def __init__(self):
62        self.buffer = collections.deque()
63
64
65    def get(self):
66        return self.buffer.pop()
67
68
69    def put(self, line):
70        self.buffer.appendleft(line)
71
72
73    def put_multiple(self, lines):
74        self.buffer.extendleft(lines)
75
76
77    def put_back(self, line):
78        self.buffer.append(line)
79
80
81    def size(self):
82        return len(self.buffer)
83
84
85def parser(version):
86    library = "autotest_lib.tko.parsers.version_%d" % version
87    module = __import__(library, globals(), locals(), ["parser"])
88    return module.parser()
89