• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright (c) 2021-2022 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import re
17import sys
18import os
19import argparse
20
21
22def main():
23    parser = argparse.ArgumentParser(
24        description="Imitates functionality of cmake's configure_file")
25    parser.add_argument("input", help="file to configure")
26    parser.add_argument("output", help="name of the configured file")
27    parser.add_argument(
28        "values", help="words to match, format: KEY=VALUE or KEY=", nargs='*')
29
30    args = parser.parse_args()
31
32    # supports both @...@ and ${...} notations
33    pattern = r'@([^@]*)@|\$\{([^}]*)\}'
34
35    # parsed variables
36    values = {}
37    for value in args.values:
38        key, val = value.split('=', 1)
39        if key in values:
40            return 1
41        values[key] = val.replace('\\n', '\n')
42
43    with open(args.input) as file:
44        in_lines = file.readlines()
45    out_lines = []
46    for in_line in in_lines:
47        def replace(pattern):
48            key = pattern.group(1) or pattern.group(2)
49            if key in values:
50                return values[key]
51            else:
52                return ""
53
54        in_line = re.sub(pattern, replace, in_line)
55
56        # structure: #cmakedefine var val
57        if in_line.startswith("#cmakedefine "):
58            var_val = in_line.split(' ', 1)[1]
59            var_val_split = var_val.split(' ', 1)
60            if len(var_val_split) == 1:
61                # only var given
62                var = var_val.rstrip()
63                in_line = '#define %s\n' % var
64            else:
65                var = var_val_split[0]
66                val = var_val_split[1]
67                in_line = '#define %s %s\n' % (var, val)
68
69            if var not in values:
70                in_line = '/* #undef %s */\n' % var
71
72        out_lines.append(in_line)
73
74    output = ''.join(out_lines)
75
76    def read(filename):
77        with open(filename) as file:
78            return file.read()
79
80    if not os.path.exists(args.output) or read(args.output) != output:
81        with open(args.output, 'w') as file:
82            file.write(output)
83        os.chmod(args.output, os.stat(args.input).st_mode & 0o777)
84
85
86if __name__ == '__main__':
87    sys.exit(main())
88