ansi-to-go.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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("{0} := [...]string {{".format(basename.upper()))
  50. # print("std::array<const char *,{1}> {0} = {{".format(basename, len(lines)))
  51. # first = True
  52. for line in lines:
  53. # if not first:
  54. # print(",")
  55. # else:
  56. # first = False
  57. print(" \"{0}\",".format(my_repr(line)))
  58. print(" }\n")
  59. # Begin the output process
  60. # print("#include <array>\n")
  61. # Process each file given
  62. for filename in filenames:
  63. readfile(filename)