~ubuntu-langpack/langpack-o-matic/main

« back to all changes in this revision

Viewing changes to lib/macros.py

  • Committer: martin at piware
  • Date: 2006-03-31 16:41:18 UTC
  • Revision ID: martin@piware.de-20060331164118-52f2fc52123bd727
state for breezy final

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
'''macros.py: Generate macro values from configuration values and provide
 
2
substitution functions.
 
3
 
 
4
The following macros are available:
 
5
 
 
6
  LCODE CCODE PCCODE PKGNAME LANG COUNTRY PCOUNTRY RELEASE UPLOADER
 
7
  DATE TIMESTAMP SUPDEPS CLASS CLASSNAME CLASSNAMESPACE
 
8
'''
 
9
 
 
10
import time, re, os.path, os
 
11
 
 
12
def _file_map(file, key, sep = None):
 
13
    '''Look up key in given file ("key value" lines). Throw an exception if
 
14
    key was not found.'''
 
15
 
 
16
    val = None
 
17
    for l in open(file):
 
18
        try:
 
19
            (k, v) = l.split(sep)
 
20
        except ValueError:
 
21
            continue
 
22
        # sort out comments
 
23
        if k.find('#') >= 0 or v.find('#') >= 0:
 
24
            continue
 
25
        if k == key:
 
26
            val = v.strip()
 
27
    if v == None:
 
28
        raise Exception, 'Key %s not found in %s' % (key, file)
 
29
    return val
 
30
 
 
31
class LangpackMacros:
 
32
    def __init__(self, locale, cls, release, version):
 
33
        self.macros = {}
 
34
        # chop .* and @* suffixes to get encoding-agnostic locale
 
35
        self['LOCALE'] = (locale.split('.')[0]).split('@')[0]
 
36
 
 
37
        # class
 
38
        self['CLASS'] = cls
 
39
        if cls:
 
40
            self['CLASSNAME'] = _file_map('maps/classnames', cls)
 
41
            self['CLASSNAMESPACE'] = self['CLASSNAME'] + ' '
 
42
 
 
43
        # language and country
 
44
        try:
 
45
            (self['LCODE'], self['CCODE']) = self['LOCALE'].split('_')
 
46
            self['PCCODE'] = '(%s)' % self['CCODE']
 
47
            self['COUNTRY'] = _file_map('maps/countries', self['CCODE'], ':')
 
48
            self['PCOUNTRY'] = '(%s)' % self['COUNTRY']
 
49
        except ValueError:
 
50
            self['LCODE'] = self['LOCALE']
 
51
 
 
52
        if not self['LCODE']:
 
53
            raise Exception, 'Internal error: LCODE is empty'
 
54
 
 
55
        self['LANG'] = _file_map('maps/languages', self['LCODE'], ':')
 
56
 
 
57
        # package name
 
58
        if self['CLASS']:
 
59
            self['PKGNAME'] = '%s-%s' % (self['CLASS'], self['LCODE'])
 
60
        else:
 
61
            self['PKGNAME'] = self['LCODE']
 
62
 
 
63
        # configuration files
 
64
        self['UPLOADER'] = open('config/UPLOADER').read().strip()
 
65
 
 
66
        # other variables
 
67
        self['DATE'] = time.strftime('%a, %d %b %Y %H:%M:%S +0000')
 
68
        self['RELEASE'] = release
 
69
        self['TIMESTAMP'] = version
 
70
 
 
71
        # support dependencies
 
72
        try:
 
73
            deps = [l.strip() for l in open('support-depends/' + self['PKGNAME'])
 
74
                if len(l) > 0]
 
75
            self['SUPDEPS'] = ', '.join(deps)
 
76
        except IOError:
 
77
            pass
 
78
 
 
79
    def __getitem__(self, item):
 
80
        # return empty string as default
 
81
        return self.macros.get(item, '')
 
82
 
 
83
    def __setitem__(self, item, value):
 
84
        self.macros[item] = value
 
85
 
 
86
    def subst_string(self, s):
 
87
        '''Substitute all macros in given string.'''
 
88
 
 
89
        re_macro = re.compile('%([A-Z]+)%')
 
90
        while 1:
 
91
            m = re_macro.search(s)
 
92
            if m:
 
93
                s = s[:m.start(1)-1] + self[m.group(1)] + s[m.end(1)+1:]
 
94
            else:
 
95
                break
 
96
 
 
97
        return s
 
98
 
 
99
    def subst_file(self, file):
 
100
        '''Substitute all macros in given file.'''
 
101
 
 
102
        s = open(file).read()
 
103
        open(file, 'w').write(self.subst_string(s))
 
104
 
 
105
    def subst_tree(self, root):
 
106
        '''Substitute all macros in given directory tree.'''
 
107
 
 
108
        for path, dirs, files in os.walk(root):
 
109
            for f in files:
 
110
                self.subst_file(os.path.join(root, path, f))
 
111
 
 
112
if __name__ == '__main__':
 
113
    for locale in ['de', 'de_DE', 'de_DE.UTF-8', 'de_DE.UTF-8@euro', 'fr_BE@latin']:
 
114
        for cl in ['', 'gnome', 'kde']:
 
115
            l = LangpackMacros(locale, cl)
 
116
            print '-------', locale, cl, '---------------'
 
117
            template = '"language-pack-%PKGNAME%: %CLASSNAMESPACE%packages for %LANG% %CCODE% %PCOUNTRY%"'
 
118
            print 'string:', l.subst_string(template)
 
119
 
 
120
            open('testtest', 'w').write(template)
 
121
            l.subst_file('testtest')
 
122
            print 'file  :', open('testtest').read()
 
123
            os.unlink('testtest')