source: rtems-tools/rtemstoolkit/macros.py @ 6c94148

4.105
Last change on this file since 6c94148 was 2de37f3, checked in by Chris Johns <chrisj@…>, on 03/09/16 at 03:27:42

Python 2 and python 3 refactor fixes.

Updates #2619.

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