lang-check.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. #!/usr/bin/env python3
  2. #
  3. # Version 1.0.2 - Build 43
  4. #############################################################################
  5. # Change log:
  6. # 7 May 2019, ondratu , Initial
  7. # 13 June 2019, 3d-gussner, Fix length false positives
  8. # 14 Sep. 2019, 3d-gussner, Prepare adding new language
  9. # 18 Sep. 2020, 3d-gussner, Fix execution of lang-check.py
  10. # 2 Apr. 2021, 3d-gussner, Fix and improve text warp
  11. # 22 Apr. 2021, DRracer , add English source to output
  12. # 23 Apr. 2021, wavexx , improve
  13. # 24 Apr. 2021, wavexx , improve
  14. # 26 Apr. 2021, wavexx , add character ruler
  15. # 21 Dec. 2021, 3d-gussner, Prepare more community languages
  16. # Swedish
  17. # Danish
  18. # Slovanian
  19. # Hungarian
  20. # Luxembourgian
  21. # Croatian
  22. # 3 Jan. 2022, 3d-gussner, Prepare Lithuanian
  23. # 7 Jan. 2022, 3d-gussner, Check for Syntax errors and exit with error
  24. # , add Build number 'git rev-list --count HEAD lang-check.py'
  25. # 30 Jan. 2022, 3d-gussner, Add arguments. Requested by @AttilaSVK
  26. # --information == output all source and translated messages
  27. # --import-check == used by `lang-import.sh`to verify
  28. # newly import `lang_en_??.txt` files
  29. # 14 Mar. 2022, 3d-gussner, Check if translation isn't equal to origin
  30. #############################################################################
  31. """Check PO files for formatting errors."""
  32. from argparse import ArgumentParser
  33. from sys import stdout, stderr, exit
  34. import codecs
  35. import polib
  36. import textwrap
  37. import re
  38. import os
  39. from lib import charset as cs
  40. from lib.io import load_map
  41. COLORIZE = (stdout.isatty() and os.getenv("TERM", "dumb") != "dumb") or os.getenv('NO_COLOR') == "0"
  42. def color_maybe(color_attr, text):
  43. if COLORIZE:
  44. return '\033[0;' + str(color_attr) + 'm' + text + '\033[0m'
  45. else:
  46. return text
  47. red = lambda text: color_maybe(31, text)
  48. green = lambda text: color_maybe(32, text)
  49. yellow = lambda text: color_maybe(33, text)
  50. cyan = lambda text: color_maybe(36, text)
  51. def print_wrapped(wrapped_text, rows, cols):
  52. if type(wrapped_text) == str:
  53. wrapped_text = [wrapped_text]
  54. for r, line in enumerate(wrapped_text):
  55. r_ = str(r + 1).rjust(3)
  56. if r >= rows:
  57. r_ = red(r_)
  58. print((' {} |{:' + str(cols) + 's}|').format(r_, line))
  59. def print_truncated(text, cols):
  60. if len(text) <= cols:
  61. prefix = text.ljust(cols)
  62. suffix = ''
  63. else:
  64. prefix = text[0:cols]
  65. suffix = red(text[cols:])
  66. print(' |' + prefix + '|' + suffix)
  67. def print_ruler(spc, cols):
  68. print(' ' * spc + cyan(('₀₁₂₃₄₅₆₇₈₉'*4)[:cols]))
  69. def print_source_translation(source, translation, wrapped_source, wrapped_translation, rows, cols):
  70. if rows == 1:
  71. print(' source text:')
  72. print_ruler(4, cols);
  73. print_truncated(source, cols)
  74. print(' translated text:')
  75. print_ruler(4, cols);
  76. print_truncated(translation, cols)
  77. else:
  78. print(' source text:')
  79. print_ruler(6, cols);
  80. print_wrapped(wrapped_source, rows, cols)
  81. print(' translated text:')
  82. print_ruler(6, cols);
  83. print_wrapped(wrapped_translation, rows, cols)
  84. print()
  85. def highlight_trailing_white(text):
  86. if type(text) == str:
  87. return re.sub(r' $', '·', text)
  88. else:
  89. ret = text[:]
  90. ret[-1] = highlight_trailing_white(ret[-1])
  91. return ret
  92. def wrap_text(text, cols):
  93. ret = []
  94. for line in text.split('\n'):
  95. # wrap each input line in text individually
  96. tmp = list(textwrap.TextWrapper(width=cols).wrap(line))
  97. if len(ret):
  98. # add back trailing whitespace
  99. tmp[-1] += ' ' * (len(text) - len(text.rstrip()))
  100. ret.extend(tmp)
  101. return ret
  102. def ign_char_first(c):
  103. return c.isalnum() or c in {'%', '?'}
  104. def ign_char_last(c):
  105. return c.isalnum() or c in {'.', "'"}
  106. def check_translation(entry, msgids, is_pot, no_warning, no_suggest, warn_empty, warn_same, information):
  107. """Check strings to display definition."""
  108. # do not check obsolete/deleted entriees
  109. if entry.obsolete:
  110. return True
  111. # fetch/decode entry for easy access
  112. meta = entry.comment.split('\n', 1)[0]
  113. source = entry.msgid
  114. translation = entry.msgstr
  115. line = entry.linenum
  116. known_msgid = msgids is None or source in msgids
  117. errors = 0
  118. # Check comment syntax (non-empty and include a MSG id)
  119. if known_msgid or warn_empty:
  120. if len(meta) == 0:
  121. print(red("[E]: Translation doesn't contain any comment metadata on line %d" % line))
  122. return False
  123. if not meta.startswith('MSG'):
  124. print(red("[E]: Critical syntax error: comment doesn't start with MSG on line %d" % line))
  125. print(red(" comment: " + meta))
  126. return False
  127. # Check if columns and rows are defined
  128. tokens = meta.split(' ')
  129. cols = None
  130. rows = None
  131. for item in tokens[1:]:
  132. try:
  133. key, val = item.split('=')
  134. if key == 'c':
  135. cols = int(val)
  136. elif key == 'r':
  137. rows = int(val)
  138. else:
  139. raise ValueError
  140. except ValueError:
  141. print(red("[E]: Invalid display definition on line %d" % line))
  142. print(red(" definition: " + meta))
  143. return False
  144. if cols is None and rows is None:
  145. if not no_warning and known_msgid:
  146. errors += 1
  147. print(yellow("[W]: No usable display definition on line %d" % line))
  148. # probably fullscreen, guess from the message length to continue checking
  149. cols = len(source)
  150. if rows is None:
  151. rows = 1
  152. elif rows > 1 and cols != 20:
  153. errors += 1
  154. print(yellow("[W]: Multiple rows with odd number of columns on line %d" % line))
  155. # Check if translation contains unsupported characters
  156. invalid_char = cs.translation_check(cs.unicode_to_source(translation))
  157. if invalid_char is not None:
  158. print(red('[E]: Critical syntax: Unhandled char %s found on line %d' % (repr(invalid_char), line)))
  159. print(red(' translation: ' + translation))
  160. return False
  161. # Pre-process the translation to translated characters for a correct preview and length check
  162. translation = cs.trans_replace(translation)
  163. wrapped_source = wrap_text(source, cols)
  164. rows_count_source = len(wrapped_source)
  165. wrapped_translation = wrap_text(translation, cols)
  166. rows_count_translation = len(wrapped_translation)
  167. # Incorrect number of rows/cols on the definition
  168. if rows == 1 and (len(source) > cols or rows_count_source > rows):
  169. errors += 1
  170. print(yellow('[W]: Source text longer than %d cols as defined on line %d:' % (cols, line)))
  171. print_ruler(4, cols);
  172. print_truncated(source, cols)
  173. print()
  174. elif rows_count_source > rows:
  175. errors += 1
  176. print(yellow('[W]: Wrapped source text longer than %d rows as defined on line %d:' % (rows, line)))
  177. print_ruler(6, cols);
  178. print_wrapped(wrapped_source, rows, cols)
  179. print()
  180. # All further checks are against the translation
  181. if is_pot:
  182. return (errors == 0)
  183. # Missing translation
  184. if len(translation) == 0 and (known_msgid or warn_empty):
  185. errors += 1
  186. if rows == 1:
  187. print(yellow("[W]: Empty translation for \"%s\" on line %d" % (source, line)))
  188. else:
  189. print(yellow("[W]: Empty translation on line %d" % line))
  190. print_ruler(6, cols);
  191. print_wrapped(wrapped_source, rows, cols)
  192. print()
  193. # Check for translation lenght
  194. if (rows_count_translation > rows) or (rows == 1 and len(translation) > cols):
  195. errors += 1
  196. print(red('[E]: Text is longer than definition on line %d: cols=%d rows=%d (rows diff=%d)'
  197. % (line, cols, rows, rows_count_translation-rows)))
  198. print_source_translation(source, translation,
  199. wrapped_source, wrapped_translation,
  200. rows, cols)
  201. # Different count of % sequences
  202. if source.count('%') != translation.count('%') and len(translation) > 0:
  203. errors += 1
  204. print(red('[E]: Unequal count of %% escapes on line %d:' % (line)))
  205. print_source_translation(source, translation,
  206. wrapped_source, wrapped_translation,
  207. rows, cols)
  208. # Different first/last character
  209. if not no_suggest and len(source) > 0 and len(translation) > 0:
  210. source_end = source.rstrip()[-1]
  211. translation_end = translation.rstrip()[-1]
  212. start_diff = not (ign_char_first(source[0]) and ign_char_first(translation[0])) and source[0] != translation[0]
  213. end_diff = not (ign_char_last(source_end) and ign_char_last(translation_end)) and source_end != translation_end
  214. if start_diff or end_diff:
  215. if start_diff:
  216. print(yellow('[S]: Differing first punctuation character (%s => %s) on line %d:' % (source[0], translation[0], line)))
  217. if end_diff:
  218. print(yellow('[S]: Differing last punctuation character (%s => %s) on line %d:' % (source[-1], translation[-1], line)))
  219. print_source_translation(source, translation,
  220. wrapped_source, wrapped_translation,
  221. rows, cols)
  222. if not no_suggest and source == translation and (warn_same or len(source.split(' ', 1)) > 1):
  223. print(yellow('[S]: Translation same as original on line %d:' %line))
  224. print_source_translation(source, translation,
  225. wrapped_source, wrapped_translation,
  226. rows, cols)
  227. # Short translation
  228. if not no_suggest and len(source) > 0 and len(translation) > 0:
  229. if len(translation.rstrip()) < len(source.rstrip()) / 2:
  230. print(yellow('[S]: Short translation on line %d:' % (line)))
  231. print_source_translation(source, translation,
  232. wrapped_source, wrapped_translation,
  233. rows, cols)
  234. # Incorrect trailing whitespace in translation
  235. if not no_warning and len(translation) > 0 and \
  236. (source.rstrip() == source or (rows == 1 and len(source) == cols)) and \
  237. translation.rstrip() != translation and \
  238. (rows > 1 or len(translation) != len(source)):
  239. errors += 1
  240. print(yellow('[W]: Incorrect trailing whitespace for translation on line %d:' % (line)))
  241. source = highlight_trailing_white(source)
  242. translation = highlight_trailing_white(translation)
  243. wrapped_translation = highlight_trailing_white(wrapped_translation)
  244. print_source_translation(source, translation,
  245. wrapped_source, wrapped_translation,
  246. rows, cols)
  247. # show the information
  248. if information and errors == 0:
  249. print(green('[I]: %s' % (meta)))
  250. print_source_translation(source, translation,
  251. wrapped_source, wrapped_translation,
  252. rows, cols)
  253. return (errors == 0)
  254. def main():
  255. """Main function."""
  256. parser = ArgumentParser(description=__doc__)
  257. parser.add_argument("po", help="PO file to check")
  258. parser.add_argument(
  259. "--no-warning", action="store_true",
  260. help="Disable warnings")
  261. parser.add_argument(
  262. "--no-suggest", action="store_true",
  263. help="Disable suggestions")
  264. parser.add_argument(
  265. "--pot", action="store_true",
  266. help="Do not check translations")
  267. parser.add_argument(
  268. "--information", action="store_true",
  269. help="Output all translations")
  270. parser.add_argument("--map",
  271. help="Provide a map file to suppress warnings about unused translations")
  272. parser.add_argument(
  273. "--warn-empty", action="store_true",
  274. help="Warn about empty definitions and translations even if unused")
  275. parser.add_argument(
  276. "--warn-same", action="store_true",
  277. help="Warn about one-word translations which are identical to the source")
  278. # load the translations
  279. args = parser.parse_args()
  280. if not os.path.isfile(args.po):
  281. print("{}: file does not exist or is not a regular file".format(args.po), file=stderr)
  282. return 1
  283. # load the symbol map to supress empty (but unused) translation warnings
  284. msgids = None
  285. if args.map:
  286. msgids = set()
  287. for sym in load_map(args.map):
  288. if type(sym['data']) == bytes:
  289. msgid = cs.source_to_unicode(codecs.decode(sym['data'], 'unicode_escape', 'strict'))
  290. msgids.add(msgid)
  291. # check each translation in turn
  292. status = True
  293. for translation in polib.pofile(args.po):
  294. status &= check_translation(translation, msgids, args.pot, args.no_warning, args.no_suggest,
  295. args.warn_empty, args.warn_same, args.information)
  296. return 0 if status else 1
  297. if __name__ == "__main__":
  298. exit(main())