lang-check.py 17 KB

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