-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
textify.py
executable file
·78 lines (70 loc) · 2.73 KB
/
textify.py
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
#!/usr/bin/env python3
import re
import argparse
def textify(indent, name, string):
length = len(string) + 1 # Account for null terminator
result = []
i = 0
p = 0
while i < len(string):
char = string[i]
if char == "\\" and i + 1 < len(string) and string[i + 1] == "n":
result.append(f"{indent}{name}[{i-p}] = '\\n';")
elif char == "n" and i - 1 >= 0 and string[i - 1] == "\\":
p += 1
else:
result.append(f"{indent}{name}[{i-p}] = '{char}';")
i += 1
result.append(f"{indent}{name}[{i-p}] = '\\0';\n") # Append null terminator
return "\n".join(result)
def main(input_file, output_file):
with open(input_file, "r") as file:
lines = file.readlines()
new_lines = []
new_lines.append("/* Hi! This file contains autogenerated code.\n")
new_lines.append(" * You probably don't want to edit it directly!\n")
new_lines.append(
" * Instead, edit the original and run textify.py <filename> to regenerate this file.\n"
)
new_lines.append(" * Anyway, thanks for playing 😌")
new_lines.append(" */\n")
i = 0
while i < len(lines):
line = lines[i]
if "//@textify" in line:
next_line = lines[i + 1]
match = re.search(r'(\s*)char (\w+)\[\] = "(.*)";', next_line)
if match:
indent, name, string = match.groups()
print(f"Found match!\n\t {name} = '{string}'")
escaped_string_count = string.count("\\")
new_lines.append(f"{indent}// Begin auto-generated code ({name})\n")
new_lines.append(f"{indent}// {name} = {string}\n")
new_lines.append(
f"{indent}char {name}[{len(string)+1 - escaped_string_count}]"
+ " = {0};\n"
) # Account for null terminator
new_lines.append(textify(indent, name, string))
new_lines.append(f"{indent}// End auto-generated code ({name})\n\n")
i += 2
continue
new_lines.append(line)
i += 1
with open(output_file, "w") as file:
file.writelines(new_lines)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This script transforms a C source file, replacing char[] definitions with explicit char assignments.",
epilog="also uraqt3.14",
)
parser.add_argument(
"-i", "--input", default="hook.c", help="Input C source file (default: hook.c)"
)
parser.add_argument(
"-o",
"--output",
default="out-hook.c",
help="Output C source file (default: out-hook.c)",
)
args = parser.parse_args()
main(args.input, args.output)