lang-check.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. #!/usr/bin/env python3
  2. #
  3. # Version 1.0.2 - Build 37
  4. #############################################################################
  5. # Change log:
  6. # 7 May 2019, Ondrej Tuma, Initial
  7. # 9 June 2020, 3d-gussner, Added version and Change log
  8. # 9 June 2020, 3d-gussner, Wrap text to 20 char and rows
  9. # 9 June 2020, 3d-gussner, colored output
  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, 3d-gussner, add character ruler
  15. # 07 Jan. 2022, 3d-gussner, Check for Syntax errors and exit with error
  16. # , add Build number 'git rev-list --count HEAD lang-check.py'
  17. #############################################################################
  18. #
  19. # Expected syntax of the files, which other scripts depend on
  20. # 'lang_en.txt'
  21. # 1st line: '#MSG_'<some text>' c='<max chars in a column>' r='<max rows> ; '#MSG' is mandentory while 'c=' and 'r=' aren't but should be there
  22. # 2nd line: '"'<origin message used in the source code>'"' ; '"' double quotes at the beginning and end of message are mandentory
  23. # 3rd line: LF ; Line feed is mandantory between messages
  24. #
  25. # 'lang_en_??.txt'
  26. # 1st line: '#MSG_'<some text>' c='<max chars in a column>' r='<max rows> ; '#MSG' is mandentory while 'c=' and 'r=' aren't but should be there
  27. # 2nd line: '"'<origin message used in the source code>'"' ; '"' double quotes at the beginning and end of message are mandentory
  28. # 3rd line: '"'<translated message>'"' ; '"' double quotes at the beginning and end of message are mandentory
  29. # 4th line: LF ; Line feed is mandantory between messages
  30. #
  31. """Check lang files."""
  32. from argparse import ArgumentParser
  33. from traceback import print_exc
  34. from sys import stdout, stderr, exit
  35. import textwrap
  36. import re
  37. def color_maybe(color_attr, text):
  38. if stdout.isatty():
  39. return '\033[0;' + str(color_attr) + 'm' + text + '\033[0m'
  40. else:
  41. return text
  42. red = lambda text: color_maybe(31, text)
  43. green = lambda text: color_maybe(32, text)
  44. yellow = lambda text: color_maybe(33, text)
  45. cyan = lambda text: color_maybe(36, text)
  46. def print_wrapped(wrapped_text, rows, cols):
  47. if type(wrapped_text) == str:
  48. wrapped_text = [wrapped_text]
  49. for r, line in enumerate(wrapped_text):
  50. r_ = str(r + 1).rjust(3)
  51. if r >= rows:
  52. r_ = red(r_)
  53. print((' {} |{:' + str(cols) + 's}|').format(r_, line))
  54. def print_truncated(text, cols):
  55. if len(text) <= cols:
  56. prefix = text.ljust(cols)
  57. suffix = ''
  58. else:
  59. prefix = text[0:cols]
  60. suffix = red(text[cols:])
  61. print(' |' + prefix + '|' + suffix)
  62. def print_ruler(spc, cols):
  63. print(' ' * spc + cyan(('₀₁₂₃₄₅₆₇₈₉'*4)[:cols]))
  64. def print_source_translation(source, translation, wrapped_source, wrapped_translation, rows, cols):
  65. if rows == 1:
  66. print(' source text:')
  67. print_ruler(4, cols);
  68. print_truncated(source, cols)
  69. print(' translated text:')
  70. print_ruler(4, cols);
  71. print_truncated(translation, cols)
  72. else:
  73. print(' source text:')
  74. print_ruler(6, cols);
  75. print_wrapped(wrapped_source, rows, cols)
  76. print(' translated text:')
  77. print_ruler(6, cols);
  78. print_wrapped(wrapped_translation, rows, cols)
  79. print()
  80. def highlight_trailing_white(text):
  81. if type(text) == str:
  82. return re.sub(r' $', '·', text)
  83. else:
  84. ret = text[:]
  85. ret[-1] = highlight_trailing_white(ret[-1])
  86. return ret
  87. def wrap_text(text, cols):
  88. # wrap text
  89. ret = list(textwrap.TextWrapper(width=cols).wrap(text))
  90. if len(ret):
  91. # add back trailing whitespace
  92. ret[-1] += ' ' * (len(text) - len(text.rstrip()))
  93. return ret
  94. def unescape(text):
  95. if '\\' not in text:
  96. return text
  97. return text.encode('ascii').decode('unicode_escape')
  98. def ign_char_first(c):
  99. return c.isalnum() or c in {'%', '?'}
  100. def ign_char_last(c):
  101. return c.isalnum() or c in {'.', "'"}
  102. def parse_txt(lang, no_warning, warn_empty):
  103. """Parse txt file and check strings to display definition."""
  104. if lang == "en":
  105. file_path = "lang_en.txt"
  106. else:
  107. file_path = "lang_en_%s.txt" % lang
  108. print(green("Start %s lang-check" % lang))
  109. lines = 0
  110. with open(file_path) as src:
  111. while True:
  112. message = src.readline()
  113. lines += 1
  114. #print(message) #Debug
  115. #check syntax 1st line starts with `#MSG`
  116. if (message[0:4] != '#MSG'):
  117. print(red("[E]: Critical syntax error: 1st line doesn't start with #MSG on line %d" % lines))
  118. print(red(message))
  119. exit(1)
  120. #Check if columns and rows are defined
  121. comment = message.split(' ')
  122. #Check if columns and rows are defined
  123. cols = None
  124. rows = None
  125. for item in comment[1:]:
  126. key, val = item.split('=')
  127. if key == 'c':
  128. cols = int(val)
  129. #print ("c=",cols) #Debug
  130. elif key == 'r':
  131. rows = int(val)
  132. #print ("r=",rows) #Debug
  133. else:
  134. raise RuntimeError(
  135. "Unknown display definition %s on line %d" %
  136. (' '.join(comment), lines))
  137. if cols is None and rows is None:
  138. if not no_warning:
  139. print(yellow("[W]: No display definition on line %d" % lines))
  140. cols = len(source) # propably fullscreen
  141. if rows is None:
  142. rows = 1
  143. elif rows > 1 and cols != 20:
  144. print(yellow("[W]: Multiple rows with odd number of columns on line %d" % lines))
  145. #Wrap text to 20 chars and rows
  146. source = src.readline()[:-1] #read whole line
  147. lines += 1
  148. #check if 2nd line of origin message beginns and ends with " double quote
  149. if (source[0]!="\""):
  150. print(red('[E]: Critical syntax error: Missing " double quotes at beginning of message in source on line %d' % lines))
  151. print(red(source))
  152. exit(1)
  153. if (source[-1]=="\""):
  154. source = source.strip('"') #remove " double quotes from message
  155. else:
  156. print(red('[E]: Critical syntax error: Missing " double quotes at end of message in source on line %d' % lines))
  157. print(red(source))
  158. exit(1)
  159. #print(source) #Debug
  160. if lang != "en":
  161. translation = src.readline()[:-1]#read whole line
  162. lines += 1
  163. #check if 3rd line of translation message beginns and ends with " double quote
  164. if (translation[0]!="\""):
  165. print(red('[E]: Critical syntax error: Missing " double quotes at beginning of message in translation on line %d' % lines))
  166. print(red(translation))
  167. exit(1)
  168. if (translation[-1]=="\""):
  169. #print ("End ok")
  170. translation = translation.strip('"') #remove " double quote from message
  171. else:
  172. print(red('[E]: Critical syntax error: Missing " double quotes at end of message in translation on line %d' % lines))
  173. print(red(translation))
  174. exit(1)
  175. #print(translation) #Debug
  176. if translation == '\\x00':
  177. # crude hack to handle intentionally-empty translations
  178. translation = ''
  179. #check if source is ascii only
  180. if source.isascii() == False:
  181. print(red('[E]: Critical syntax: Non ascii chars found on line %d' % lines))
  182. print(red(source))
  183. exit(1)
  184. #check if translation is ascii only
  185. if lang != "en":
  186. if translation.isascii() == False:
  187. print(red('[E]: Critical syntax: Non ascii chars found on line %d' % lines))
  188. print(red(translation))
  189. exit(1)
  190. # handle backslash sequences
  191. source = unescape(source)
  192. if lang != "en":
  193. translation = unescape(translation)
  194. #print (translation) #Debug
  195. wrapped_source = wrap_text(source, cols)
  196. rows_count_source = len(wrapped_source)
  197. if lang != "en":
  198. wrapped_translation = wrap_text(translation, cols)
  199. rows_count_translation = len(wrapped_translation)
  200. # Check for potential errors in the definition
  201. if not no_warning:
  202. # Incorrect number of rows/cols on the definition
  203. if rows == 1 and (len(source) > cols or rows_count_source > rows):
  204. print(yellow('[W]: Source text longer than %d cols as defined on line %d:' % (cols, lines)))
  205. print_ruler(4, cols);
  206. print_truncated(source, cols)
  207. print()
  208. elif rows_count_source > rows:
  209. print(yellow('[W]: Wrapped source text longer than %d rows as defined on line %d:' % (rows, lines)))
  210. print_ruler(6, cols);
  211. print_wrapped(wrapped_source, rows, cols)
  212. print()
  213. # Missing translation
  214. if lang != "en":
  215. if len(translation) == 0 and (warn_empty or rows > 1):
  216. if rows == 1:
  217. print(yellow("[W]: Empty translation for \"%s\" on line %d" % (source, lines)))
  218. else:
  219. print(yellow("[W]: Empty translation on line %d" % lines))
  220. print_ruler(6, cols);
  221. print_wrapped(wrapped_source, rows, cols)
  222. print()
  223. # Check for translation lenght
  224. if (rows_count_translation > rows) or (rows == 1 and len(translation) > cols):
  225. print(red('[E]: Text is longer than definition on line %d: cols=%d rows=%d (rows diff=%d)'
  226. % (lines, cols, rows, rows_count_translation-rows)))
  227. print_source_translation(source, translation,
  228. wrapped_source, wrapped_translation,
  229. rows, cols)
  230. # Different count of % sequences
  231. if source.count('%') != translation.count('%') and len(translation) > 0:
  232. print(red('[E]: Unequal count of %% escapes on line %d:' % (lines)))
  233. print_source_translation(source, translation,
  234. wrapped_source, wrapped_translation,
  235. rows, cols)
  236. # Different first/last character
  237. if not no_warning and len(source) > 0 and len(translation) > 0:
  238. source_end = source.rstrip()[-1]
  239. translation_end = translation.rstrip()[-1]
  240. start_diff = not (ign_char_first(source[0]) and ign_char_first(translation[0])) and source[0] != translation[0]
  241. end_diff = not (ign_char_last(source_end) and ign_char_last(translation_end)) and source_end != translation_end
  242. if start_diff or end_diff:
  243. if start_diff:
  244. print(yellow('[W]: Differing first punctuation character (%s => %s) on line %d:' % (source[0], translation[0], lines)))
  245. if end_diff:
  246. print(yellow('[W]: Differing last punctuation character (%s => %s) on line %d:' % (source[-1], translation[-1], lines)))
  247. print_source_translation(source, translation,
  248. wrapped_source, wrapped_translation,
  249. rows, cols)
  250. # Short translation
  251. if not no_warning and len(source) > 0 and len(translation) > 0:
  252. if len(translation.rstrip()) < len(source.rstrip()) / 2:
  253. print(yellow('[W]: Short translation on line %d:' % (lines)))
  254. print_source_translation(source, translation,
  255. wrapped_source, wrapped_translation,
  256. rows, cols)
  257. # Incorrect trailing whitespace in translation
  258. if not no_warning and len(translation) > 0 and \
  259. (source.rstrip() == source or (rows == 1 and len(source) == cols)) and \
  260. translation.rstrip() != translation and \
  261. (rows > 1 or len(translation) != len(source)):
  262. print(yellow('[W]: Incorrect trailing whitespace for translation on line %d:' % (lines)))
  263. source = highlight_trailing_white(source)
  264. translation = highlight_trailing_white(translation)
  265. wrapped_translation = highlight_trailing_white(wrapped_translation)
  266. print_source_translation(source, translation,
  267. wrapped_source, wrapped_translation,
  268. rows, cols)
  269. delimiter = src.readline()
  270. lines += 1
  271. if ("" == delimiter):
  272. break
  273. elif len(delimiter) != 1: # empty line
  274. print(red('[E]: Critical Syntax error: Missing empty line between messages between lines: %d and %d' % (lines-1,lines)))
  275. break
  276. print(green("End %s lang-check" % lang))
  277. def main():
  278. """Main function."""
  279. parser = ArgumentParser(
  280. description=__doc__,
  281. usage="%(prog)s lang")
  282. parser.add_argument(
  283. "lang", nargs='?', default="en", type=str,
  284. help="Check lang file (en|cs|da|de|es|fr|hr|hu|lb|lt|nl|it|pl|ro|sl|sv)")
  285. parser.add_argument(
  286. "--no-warning", action="store_true",
  287. help="Disable warnings")
  288. parser.add_argument(
  289. "--warn-empty", action="store_true",
  290. help="Warn about empty translations")
  291. args = parser.parse_args()
  292. try:
  293. parse_txt(args.lang, args.no_warning, args.warn_empty)
  294. return 0
  295. except Exception as exc:
  296. print_exc()
  297. parser.error("%s" % exc)
  298. return 1
  299. if __name__ == "__main__":
  300. exit(main())