root/pkgcore-checks/pkgcore_checks/report_stream.py @ ferringb%2540gmail.com-20080624174036-q45fk4fxguj9kjlv

Revision ferringb%2540gmail.com-20080624174036-q45fk4fxguj9kjlv, 4.2 kB (checked in by Brian Harring <ferringb@…>, 7 months ago)

punt trailing whitespace

Line 
1#!/usr/bin/python
2
3"""
4Replay a pickled results stream from pcheck, feeding the results into a
5reporter.
6
7Useful if you need to delay acting on results until it can be done in
8one minimal window (say updating a database), or want to generate
9several different reports without using a config defined multiplex reporter.
10"""
11
12from pkgcore_checks import base
13
14from pkgcore.util import commandline
15from snakeoil import demandload
16demandload.demandload(globals(),
17    'snakeoil:pickling,formatters',
18    'snakeoil.modules:load_attribute',
19    'pkgcore_checks:reporters',
20    'os',
21)
22
23
24class StreamHeader(object):
25
26    def __init__(self, checks, criteria):
27        self.checks = sorted((x for x in checks if x.known_results),
28            key=lambda x:x.__name__)
29        self.known_results = set()
30        for x in checks:
31            self.known_results.update(x.known_results)
32
33        self.known_results = tuple(sorted(self.known_results))
34        self.criteria = str(criteria)
35
36
37class PickleStream(base.Reporter):
38    """
39    Generate a stream of pickled objects.
40    For each specific target for checks, a header is pickled
41    detailing the checks used, possible results, and search
42    criteria.
43
44    """
45    priority = -1001
46    protocol = 0
47
48    def __init__(self, out):
49        """Initialize.
50
51        @type out: L{snakeoil.formatters.Formatter}.
52        """
53        base.Reporter.__init__(self)
54        self.out = out
55        self.dump = pickling.dump
56
57    def start(self):
58        self.out.wrap = False
59        self.out.autoline = False
60
61    def start_check(self, checks, target):
62        self.dump(StreamHeader(checks, target), self.out)
63
64    def add_report(self, result):
65        try:
66            self.dump(result, self.out, self.protocol)
67        except TypeError, t:
68            raise TypeError(result, str(t))
69
70
71class BinaryPickleStream(PickleStream):
72    """
73    Dump a binary pickle stream (highest protocol).
74    For details of the stream, see PickleStream
75    """
76    priority = -1002
77    protocol = -1
78
79
80class OptionParser(commandline.OptionParser):
81
82    def __init__(self, **kwargs):
83        commandline.OptionParser.__init__(self, description=__doc__,
84            usage="replay_report_stream <pickle-file> <python namespace path"
85            "reporter to replay it into>",
86            **kwargs)
87        self.add_option("--quiet", default=False, action='store_true',
88            help="disable all status information written to stderr.")
89        self.add_option("--out", default=None,
90            help="redirect reporters output to a file")
91
92    def check_values(self, values, args):
93        vals, args = commandline.OptionParser.check_values(self, values, args)
94
95        if len(args) < 2:
96            self.error("need at least two args, pickle file, and reporter")
97        elif len(args) > 2:
98            self.error("only two arguements are accepted")
99        args[0] = os.path.abspath(args[0])
100        if not os.path.isfile(args[0]):
101            self.error("pickle file %r doesn't exist" % args[0])
102        values.reporter = load_attribute(args[1])
103        values.stream_path = args[0]
104
105        return values, []
106
107
108def replay_stream(stream_handle, reporter, debug=None):
109    headers = []
110    last_count = 0
111    for count, item in enumerate(pickling.iter_stream(stream_handle)):
112        if isinstance(item, StreamHeader):
113            if debug:
114                if headers:
115                    debug.write("finished processing %i results for %s" %
116                        (count - last_count, headers[-1].criteria))
117                last_count = count
118                debug.write("encountered new stream header for %s" %
119                    item.criteria)
120            if headers:
121                reporter.end_check()
122            reporter.start_check(item.checks, item.criteria)
123            headers.append(item)
124            continue
125        reporter.add_report(item)
126    if headers:
127        reporter.end_check()
128        if debug:
129            debug.write("finished processing %i results for %s" %
130                (count - last_count, headers[-1].criteria))
131
132
133def main(options, out, err):
134    if options.out:
135        out = formatters.get_formatter(open(options.out, 'w'))
136    debug = None
137    if options.debug:
138        debug = err
139    replay_stream(open(options.stream_path), options.reporter(out),
140        debug=debug)
141    return 0
Note: See TracBrowser for help on using the browser.