1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""
5Format management.
6
7
8Creating new formats
9--------------------
10
11A new format named 'foo-bar' corresponds to Python module
12'tracetool/format/foo_bar.py'.
13
14A format module should provide a docstring, whose first non-empty line will be
15considered its short description.
16
17All formats must generate their contents through the 'tracetool.out' routine.
18
19
20Format functions
21----------------
22
23======== ==================================================================
24Function Description
25======== ==================================================================
26generate 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
39import os
40
41import tracetool
42
43
44def 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
69def 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
77def generate(events, format, backend, group):
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, group)
86