aboutsummaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
Diffstat (limited to 'bin')
-rwxr-xr-xbin/txt2c.py62
1 files changed, 62 insertions, 0 deletions
diff --git a/bin/txt2c.py b/bin/txt2c.py
new file mode 100755
index 0000000..1d8ff70
--- /dev/null
+++ b/bin/txt2c.py
@@ -0,0 +1,62 @@
1#!/usr/bin/python3
2
3import fileinput
4import os
5import sys
6
7
8def escape_quotes(string):
9 return string.replace("\"", '\\"')
10
11
12def escape_newlines(string):
13 return string.replace("\n", "\\n")
14
15
16def quote(string):
17 return "\"" + string + "\""
18
19
20def main():
21 if len(sys.argv) < 3:
22 print("Usage: {} [text files...] [C files...]".format(sys.argv[0]))
23 return 1
24
25 files = sys.argv[1:]
26 assert(len(files) % 2 == 0)
27 N = int(len(files) / 2)
28 text_files = files[:N]
29 c_files = files[N:]
30
31 for i in range(len(text_files)):
32 text_file = text_files[i]
33 c_file = c_files[i]
34 h_file = c_file.replace(".c", ".h")
35 variable_name = os.path.basename(text_file).replace(".", "_")
36
37 os.makedirs(os.path.join(".", os.path.dirname(c_file)), exist_ok=True)
38
39 # Create the C file.
40 with open(c_file, 'w') as out_file:
41 out_file.write("const char {}[] =\n".format(variable_name))
42 pad = " "
43 with open(text_file, 'r') as in_file:
44 for line in in_file.readlines():
45 line = escape_quotes(line)
46 line = escape_newlines(line)
47 line = quote(line)
48 line = pad + line + "\n"
49 out_file.write(line)
50 out_file.write(pad + "\"\";")
51
52 # Create the header file.
53 with open(h_file, 'w') as out_file:
54 out_file.write("#pragma once\n")
55 out_file.write("\n")
56 out_file.write("extern const char {}[];".format(variable_name))
57
58 return 0
59
60
61if __name__ == '__main__':
62 sys.exit(main())