aboutsummaryrefslogtreecommitdiff
path: root/bin/txt2c.py
blob: 1d8ff70d8b97a8b7fa8852a49b7b470698ada364 (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
#!/usr/bin/python3

import fileinput
import os
import sys


def escape_quotes(string):
  return string.replace("\"", '\\"')


def escape_newlines(string):
  return string.replace("\n", "\\n")


def quote(string):
  return "\"" + string + "\""


def main():
  if len(sys.argv) < 3:
    print("Usage: {} [text files...] [C files...]".format(sys.argv[0]))
    return 1

  files = sys.argv[1:]
  assert(len(files) % 2 == 0)
  N = int(len(files) / 2)
  text_files = files[:N]
  c_files = files[N:]

  for i in range(len(text_files)):
    text_file = text_files[i]
    c_file = c_files[i]
    h_file = c_file.replace(".c", ".h")
    variable_name = os.path.basename(text_file).replace(".", "_")

    os.makedirs(os.path.join(".", os.path.dirname(c_file)), exist_ok=True)

    # Create the C file.
    with open(c_file, 'w') as out_file:
      out_file.write("const char {}[] =\n".format(variable_name))
      pad = "  "
      with open(text_file, 'r') as in_file:
        for line in in_file.readlines():
          line = escape_quotes(line)
          line = escape_newlines(line)
          line = quote(line)
          line = pad + line + "\n"
          out_file.write(line)
        out_file.write(pad + "\"\";")

    # Create the header file.
    with open(h_file, 'w') as out_file:
      out_file.write("#pragma once\n")
      out_file.write("\n")
      out_file.write("extern const char {}[];".format(variable_name))

  return 0


if __name__ == '__main__':
  sys.exit(main())