File: meson-render-jinja2.py

package info (click to toggle)
systemd 259-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 105,132 kB
  • sloc: ansic: 726,480; xml: 121,118; python: 36,740; sh: 35,016; cpp: 946; makefile: 273; awk: 102; lisp: 13; sed: 1
file content (45 lines) | stat: -rwxr-xr-x 1,321 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later
# pylint: disable=consider-using-with

import ast
import os
import re
import sys

import jinja2

def parse_config_h(filename):
    # Parse config.h file generated by meson.
    ans = {}
    for line in open(filename):
        m = re.match(r'#define\s+(\w+)\s+(.*)', line)
        if not m:
            continue
        a, b = m.groups()
        # The function ast.literal_eval() cannot evaluate octal integers, e.g. 0600.
        # So, it is intentional that the string below does not contain '0'.
        if b and (b[0] in '123456789"' or b == '0'):
            b = ast.literal_eval(b)
        ans[a] = b
    return ans

def render(filename, defines):
    text = open(filename).read()
    template = jinja2.Template(text,
                               trim_blocks=True,
                               lstrip_blocks=True,
                               keep_trailing_newline=True,
                               undefined=jinja2.StrictUndefined)
    return template.render(defines)

def main():
    defines = parse_config_h(sys.argv[1])
    output = render(sys.argv[2], defines)
    with open(sys.argv[3], 'w') as f:
        f.write(output)
    info = os.stat(sys.argv[2])
    os.chmod(sys.argv[3], info.st_mode)

if __name__ == '__main__':
    main()