~sylvain-pineau/checkbox-core/bug983035

« back to all changes in this revision

Viewing changes to checkbox/scripts/convert.py

  • Committer: Marc Tardif
  • Date: 2012-04-12 18:58:39 UTC
  • Revision ID: marc.tardif@canonical.com-20120412185839-5lxr7972gntlpl2z
Added journal component.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
 
1
#
 
2
# Copyright (c) 2012 Canonical
 
3
#
 
4
# This file is part of Checkbox.
 
5
#
 
6
# Storm is free software; you can redistribute it and/or modify
 
7
# it under the terms of the GNU Lesser General Public License as
 
8
# published by the Free Software Foundation; either version 2.1 of
 
9
# the License, or (at your option) any later version.
 
10
#
 
11
# Storm is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
# GNU Lesser General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU Lesser General Public License
 
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
18
#
 
19
__metaclass__ = type
 
20
 
 
21
__all__ = [
 
22
    "run",
 
23
    ]
2
24
 
3
25
import re
4
26
import sys
5
27
import posixpath
6
28
 
7
 
from optparse import OptionParser
 
29
from optparse import OptionGroup
8
30
from StringIO import StringIO
9
31
 
10
32
from checkbox.lib.path import path_expand_recursive
16
38
from checkbox.message.record import Record
17
39
from checkbox.message.unparser import UnparserStream
18
40
 
 
41
from checkbox.scripts.application import (
 
42
    Application,
 
43
    ApplicationError,
 
44
    )
 
45
 
19
46
 
20
47
CONVERT_RE = re.compile(r"(\b(or|and|float)\b|')")
21
48
CONVERT_DICT = {'or': '||', 'and': '&&', 'float': 'real', "'": "\""}
22
49
CONVERT_REPL = lambda m: CONVERT_DICT[m.group(0)]
23
50
 
24
51
 
25
 
def convert_function(value):
26
 
    parser = Parser()
27
 
    value = CONVERT_RE.sub(CONVERT_REPL, value)
28
 
    file = StringIO(value)
29
 
    return parser.parseExpression(file, True)
30
 
 
31
 
 
32
 
def parse_file(file, *args, **kwargs):
33
 
    records = []
34
 
    template = Template()
35
 
    for section in template.loadFile(file):
36
 
        for key, value in section.iteritems():
37
 
            if key == "requires":
38
 
                section[key] = convert_function(value)
39
 
            elif key == "requires_extended":
40
 
                section[key] = List([convert_function(v)
41
 
                    for v in value.split("\n")])
42
 
            else:
43
 
                section[key] = Literal(value)
44
 
        record = Record(section)
45
 
        records.append(record)
46
 
 
47
 
    for record in records:
48
 
        print UnparserStream.unparseRecord(record)
49
 
 
50
 
 
51
 
def parse_path(path, *args, **kwargs):
52
 
    for filename in path_expand_recursive(path):
53
 
        name = posixpath.basename(filename)
54
 
        if name.startswith(".") or name.endswith("~"):
55
 
            continue
56
 
 
57
 
        file = open(filename, "r")
58
 
        parse_file(file, *args, **kwargs)
59
 
 
60
 
 
61
 
def parse_paths(paths, *args, **kwargs):
62
 
    for path in paths:
63
 
        parse_path(path, *args, **kwargs)
64
 
 
65
 
 
66
 
def main(args):
 
52
class ConvertApplication(Application):
 
53
 
 
54
    # Application defaults
67
55
    usage = "Usage: %prog [OPTIONS] [FILE...]"
68
 
    parser = OptionParser(usage=usage)
69
 
    parser.add_option("-a", "--attribute",
70
 
        action="append",
71
 
        type="string",
72
 
        default=[],
73
 
        help="Set additional attributes by name and value.")
74
 
    parser.add_option("-b", "--blacklist",
75
 
        action="append",
76
 
        type="string",
77
 
        default=[],
78
 
        help="Blacklist of elements by name and value.")
