ansi-to-go.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import (
  3. "bufio"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "os"
  8. "strings"
  9. )
  10. func hexout(text string) {
  11. for _, b := range []byte(text) {
  12. fmt.Printf("%02x ", b)
  13. }
  14. fmt.Println("")
  15. }
  16. func repr_line(line string) string {
  17. output := ""
  18. for _, ch := range []byte(line) {
  19. switch {
  20. case ch == '\'':
  21. output += "\\'"
  22. case ch == '"':
  23. output += "\\\""
  24. case ch == '\\':
  25. output += "\\\\"
  26. case ch < byte(0x20) || ch > byte(0x7e):
  27. output += fmt.Sprintf("\\x%02x", ch)
  28. default:
  29. output += string(ch)
  30. }
  31. }
  32. return output
  33. }
  34. func readfile(filename string) {
  35. var basename string
  36. var lines []string
  37. idx := strings.LastIndex(filename, "/")
  38. basename = filename[idx+1:]
  39. idx = strings.Index(basename, ".")
  40. basename = basename[:idx]
  41. file, err := os.Open(filename)
  42. if err != nil {
  43. log.Panicf("Open(%s): %s\n", filename, err)
  44. }
  45. defer file.Close()
  46. // Read the lines
  47. scanner := bufio.NewScanner(file)
  48. for scanner.Scan() {
  49. line := scanner.Text()
  50. lines = append(lines, line)
  51. }
  52. // Ok, is what we have usable, or did it mangle up our Latin1 text?
  53. // hexout(lines[0])
  54. // fmt.Printf("func ANSI%s() [%d]string {\n", strings.Title(basename), len(lines))
  55. fmt.Printf("func ANSI%s() []string {\n", strings.Title(basename))
  56. // insert CP437_to_Unicode in here, if needed.
  57. // fmt.Printf(" data := [%d]string {\n", len(lines))
  58. fmt.Print(" data := []string {\n")
  59. for _, line := range lines {
  60. fmt.Printf(" \"%s\",\n", repr_line(line))
  61. }
  62. fmt.Println(" }")
  63. fmt.Println(" if !door.Unicode && !door.CP437 {")
  64. fmt.Println(" log.Panicf(\"Call after door.Init() so Unicode/CP437 has been set.\")")
  65. fmt.Println(" }")
  66. fmt.Println(" if door.Unicode {")
  67. fmt.Println(" for idx := range data {")
  68. fmt.Println(" data[idx] = door.CP437_to_Unicode(data[idx])")
  69. fmt.Println(" }")
  70. fmt.Println(" }")
  71. fmt.Println(" return data")
  72. fmt.Printf("}\n\n")
  73. }
  74. func main() {
  75. var defaultPackage string = "main"
  76. flag.StringVar(&defaultPackage, "p", "main", "Package name to use")
  77. flag.Parse()
  78. if flag.NArg() == 0 {
  79. fmt.Println("ANSI (CP437) to go converter.")
  80. fmt.Println("No ANSI filenames given.")
  81. flag.PrintDefaults()
  82. os.Exit(2)
  83. }
  84. fmt.Printf("package %s\n\n", defaultPackage)
  85. fmt.Printf("import (\n \"red-green/door\"\n \"log\"\n )\n\n")
  86. for _, filename := range flag.Args() {
  87. readfile(filename)
  88. }
  89. }