source: rtems-tools/rtemstoolkit/macros.py @ fa81491

5
Last change on this file since fa81491 was 1676b9c, checked in by Chris Johns <chrisj@…>, on 08/18/16 at 04:24:13

rtemstoolkit: Trace opening a macro file.

  • Property mode set to 100644
File size: 19.1 KB
Line 
1#
2# RTEMS Tools Project (http://www.rtems.org/)
3# Copyright 2010-2016 Chris Johns (chrisj@rtems.org)
4# All rights reserved.
5#
6# This file is part of the RTEMS Tools package in 'rtems-tools'.
7#
8# Redistribution and use in source and binary forms, with or without
9# modification, are permitted provided that the following conditions are met:
10#
11# 1. Redistributions of source code must retain the above copyright notice,
12# this list of conditions and the following disclaimer.
13#
14# 2. Redistributions in binary form must reproduce the above copyright notice,
15# this list of conditions and the following disclaimer in the documentation
16# and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29#
30
31#
32# Macro tables.
33#
34
35from __future__ import print_function
36
37import copy
38import inspect
39import re
40import os
41import string
42
43#
44# Support to handle use in a package and as a unit test.
45# If there is a better way to let us know.
46#
47try:
48    from . import error
49    from . import log
50    from . import path
51except (ValueError, SystemError):
52    import error
53    import log
54    import path
55
56#
57# Macro tables
58#
59class macros:
60
61    class macro_iterator:
62        def __init__(self, keys):
63            self.keys = keys
64            self.index = 0
65
66        def __iter__(self):
67            return self
68
69        def __next__(self):
70            if self.index < len(self.keys):
71                key = self.keys[self.index]
72                self.index += 1
73                return key
74            raise StopIteration
75
76        def iterkeys(self):
77            return self.keys
78
79    def _unicode_to_str(self, us):
80        try:
81            if type(us) == unicode:
82                return us.encode('ascii', 'replace')
83        except:
84            pass
85        try:
86            if type(us) == bytes:
87                return us.encode('ascii', 'replace')
88        except:
89            pass
90        return us
91
92    def __init__(self, name = None, original = None, rtdir = '.'):
93        self.files = []
94        self.macro_filter = re.compile(r'%{[^}]+}')
95        if original is None:
96            self.macros = {}
97            self.read_maps = []
98            self.read_map_locked = False
99            self.write_map = 'global'
100            self.rtpath = path.abspath(path.dirname(inspect.getfile(macros)))
101            if path.dirname(self.rtpath).endswith('/share/rtems'):
102                self.prefix = path.dirname(self.rtpath)[:-len('/share/rtems')]
103            else:
104                self.prefix = '.'
105            self.macros['global'] = {}
106            self.macros['global']['nil'] = ('none', 'none', '')
107            self.macros['global']['_cwd'] = ('dir',
108                                             'required',
109                                             path.abspath(os.getcwd()))
110            self.macros['global']['_prefix'] = ('dir', 'required', self.prefix)
111            self.macros['global']['_rtdir'] = ('dir',
112                                               'required',
113                                               path.abspath(self.expand(rtdir)))
114            self.macros['global']['_rttop'] = ('dir', 'required', self.prefix)
115        else:
116            self.macros = {}
117            for m in original.macros:
118                if m not in self.macros:
119                    self.macros[m] = {}
120                for k in original.macros[m]:
121                    self.macros[m][k] = copy.copy(original.macros[m][k])
122            self.read_maps = sorted(copy.copy(original.read_maps))
123            self.read_map_locked = copy.copy(original.read_map_locked)
124            self.write_map = copy.copy(original.write_map)
125        if name is not None:
126            self.load(name)
127
128    def __copy__(self):
129        return macros(original = self)
130
131    def __str__(self):
132        text_len = 80
133        text = ''
134        for f in self.files:
135            text += '> %s%s' % (f, os.linesep)
136        for map in self.macros:
137            if map in self.read_maps:
138                if self.read_map_locked:
139                    rm = 'R'
140                else:
141                    rm = 'r'
142            else:
143                rm = '-'
144            if map == self.write_map:
145                wm = 'w'
146            else:
147                wm = '-'
148            text += '[%s] %s%s%s' % (map, rm, wm, os.linesep)
149            for k in sorted(self.macros[map].keys()):
150                d = self.macros[map][k]
151                text += " %s:%s '%s'%s '%s'%s" % \
152                    (k, ' ' * (20 - len(k)),
153                     d[0], ' ' * (8 - len(d[0])),
154                     d[1], ' ' * (10 - len(d[1])))
155                if len(d[2]) == 0:
156                    text += "''%s" % (os.linesep)
157                else:
158                    if '\n' in d[2]:
159                        text += "'''"
160                    else:
161                        text += "'"
162                indent = False
163                ds = d[2].split('\n')
164                lc = 0
165                for l in ds:
166                    lc += 1
167                    while len(l):
168                        if indent:
169                            text += ' %21s %10s %12s' % (' ', ' ', ' ')
170                        text += l[0:text_len]
171                        l = l[text_len:]
172                        if len(l):
173                            text += ' \\'
174                        elif lc == len(ds):
175                            if len(ds) > 1:
176                                text += "'''"
177                            else:
178                                text += "'"
179                        text += '%s' % (os.linesep)
180                        indent = True
181        return text
182
183    def __iter__(self):
184        return macros.macro_iterator(self.keys())
185
186    def __getitem__(self, key):
187        macro = self.get(key)
188        if macro is None or macro[1] == 'undefine':
189            raise IndexError('key: %s' % (key))
190        return macro[2]
191
192    def __setitem__(self, key, value):
193        key = self._unicode_to_str(key)
194        if type(key) is not str:
195            raise TypeError('bad key type (want str): %s' % (type(key)))
196        if type(value) is not tuple:
197            value = self._unicode_to_str(value)
198        if type(value) is str:
199            value = ('none', 'none', value)
200        if type(value) is not tuple:
201            raise TypeError('bad value type (want tuple): %s' % (type(value)))
202        if len(value) != 3:
203            raise TypeError('bad value tuple (len not 3): %d' % (len(value)))
204        value = (self._unicode_to_str(value[0]),
205                 self._unicode_to_str(value[1]),
206                 self._unicode_to_str(value[2]))
207        if type(value[0]) is not str:
208            raise TypeError('bad value tuple type field: %s' % (type(value[0])))
209        if type(value[1]) is not str:
210            raise TypeError('bad value tuple attrib field: %s' % (type(value[1])))
211        if type(value[2]) is not str:
212            raise TypeError('bad value tuple value field: %s' % (type(value[2])))
213        if value[0] not in ['none', 'triplet', 'dir', 'file', 'exe']:
214            raise TypeError('bad value tuple (type field): %s' % (value[0]))
215        if value[1] not in ['none', 'optional', 'required',
216                            'override', 'undefine', 'convert']:
217            raise TypeError('bad value tuple (attrib field): %s' % (value[1]))
218        if value[1] == 'convert':
219            value = self.expand(value)
220        self.macros[self.write_map][self.key_filter(key)] = value
221
222    def __delitem__(self, key):
223        self.undefine(key)
224
225    def __contains__(self, key):
226        return self.has_key(key)
227
228    def __len__(self):
229        return len(list(self.keys()))
230
231    def keys(self):
232        keys = list(self.macros['global'].keys())
233        for rm in self.get_read_maps():
234            for mk in self.macros[rm]:
235                if self.macros[rm][mk][1] == 'undefine':
236                    if mk in keys:
237                        keys.remove(mk)
238                else:
239                    keys.append(mk)
240        return sorted(set(keys))
241
242    def has_key(self, key):
243        if type(key) is not str:
244            raise TypeError('bad key type (want str): %s' % (type(key)))
245        if self.key_filter(key) not in list(self.keys()):
246            return False
247        return True
248
249    def maps(self):
250        return self.macros.keys()
251
252    def get_read_maps(self):
253        return [rm[5:] for rm in self.read_maps]
254
255    def key_filter(self, key):
256        if key.startswith('%{') and key[-1] is '}':
257            key = key[2:-1]
258        return key.lower()
259
260    def parse(self, lines):
261
262        def _clean(l):
263            if '#' in l:
264                l = l[:l.index('#')]
265            if '\r' in l:
266                l = l[:l.index('r')]
267            if '\n' in l:
268                l = l[:l.index('\n')]
269            return l.strip()
270
271        trace_me = False
272        if trace_me:
273            print('[[[[]]]] parsing macros')
274        orig_macros = copy.copy(self.macros)
275        map = 'global'
276        lc = 0
277        state = 'key'
278        token = ''
279        macro = []
280        for l in lines:
281            lc += 1
282            #print 'l:%s' % (l[:-1])
283            if len(l) == 0:
284                continue
285            l_remaining = l
286            for c in l:
287                if trace_me:
288                    print(']]]]]]]] c:%s(%d) s:%s t:"%s" m:%r M:%s' % \
289                        (c, ord(c), state, token, macro, map))
290                l_remaining = l_remaining[1:]
291                if c is '#' and not state.startswith('value'):
292                    break
293                if c == '\n' or c == '\r':
294                    if not (state is 'key' and len(token) == 0) and \
295                            not state.startswith('value-multiline'):
296                        self.macros = orig_macros
297                        raise error.general('malformed macro line:%d: %s' % (lc, l))
298                if state is 'key':
299                    if c not in string.whitespace:
300                        if c is '[':
301                            state = 'map'
302                        elif c is '%':
303                            state = 'directive'
304                        elif c is ':':
305                            macro += [token]
306                            token = ''
307                            state = 'attribs'
308                        elif c is '#':
309                            break
310                        else:
311                            token += c
312                elif state is 'map':
313                    if c is ']':
314                        if token not in self.macros:
315                            self.macros[token] = {}
316                        map = token
317                        token = ''
318                        state = 'key'
319                    elif c in string.printable and c not in string.whitespace:
320                        token += c
321                    else:
322                        self.macros = orig_macros
323                        raise error.general('invalid macro map:%d: %s' % (lc, l))
324                elif state is 'directive':
325                    if c in string.whitespace:
326                        if token == 'include':
327                            self.load(_clean(l_remaining))
328                            token = ''
329                            state = 'key'
330                            break
331                    elif c in string.printable and c not in string.whitespace:
332                        token += c
333                    else:
334                        self.macros = orig_macros
335                        raise error.general('invalid macro directive:%d: %s' % (lc, l))
336                elif state is 'include':
337                    if c is string.whitespace:
338                        if token == 'include':
339                            state = 'include'
340                    elif c in string.printable and c not in string.whitespace:
341                        token += c
342                    else:
343                        self.macros = orig_macros
344                        raise error.general('invalid macro directive:%d: %s' % (lc, l))
345                elif state is 'attribs':
346                    if c not in string.whitespace:
347                        if c is ',':
348                            macro += [token]
349                            token = ''
350                            if len(macro) == 3:
351                                state = 'value-start'
352                        else:
353                            token += c
354                elif state is 'value-start':
355                    if c is "'":
356                        state = 'value-line-start'
357                elif state is 'value-line-start':
358                    if c is "'":
359                        state = 'value-multiline-start'
360                    else:
361                        state = 'value-line'
362                        token += c
363                elif state is 'value-multiline-start':
364                    if c is "'":
365                        state = 'value-multiline'
366                    else:
367                        macro += [token]
368                        state = 'macro'
369                elif state is 'value-line':
370                    if c is "'":
371                        macro += [token]
372                        state = 'macro'
373                    else:
374                        token += c
375                elif state is 'value-multiline':
376                    if c is "'":
377                        state = 'value-multiline-end'
378                    else:
379                        token += c
380                elif state is 'value-multiline-end':
381                    if c is "'":
382                        state = 'value-multiline-end-end'
383                    else:
384                        state = 'value-multiline'
385                        token += "'" + c
386                elif state is 'value-multiline-end-end':
387                    if c is "'":
388                        macro += [token]
389                        state = 'macro'
390                    else:
391                        state = 'value-multiline'
392                        token += "''" + c
393                else:
394                    self.macros = orig_macros
395                    raise error.internal('bad state: %s' % (state))
396                if state is 'macro':
397                    self.macros[map][macro[0].lower()] = (macro[1], macro[2], macro[3])
398                    macro = []
399                    token = ''
400                    state = 'key'
401
402    def load(self, name):
403        names = self.expand(name).split(':')
404        for n in names:
405            log.trace('opening: %s' % (n))
406            if path.exists(n):
407                try:
408                    mc = open(path.host(n), 'r')
409                    macros = self.parse(mc)
410                    mc.close()
411                    self.files += [n]
412                    return
413                except IOError as err:
414                    pass
415        raise error.general('opening macro file: %s' % \
416                                (path.host(self.expand(name))))
417
418    def get(self, key):
419        if type(key) is not str:
420            raise TypeError('bad key type: %s' % (type(key)))
421        key = self.key_filter(key)
422        for rm in self.get_read_maps():
423            if key in self.macros[rm]:
424                return self.macros[rm][key]
425        if key in self.macros['global']:
426            return self.macros['global'][key]
427        return None
428
429    def get_type(self, key):
430        m = self.get(key)
431        if m is None:
432            return None
433        return m[0]
434
435    def get_attribute(self, key):
436        m = self.get(key)
437        if m is None:
438            return None
439        return m[1]
440
441    def get_value(self, key):
442        m = self.get(key)
443        if m is None:
444            return None
445        return m[2]
446
447    def overridden(self, key):
448        return self.get_attribute(key) == 'override'
449
450    def define(self, key, value = '1'):
451        if type(key) is not str:
452            raise TypeError('bad key type: %s' % (type(key)))
453        self.__setitem__(key, ('none', 'none', value))
454
455    def undefine(self, key):
456        if type(key) is not str:
457            raise TypeError('bad key type: %s' % (type(key)))
458        key = self.key_filter(key)
459        for map in self.macros:
460            if key in self.macros[map]:
461                del self.macros[map][key]
462
463    def expand(self, _str):
464        """Simple basic expander of config file macros."""
465        start_str = _str
466        expanded = True
467        count = 0
468        while expanded:
469            count += 1
470            if count > 1000:
471                raise error.general('expansion looped over 1000 times "%s"' %
472                                    (start_str))
473            expanded = False
474            for m in self.macro_filter.findall(_str):
475                name = m[2:-1]
476                macro = self.get(name)
477                if macro is None:
478                    raise error.general('cannot expand default macro: %s in "%s"' %
479                                        (m, _str))
480                _str = _str.replace(m, macro[2])
481                expanded = True
482        return _str
483
484    def find(self, regex):
485        what = re.compile(regex)
486        keys = []
487        for key in self.keys():
488            if what.match(key):
489                keys += [key]
490        return keys
491
492    def set_read_map(self, _map):
493        if not self.read_map_locked:
494            if _map in self.macros:
495                if _map not in self.get_read_maps():
496                    rm = '%04d_%s' % (len(self.read_maps), _map)
497                    self.read_maps = sorted(self.read_maps + [rm])
498                return True
499        return False
500
501    def unset_read_map(self, _map):
502        if not self.read_map_locked:
503            if _map in self.get_read_maps():
504                for i in range(0, len(self.read_maps)):
505                    if '%04d_%s' % (i, _map) == self.read_maps[i]:
506                        self.read_maps.pop(i)
507                return True
508        return False
509
510    def set_write_map(self, map):
511        if map in self.macros:
512            self.write_map = map
513            return True
514        return False
515
516    def lock_read_map(self):
517        self.read_map_locked = True
518
519    def unlock_read_map(self):
520        self.read_map_locked = False
521
522if __name__ == "__main__":
523    import copy
524    import sys
525    print(inspect.getfile(macros))
526    m = macros()
527    d = copy.copy(m)
528    m['test1'] = 'something'
529    if d.has_key('test1'):
530        print('error: copy failed.')
531        sys.exit(1)
532    m.parse("[test]\n" \
533            "test1: none, undefine, ''\n" \
534            "name:  none, override, 'pink'\n")
535    print('set test:', m.set_read_map('test'))
536    if m['name'] != 'pink':
537        print('error: override failed. name is %s' % (m['name']))
538        sys.exit(1)
539    if m.has_key('test1'):
540        print('error: map undefine failed.')
541        sys.exit(1)
542    print('unset test:', m.unset_read_map('test'))
543    print(m)
544    print(m.keys())
Note: See TracBrowser for help on using the repository browser.