79
 
    parser.add_option("-w", "--whitelist",
80
 
        action="append",
81
 
        type="string",
82
 
        default=[],
83
 
        help="Whitelist of elements by name and value.")
84
 
    (options, args) = parser.parse_args(args)
85
 
 
86
 
    if args:
87
 
        parse_func = parse_paths
88
 
    else:
89
 
        parse_func = parse_file
90
 
        args = sys.stdin
91
 
 
92
 
    try:
93
 
        parse_func(
94
 
            args, options.attribute, options.whitelist, options.blacklist)
95
 
    except Exception, error:
96
 
        parser.error(error.args[0])
97
 
 
98
 
    return 0
99
 
 
100
 
 
101
 
if __name__ == "__main__":
102
 
    sys.exit(main(sys.argv[1:]))
 
56
 
 
57
    def addOptions(self, parser):
 
58
        """See Application."""
 
59
        super(ConvertApplication, self).addOptions(parser)
 
60
 
 
61
        group = OptionGroup(parser, "Convert options")
 
62
        group.add_option("-a", "--attribute",
 
63
            action="append",
 
64
            type="string",
 
65
            default=[],
 
66
            help="Set additional attributes by name and value.")
 
67
        group.add_option("-b", "--blacklist",
 
68
            action="append",
 
69
            type="string",
 
70
            default=[],
 
71
            help="Blacklist of elements by name and value.")
 
72
        group.add_option("-w", "--whitelist",
 
73
            action="append",
 
74
            type="string",
 
75
            default=[],
 
76
            help="Whitelist of elements by name and value.")
 
77
 
 
78
        parser.add_option_group(group)
 
79
 
 
80
    def parseOptions(self, options, args):
 
81
        """See Application."""
 
82
        super(ConvertApplication, self).parseOptions(options, args)
 
83
 
 
84
        if args:
 
85
            self.parse_func = self.parsePaths
 
86
        else:
 
87
            self.parse_func = self.parseFile
 
88
            args = sys.stdin
 
89
 
 
90
        self.args = [
 
91
            args, options.attribute, options.whitelist, options.blacklist]
 
92
 
 
93
    def process(self):
 
94
        """See Application."""
 
95
        try:
 
96
            self.parse_func(*self.args)
 
97
        except Exception, error:
 
98
            raise ApplicationError(error.args[0])
 
99
 
 
100
    def parsePaths(self, paths, *args, **kwargs):
 
101
        for path in paths:
 
102
            self.parsePath(path, *args, **kwargs)
 
103
 
 
104
    def parsePath(self, path, *args, **kwargs):
 
105
        for filename in path_expand_recursive(path):
 
106
            name = posixpath.basename(filename)
 
107
            if name.startswith(".") or name.endswith("~"):
 
108
                continue
 
109
 
 
110
            file = open(filename, "r")
 
111
            self.parseFile(file, *args, **kwargs)
 
112
 
 
113
    def parseFile(self, file, *args, **kwargs):
 
114
        records = []
 
115
        template = Template()
 
116
        for section in template.loadFile(file):
 
117
            for key, value in section.iteritems():
 
118
                if key == "requires":
 
119
                    section[key] = self.convertFunction(value)
 
120
                elif key == "requires_extended":
 
121
                    section[key] = List([self.convertFunction(v)
 
122
                        for v in value.split("\n")])
 
123
                else:
 
124
                    section[key] = Literal(value)
 
125
            record = Record(section)
 
126
            records.append(record)
 
127
 
 
128
        for record in records:
 
129
            print UnparserStream.unparseRecord(record)
 
130
 
 
131
    def convertFunction(self, value):
 
132
        parser = Parser()
 
133
        value = CONVERT_RE.sub(CONVERT_REPL, value)
 
134
        file = StringIO(value)
 
135
        return parser.parseExpression(file, True)
 
136
 
 
137
 
 
138
def run():
 
139
    application = ConvertApplication()
 
140
    application.run()