File: rename_types.py

package info (click to toggle)
libsdl3 3.2.10%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 42,240 kB
  • sloc: ansic: 389,254; objc: 12,241; xml: 9,084; cpp: 5,728; perl: 4,547; python: 3,370; sh: 947; makefile: 265; cs: 56
file content (80 lines) | stat: -rwxr-xr-x 2,171 bytes parent folder | download | duplicates (4)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python3
#
# This script renames symbols in the specified paths

import argparse
import os
import pathlib
import re
import sys


def main():
    if len(args.args) < 1:
        print("Usage: %s files_or_directories ..." % sys.argv[0])
        exit(1)

    replacements = {
        "SDL_bool": "bool",
        "SDL_TRUE": "true",
        "SDL_FALSE": "false",
    }
    entries = args.args[0:]

    regex = create_regex_from_replacements(replacements)

    for entry in entries:
        path = pathlib.Path(entry)
        if not path.exists():
            print("%s doesn't exist, skipping" % entry)
            continue

        replace_symbols_in_path(path, regex, replacements)

def create_regex_from_replacements(replacements):
    return re.compile(r"\b(%s)\b" % "|".join(map(re.escape, replacements.keys())))

def replace_symbols_in_file(file, regex, replacements):
    try:
        with file.open("r", encoding="UTF-8", newline="") as rfp:
            original = rfp.read()
            contents = regex.sub(lambda mo: replacements[mo.string[mo.start():mo.end()]], original)
            if contents != original:
                with file.open("w", encoding="UTF-8", newline="") as wfp:
                    wfp.write(contents)
    except UnicodeDecodeError:
        print("%s is not text, skipping" % file)
    except Exception as err:
        print("%s" % err)


def replace_symbols_in_dir(path, regex, replacements):
    for entry in path.glob("*"):
        if entry.is_dir():
            replace_symbols_in_dir(entry, regex, replacements)
        else:
            print("Processing %s" % entry)
            replace_symbols_in_file(entry, regex, replacements)


def replace_symbols_in_path(path, regex, replacements):
        if path.is_dir():
            replace_symbols_in_dir(path, regex, replacements)
        else:
            replace_symbols_in_file(path, regex, replacements)


if __name__ == "__main__":

    parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
    parser.add_argument("args", nargs="*")
    args = parser.parse_args()

    try:
        main()
    except Exception as e:
        print(e)
        exit(-1)

    exit(0)