Clone of Bael'Zharon's Respite @ https://github.com/boardwalk/bzr

make_include_file.py 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python
  2. import argparse
  3. import os
  4. import re
  5. def process_file(path):
  6. with open(path) as inf:
  7. content = inf.read()
  8. # remove c-style comments
  9. content = re.sub('/\*.+\*/', '', content, 0, re.DOTALL)
  10. # remove cpp-style comments
  11. content = re.sub('//.+', '', content)
  12. # replace includes
  13. def include_file(m):
  14. return process_file(os.path.join('source', m.group(1)))
  15. content = re.sub('^#include "([^"]+)"$', include_file, content, 0, re.MULTILINE)
  16. # replace newlines with spaces
  17. def replace_newline(m):
  18. return m.group(1) + ('\n' if m.group(1).startswith('#') else ' ')
  19. content = re.sub('(.*)\n', replace_newline, content)
  20. # compress extra spaces
  21. content = re.sub(' +', ' ', content)
  22. # remove leading and trailing spaces
  23. content = content.strip()
  24. return content
  25. def escape_c_string(s):
  26. s = s.replace("\n", "\\n")
  27. s = s.replace("\"", "\\\"")
  28. return s
  29. parser = argparse.ArgumentParser()
  30. parser.add_argument('infile')
  31. parser.add_argument('outfile')
  32. args = parser.parse_args()
  33. root, ext = os.path.splitext(args.infile)
  34. with open(args.outfile, 'w') as outf:
  35. varname = os.path.basename(root)
  36. content = escape_c_string(process_file(args.infile))
  37. outf.write('static const char {}[] = "{}";\n'.format(varname, content))