file2h.py 1.1 KB

123456789101112131415161718192021222324252627282930
  1. # Reads in a text file, and performs the necessary escapes so that it
  2. # can be #included as a static string like:
  3. # static const char string_from_textfile[] =
  4. # #include "build/textfile.h"
  5. # ;
  6. # This script simply prints the escaped string straight to stdout
  7. from __future__ import print_function
  8. import sys
  9. # Can either be set explicitly, or left blank to auto-detect
  10. # Except auto-detect doesn't work because the file has been passed
  11. # through Python text processing, which makes all EOL a \n
  12. line_end = '\\r\\n'
  13. if __name__ == "__main__":
  14. filename = sys.argv[1]
  15. for line in open(filename, 'r').readlines():
  16. if not line_end:
  17. for ending in ('\r\n', '\r', '\n'):
  18. if line.endswith(ending):
  19. line_end = ending.replace('\r', '\\r').replace('\n', '\\n')
  20. break
  21. if not line_end:
  22. raise Exception("Couldn't auto-detect line-ending of %s" % filename)
  23. line = line.rstrip('\r\n')
  24. line = line.replace('\\', '\\\\')
  25. line = line.replace('"', '\\"')
  26. print('"%s%s"' % (line, line_end))