aboutsummaryrefslogtreecommitdiffstats
path: root/tools/qtpy2cpp.py
blob: 6ab74d3574dcfb952773c72088fe2bdbf774e5d1 (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
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

import logging
import os
import sys
from argparse import ArgumentParser, RawTextHelpFormatter

from qtpy2cpp_lib.visitor import ConvertVisitor

DESCRIPTION = "Tool to convert Python to C++"


def create_arg_parser(desc):
    parser = ArgumentParser(description=desc,
                            formatter_class=RawTextHelpFormatter)
    parser.add_argument('--debug', '-d', action='store_true',
                        help='Debug')
    parser.add_argument('--stdout', '-s', action='store_true',
                        help='Write to stdout')
    parser.add_argument('--force', '-f', action='store_true',
                        help='Force overwrite of existing files')
    parser.add_argument('files', type=str, nargs="+", help='Python source file(s)')
    return parser


if __name__ == '__main__':
    if sys.version_info < (3, 6, 0):
        raise Exception("This script requires Python 3.6")
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    arg_parser = create_arg_parser(DESCRIPTION)
    args = arg_parser.parse_args()
    ConvertVisitor.debug = args.debug

    for input_file in args.files:
        if not os.path.isfile(input_file):
            logger.error(f'{input_file} does not exist or is not a file.')
            sys.exit(-1)
        file_root, ext = os.path.splitext(input_file)
        if ext != '.py':
            logger.error(f'{input_file} does not appear to be a Python file.')
            sys.exit(-1)

        ast_tree = ConvertVisitor.create_ast(input_file)
        if args.stdout:
            base_name = os.path.basename(input_file)
            sys.stdout.write(f'// Converted from {base_name}\n')
            ConvertVisitor(input_file, sys.stdout).visit(ast_tree)
            sys.exit(0)

        target_file = file_root + '.cpp'
        if os.path.exists(target_file):
            if not os.path.isfile(target_file):
                logger.error(f'{target_file} exists and is not a file.')
                sys.exit(-1)
            if not args.force:
                logger.error(f'{target_file} exists. Use -f to overwrite.')
                sys.exit(-1)

        with open(target_file, "w") as file:
            base_name = os.path.basename(input_file)
            file.write(f'// Converted from {base_name}\n')
            ConvertVisitor(input_file, file).visit(ast_tree)
            logger.info(f"Wrote {target_file} ...")