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