xref: /aosp_15_r20/build/soong/scripts/text_file_processor.py (revision 333d2b3687b3a337dbcca9d65000bca186795e39)
1#!/usr/bin/env python
2#
3# Copyright (C) 2024 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the 'License');
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an 'AS IS' BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import argparse
18import re
19
20def main():
21    parser = argparse.ArgumentParser(description='This script looks for '
22        '`{CONTENTS_OF:path/to/file}` markers in the input file and replaces them with the actual '
23        'contents of that file, with leading/trailing whitespace stripped. The idea is that this '
24        'script could be extended to support more types of markers in the future.')
25    parser.add_argument('input')
26    parser.add_argument('output')
27    args = parser.parse_args()
28
29    with open(args.input, 'r') as f:
30        contents = f.read()
31
32    i = 0
33    replacedContents = ''
34    for m in re.finditer(r'{CONTENTS_OF:([a-zA-Z0-9 _/.-]+)}', contents):
35        replacedContents += contents[i:m.start()]
36        with open(m.group(1), 'r') as f:
37            replacedContents += f.read().strip()
38        i = m.end()
39    replacedContents += contents[i:]
40
41    with open(args.output, 'w') as f:
42        f.write(replacedContents)
43
44
45if __name__ == '__main__':
46    main()
47