summaryrefslogtreecommitdiff
path: root/numpy/_build_utils/process_src_template.py
blob: 4a0915e25254bbb29850ecf460f8f774d63ff371 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
import sys
import os
import argparse
import importlib.util


def get_processor():
    # Convoluted because we can't import from numpy.distutils
    # (numpy is not yet built)
    conv_template_path = os.path.join(
        os.path.dirname(__file__),
        '..', 'distutils', 'conv_template.py'
    )
    spec = importlib.util.spec_from_file_location(
        'conv_template', conv_template_path
    )
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod.process_file


def process_and_write_file(fromfile, outfile):
    """Process tempita templated file and write out the result.

    The template file is expected to end in `.src`
    (e.g., `.c.src` or `.h.src`).
    Processing `npy_somefile.c.src` generates `npy_somefile.c`.

    """
    process_file = get_processor()
    content = process_file(fromfile)
    with open(outfile, 'w') as f:
        f.write(content)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "infile",
        type=str,
        help="Path to the input file"
    )
    parser.add_argument(
        "-o",
        "--outfile",
        type=str,
        help="Path to the output file"
    )
    parser.add_argument(
        "-i",
        "--ignore",
        type=str,
        help="An ignored input - may be useful to add a "
        "dependency between custom targets",
    )
    args = parser.parse_args()

    if not args.infile.endswith('.src'):
        raise ValueError(f"Unexpected extension: {args.infile}")

    outfile_abs = os.path.join(os.getcwd(), args.outfile)
    process_and_write_file(args.infile, outfile_abs)


if __name__ == "__main__":
    main()