ansi-to-go.py 2.0 KB

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