lang-check.py 9.3 KB

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