lang.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python3
  2. import os
  3. import glob
  4. import sys
  5. import csv
  6. def get_lang(lang):
  7. out = {}
  8. for ln in open('./src/lang/%s.rs' % lang, encoding='utf8'):
  9. ln = ln.strip()
  10. if ln.startswith('("'):
  11. k, v = line_split(ln)
  12. out[k] = v
  13. return out
  14. def line_split(line):
  15. toks = line.split('", "')
  16. if len(toks) != 2:
  17. print(line)
  18. assert 0
  19. # Replace fixed position.
  20. # Because toks[1] may be v") or v"),
  21. k = toks[0][toks[0].find('"') + 1:]
  22. v = toks[1][:toks[1].rfind('"')]
  23. return k, v
  24. def main():
  25. if len(sys.argv) == 1:
  26. expand()
  27. elif sys.argv[1] == '1':
  28. to_csv()
  29. else:
  30. to_rs(sys.argv[1])
  31. def expand():
  32. for fn in glob.glob('./src/lang/*.rs'):
  33. lang = os.path.basename(fn)[:-3]
  34. if lang in ['en', 'template']: continue
  35. print(lang)
  36. dict = get_lang(lang)
  37. fw = open("./src/lang/%s.rs" % lang, "wt", encoding='utf8')
  38. for line in open('./src/lang/template.rs', encoding='utf8'):
  39. line_strip = line.strip()
  40. if line_strip.startswith('("'):
  41. k, v = line_split(line_strip)
  42. if k in dict:
  43. # embraced with " to avoid empty v
  44. line = line.replace('"%s"' % v, '"%s"' % dict[k])
  45. else:
  46. line = line.replace(v, "")
  47. fw.write(line)
  48. else:
  49. fw.write(line)
  50. fw.close()
  51. def to_csv():
  52. for fn in glob.glob('./src/lang/*.rs'):
  53. lang = os.path.basename(fn)[:-3]
  54. csvfile = open('./src/lang/%s.csv' % lang, "wt", encoding='utf8')
  55. csvwriter = csv.writer(csvfile)
  56. for line in open(fn, encoding='utf8'):
  57. line_strip = line.strip()
  58. if line_strip.startswith('("'):
  59. k, v = line_split(line_strip)
  60. csvwriter.writerow([k, v])
  61. csvfile.close()
  62. def to_rs(lang):
  63. csvfile = open('%s.csv' % lang, "rt", encoding='utf8')
  64. fw = open("./src/lang/%s.rs" % lang, "wt", encoding='utf8')
  65. fw.write('''lazy_static::lazy_static! {
  66. pub static ref T: std::collections::HashMap<&'static str, &'static str> =
  67. [
  68. ''')
  69. for row in csv.reader(csvfile):
  70. fw.write(' ("%s", "%s"),\n' % (row[0].replace('"', '\"'), row[1].replace('"', '\"')))
  71. fw.write(''' ].iter().cloned().collect();
  72. }
  73. ''')
  74. fw.close()
  75. main()