xref: /qemu/scripts/tracetool/format/__init__.py (revision 12b35405)
1# -*- coding: utf-8 -*-
2
3"""
4Format management.
5
6
7Creating new formats
8--------------------
9
10A new format named 'foo-bar' corresponds to Python module
11'tracetool/format/foo_bar.py'.
12
13A format module should provide a docstring, whose first non-empty line will be
14considered its short description.
15
16All formats must generate their contents through the 'tracetool.out' routine.
17
18
19Format functions
20----------------
21
22======== ==================================================================
23Function Description
24======== ==================================================================
25generate Called to generate a format-specific file.
26======== ==================================================================
27
28"""
29
30__author__     = "Lluís Vilanova <vilanova@ac.upc.edu>"
31__copyright__  = "Copyright 2012-2014, Lluís Vilanova <vilanova@ac.upc.edu>"
32__license__    = "GPL version 2 or (at your option) any later version"
33
34__maintainer__ = "Stefan Hajnoczi"
35__email__      = "stefanha@redhat.com"
36
37
38import os
39
40import tracetool
41
42
43def get_list():
44    """Get a list of (name, description) pairs."""
45    res = []
46    modnames = []
47    for filename in os.listdir(tracetool.format.__path__[0]):
48        if filename.endswith('.py') and filename != '__init__.py':
49            modnames.append(filename.rsplit('.', 1)[0])
50    for modname in sorted(modnames):
51        module = tracetool.try_import("tracetool.format." + modname)
52
53        # just in case; should never fail unless non-module files are put there
54        if not module[0]:
55            continue
56        module = module[1]
57
58        doc = module.__doc__
59        if doc is None:
60            doc = ""
61        doc = doc.strip().split("\n")[0]
62
63        name = modname.replace("_", "-")
64        res.append((name, doc))
65    return res
66
67
68def exists(name):
69    """Return whether the given format exists."""
70    if len(name) == 0:
71        return False
72    name = name.replace("-", "_")
73    return tracetool.try_import("tracetool.format." + name)[1]
74
75
76def generate(events, format, backend, group):
77    if not exists(format):
78        raise ValueError("unknown format: %s" % format)
79    format = format.replace("-", "_")
80    func = tracetool.try_import("tracetool.format." + format,
81                                "generate")[1]
82    if func is None:
83        raise AttributeError("format has no 'generate': %s" % format)
84    func(events, backend, group)
85