ansi-to-src.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. import sys
  3. ##
  4. ## Convert ANSI art files to C++ header file.
  5. ##
  6. filenames = sys.argv
  7. filenames.pop(0)
  8. if not filenames:
  9. print("I need filename(s) to convert.")
  10. sys.exit(0)
  11. def my_repr(line):
  12. """ Given a latin1 line, output valid C++ string.
  13. if the character is < 0x20 or > 0x7e, output in hex format.
  14. if the character is ', " or ?, output \', \", or \?.
  15. """
  16. r = ""
  17. for c in line:
  18. o = ord(c)
  19. if ((o< 0x20) or (o > 0x7e)):
  20. r += "\\x{0:02x}".format(o)
  21. else:
  22. if c == "'":
  23. r += "\\'"
  24. elif c == '"':
  25. r += '\\"'
  26. elif c == '?':
  27. r += '\\?'
  28. elif c == '\\':
  29. r += '\\\\'
  30. else:
  31. r += c
  32. return r
  33. def readfile(filename):
  34. """ Reads the given ANSI file and outputs valid C++ code. """
  35. # basename will be the name of the array defined in the headerfile.
  36. basename = filename
  37. pos = basename.find('.')
  38. if pos != -1:
  39. basename = basename[:pos]
  40. pos = basename.rfind('/')
  41. if pos != -1:
  42. basename = basename[pos+1:]
  43. # Read the file into lines
  44. lines = []
  45. with open(filename, "r", encoding="latin1") as fp:
  46. for line in fp:
  47. line = line.rstrip("\r\n")
  48. lines.append(line)
  49. print("std::array<const char *,{1}> {0} = {{".format(basename, len(lines)))
  50. first = True
  51. for line in lines:
  52. if not first:
  53. print(",")
  54. else:
  55. first = False
  56. print(" \"{0}\"".format(my_repr(line)), end='')
  57. print(" };\n")
  58. # Begin the output process
  59. print("#include <array>\n")
  60. # Process each file given
  61. for filename in filenames:
  62. readfile(filename)