Project

General

Profile

Download (3.15 KB) Statistics
| Branch: | Tag: | Revision:

calebasse / calebasse / doc_templates.py @ 26c60057

1
import os
2
import os.path
3
import re
4
import contextlib
5

    
6
__ALL__ = [ 'DocTemplateError', 'make_doc_from_template' ]
7

    
8
VARIABLE_RE = re.compile(r'@[A-Z]{2,3}[0-9]{0,2}')
9

    
10
class DocTemplateError(RuntimeError):
11
    def __str__(self):
12
        return ' '.join(map(str, self.args))
13

    
14

    
15
@contextlib.contextmanager
16
def delete_on_error(f):
17
    '''Context manager which deletes a file if an exception occur'''
18
    try:
19
        yield
20
    except:
21
        os.remove(f.name)
22
        raise
23

    
24

    
25
def replace_variables(template, variables):
26
    '''Lookup all substring looking like @XXX9 in the string template, and
27
       replace them by the value of the key XXX9 in the dictionary variables.
28

    
29
       Returns a new :class:str
30

    
31
       :param template: string containing the variables references
32
       :param variables: dictionary containing the variables values
33

    
34
    '''
35
    needed_vars = set([v[1:] for v in re.findall(VARIABLE_RE, template)])
36
    given_vars = set(variables.keys())
37
    if given_vars != needed_vars:
38
        missing = needed_vars - given_vars
39
        unused = given_vars - needed_vars
40
        raise DocTemplateError(
41
            'Mismatch between given and needed variables: missing={0} unused={1}'
42
            .format(map(repr, missing), map(repr, unused)))
43
    def variable_replacement(match_obj):
44
        return variables[match_obj.group(0)[1:]]
45
    return re.sub(VARIABLE_RE, variable_replacement, template)
46

    
47

    
48
def char_to_rtf(c):
49
    if ord(c) < 128:
50
        return c
51
    else:
52
        return '\u%d?' % ord(c)
53

    
54

    
55
def utf8_to_rtf(s):
56
    s = ''.join([ char_to_rtf(c) for c in s])
57
    return '{\uc1{%s}}' % s
58

    
59

    
60
def unicode_to_rtf(value):
61
    try:
62
        value = unicode(value)
63
    except Exception, e:
64
        raise DocTemplateError('Unable to get a unicode value', e)
65
    return utf8_to_rtf(value)
66

    
67

    
68
def variables_to_rtf(variables):
69
    return dict(((k, unicode_to_rtf(v)) for k,v in variables.iteritems()))
70

    
71

    
72
def make_doc_from_template(from_path, to_path, variables):
73
    '''Use file from_path as a template to combine with the variables
74
       dictionary and place the result in the file to_path.
75
       Encode value of variable into encoding of UTF-8 for the RTF file format.
76

    
77
       :param from_path: the template file path
78
       :param to_path: the newly created file containing the result of the templating
79
       :param variables: the dictionary of variables to replace
80
    '''
81

    
82
    if not os.path.exists(from_path):
83
        raise DocTemplateError('Template file does not exist', repr(from_path))
84
    if os.path.exists(to_path):
85
        raise DocTemplateError('Destination file already exists', repr(to_path))
86
    variables = variables_to_rtf(variables)
87
    with open(to_path, 'w') as to_file:
88
        with open(from_path) as from_file:
89
            with delete_on_error(to_file):
90
                to_file.write(replace_variables(from_file.read(), variables))
91

    
92
if __name__ == '__main__':
93
    import sys
94
    try:
95
        variables = dict((map(lambda x: unicode(x, 'utf-8'), arg.split('=')) for arg in sys.argv[3:]))
96
        make_doc_from_template(sys.argv[1], sys.argv[2], variables)
97
    except Exception, e:
98
        raise
99
        print 'Usage: python doc_template.py <template.rtf> <output.rtf> [KEY1=value1 KEY2=value2 ...]'
(4-4/12)