lang-check.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #!/usr/bin/env python3
  2. #
  3. # Version 1.0.1
  4. #
  5. #############################################################################
  6. # Change log:
  7. # 7 May 2019, Ondrej Tuma, Initial
  8. # 9 June 2020, 3d-gussner, Added version and Change log
  9. # 9 June 2020, 3d-gussner, Wrap text to 20 char and rows
  10. # 9 June 2020, 3d-gussner, colored output
  11. # 2 Apr. 2021, 3d-gussner, Fix and improve text warp
  12. # 22 Apr. 2021, DRracer , add English source to output
  13. # 23 Apr. 2021, wavexx , improve
  14. # 24 Apr. 2021, wavexx , improve
  15. # 26 Apr. 2021, 3d-gussner, add character ruler
  16. #############################################################################
  17. #
  18. """Check lang files."""
  19. from argparse import ArgumentParser
  20. from traceback import print_exc
  21. from sys import stdout, stderr
  22. import textwrap
  23. import re
  24. def color_maybe(color_attr, text):
  25. if stdout.isatty():
  26. return '\033[0;' + str(color_attr) + 'm' + text + '\033[0m'
  27. else:
  28. return text
  29. red = lambda text: color_maybe(31, text)
  30. green = lambda text: color_maybe(32, text)
  31. yellow = lambda text: color_maybe(33, text)
  32. def print_wrapped(wrapped_text, rows, cols):
  33. if type(wrapped_text) == str:
  34. wrapped_text = [wrapped_text]
  35. for r, line in enumerate(wrapped_text):
  36. r_ = str(r + 1).rjust(3)
  37. if r >= rows:
  38. r_ = color_maybe(31, r_)
  39. print((' {} |{:' + str(cols) + 's}|').format(r_, line))
  40. def print_truncated(text, cols):
  41. if len(text) <= cols:
  42. prefix = text.ljust(cols)
  43. suffix = ''
  44. else:
  45. prefix = text[0:cols]
  46. suffix = color_maybe(31, text[cols:])
  47. print(' |' + prefix + '|' + suffix)
  48. def print_ruler(spc, cols):
  49. print(' ' * spc + color_maybe(36, ('₀₁₂₃₄₅₆₇₈₉'*4)[:cols]))
  50. def print_source_translation(source, translation, wrapped_source, wrapped_translation, rows, cols):
  51. if rows == 1:
  52. print(' source text:')
  53. print_ruler(4, cols);
  54. print_truncated(source, cols)
  55. print(' translated text:')
  56. print_ruler(4, cols);
  57. print_truncated(translation, cols)
  58. else:
  59. print(' source text:')
  60. print_ruler(6, cols);
  61. print_wrapped(wrapped_source, rows, cols)
  62. print(' translated text:')
  63. print_ruler(6, cols);
  64. print_wrapped(wrapped_translation, rows, cols)
  65. print()
  66. def highlight_trailing_white(text):
  67. if type(text) == str:
  68. return re.sub(r' $', '·', text)
  69. else:
  70. ret = text[:]
  71. ret[-1] = highlight_trailing_white(ret[-1])
  72. return ret
  73. def wrap_text(text, cols):
  74. # wrap text
  75. ret = list(textwrap.TextWrapper(width=cols).wrap(text))
  76. if len(ret):
  77. # add back trailing whitespace
  78. ret[-1] += ' ' * (len(text) - len(text.rstrip()))
  79. return ret
  80. def unescape(text):
  81. if '\\' not in text:
  82. return text
  83. return text.encode('ascii').decode('unicode_escape')
  84. def ign_char_first(c):
  85. return c.isalnum() or c in {'%', '?'}
  86. def ign_char_last(c):
  87. return c.isalnum() or c in {'.', "'"}
  88. def parse_txt(lang, no_warning):
  89. """Parse txt file and check strings to display definition."""
  90. if lang == "en":
  91. file_path = "lang_en.txt"
  92. else:
  93. file_path = "lang_en_%s.txt" % lang
  94. print(green("Start %s lang-check" % lang))
  95. lines = 1
  96. with open(file_path) as src:
  97. while True:
  98. comment = src.readline().split(' ')
  99. #print (comment) #Debug
  100. #Check if columns and rows are defined
  101. cols = None
  102. rows = None
  103. for item in comment[1:]:
  104. key, val = item.split('=')
  105. if key == 'c':
  106. cols = int(val)
  107. #print ("c=",cols) #Debug
  108. elif key == 'r':
  109. rows = int(val)
  110. #print ("r=",rows) #Debug
  111. else:
  112. raise RuntimeError(
  113. "Unknown display definition %s on line %d" %
  114. (' '.join(comment), lines))
  115. if cols is None and rows is None:
  116. if not no_warning:
  117. print(yellow("[W]: No display definition on line %d" % lines))
  118. cols = len(translation) # propably fullscreen
  119. if rows is None:
  120. rows = 1
  121. elif rows > 1 and cols != 20:
  122. print(yellow("[W]: Multiple rows with odd number of columns on line %d" % lines))
  123. #Wrap text to 20 chars and rows
  124. source = src.readline()[:-1].strip('"')
  125. #print (source) #Debug
  126. translation = src.readline()[:-1].strip('"')
  127. if translation == '\\x00':
  128. # crude hack to handle intentionally-empty translations
  129. translation = ''
  130. # handle backslash sequences
  131. source = unescape(source)
  132. translation = unescape(translation)
  133. #print (translation) #Debug
  134. wrapped_source = wrap_text(source, cols)
  135. rows_count_source = len(wrapped_source)
  136. wrapped_translation = wrap_text(translation, cols)
  137. rows_count_translation = len(wrapped_translation)
  138. #End wrap text
  139. # Check for potential errors in the definition
  140. if not no_warning:
  141. if rows == 1 and (len(source) > cols or rows_count_source > rows):
  142. print(yellow('[W]: Source text longer than %d cols as defined on line %d:' % (cols, lines)))
  143. print_truncated(source, cols)
  144. print()
  145. elif rows_count_source > rows:
  146. print(yellow('[W]: Wrapped source text longer than %d rows as defined on line %d:' % (rows, lines)))
  147. print_wrapped(wrapped_source, rows, cols)
  148. print()
  149. # Check for translation lenght
  150. if (rows_count_translation > rows) or (rows == 1 and len(translation) > cols):
  151. print(red('[E]: Text is longer than definition on line %d: cols=%d rows=%d (rows diff=%d)'
  152. % (lines, cols, rows, rows_count_translation-rows)))
  153. print_source_translation(source, translation,
  154. wrapped_source, wrapped_translation,
  155. rows, cols)
  156. # Different count of % sequences
  157. if source.count('%') != translation.count('%') and len(translation) > 0:
  158. print(red('[E]: Unequal count of %% escapes on line %d:' % (lines)))
  159. print_source_translation(source, translation,
  160. wrapped_source, wrapped_translation,
  161. rows, cols)
  162. # Different first/last character
  163. if not no_warning and len(source) > 0 and len(translation) > 0:
  164. source_end = source.rstrip()[-1]
  165. translation_end = translation.rstrip()[-1]
  166. start_diff = not (ign_char_first(source[0]) and ign_char_first(translation[0])) and source[0] != translation[0]
  167. end_diff = not (ign_char_last(source_end) and ign_char_last(translation_end)) and source_end != translation_end
  168. if start_diff or end_diff:
  169. if start_diff:
  170. print(yellow('[W]: Differing first punctuation character (%s => %s) on line %d:' % (source[0], translation[0], lines)))
  171. if end_diff:
  172. print(yellow('[W]: Differing last punctuation character (%s => %s) on line %d:' % (source[-1], translation[-1], lines)))
  173. print_source_translation(source, translation,
  174. wrapped_source, wrapped_translation,
  175. rows, cols)
  176. # Short translation
  177. if not no_warning and len(source) > 0 and len(translation) > 0:
  178. if len(translation.rstrip()) < len(source.rstrip()) / 2:
  179. print(yellow('[W]: Short translation on line %d:' % (lines)))
  180. print_source_translation(source, translation,
  181. wrapped_source, wrapped_translation,
  182. rows, cols)
  183. # Incorrect trailing whitespace in translation
  184. if not no_warning and len(translation) > 0 and \
  185. (source.rstrip() == source or (rows == 1 and len(source) == cols)) and \
  186. translation.rstrip() != translation and \
  187. (rows > 1 or len(translation) != len(source)):
  188. print(yellow('[W]: Incorrect trailing whitespace for translation on line %d:' % (lines)))
  189. source = highlight_trailing_white(source)
  190. translation = highlight_trailing_white(translation)
  191. wrapped_translation = highlight_trailing_white(wrapped_translation)
  192. print_source_translation(source, translation,
  193. wrapped_source, wrapped_translation,
  194. rows, cols)
  195. if len(src.readline()) != 1: # empty line
  196. break
  197. lines += 4
  198. print(green("End %s lang-check" % lang))
  199. def main():
  200. """Main function."""
  201. parser = ArgumentParser(
  202. description=__doc__,
  203. usage="%(prog)s lang")
  204. parser.add_argument(
  205. "lang", nargs='?', default="en", type=str,
  206. help="Check lang file (en|cs|de|es|fr|nl|it|pl)")
  207. parser.add_argument(
  208. "--no-warning", action="store_true",
  209. help="Disable warnings")
  210. args = parser.parse_args()
  211. try:
  212. parse_txt(args.lang, args.no_warning)
  213. return 0
  214. except Exception as exc:
  215. print_exc()
  216. parser.error("%s" % exc)
  217. return 1
  218. if __name__ == "__main__":
  219. exit(main())