lang-check.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. def color_maybe(color_attr, text):
  21. if stdout.isatty():
  22. return '\033[0;' + str(color_attr) + 'm' + text + '\033[0m'
  23. else:
  24. return text
  25. red = lambda text: color_maybe(31, text)
  26. green = lambda text: color_maybe(32, text)
  27. yellow = lambda text: color_maybe(33, text)
  28. def print_wrapped(wrapped_text, rows, cols):
  29. if type(wrapped_text) == str:
  30. wrapped_text = [wrapped_text]
  31. for r, line in enumerate(wrapped_text):
  32. r_ = str(r + 1).rjust(3)
  33. if r >= rows:
  34. r_ = color_maybe(31, r_)
  35. print((' {} |{:' + str(cols) + 's}|').format(r_, line))
  36. def print_truncated(text, cols):
  37. if len(text) <= cols:
  38. prefix = text.ljust(cols)
  39. suffix = ''
  40. else:
  41. prefix = text[0:cols]
  42. suffix = color_maybe(31, text[cols:])
  43. print(' |' + prefix + '|' + suffix)
  44. def unescape(text):
  45. if '\\' not in text:
  46. return text
  47. return text.encode('ascii').decode('unicode_escape')
  48. def parse_txt(lang, no_warning):
  49. """Parse txt file and check strings to display definition."""
  50. if lang == "en":
  51. file_path = "lang_en.txt"
  52. else:
  53. file_path = "lang_en_%s.txt" % lang
  54. print(green("Start %s lang-check" % lang))
  55. lines = 1
  56. with open(file_path) as src:
  57. while True:
  58. comment = src.readline().split(' ')
  59. #print (comment) #Debug
  60. #Check if columns and rows are defined
  61. cols = None
  62. rows = None
  63. for item in comment[1:]:
  64. key, val = item.split('=')
  65. if key == 'c':
  66. cols = int(val)
  67. #print ("c=",cols) #Debug
  68. elif key == 'r':
  69. rows = int(val)
  70. #print ("r=",rows) #Debug
  71. else:
  72. raise RuntimeError(
  73. "Unknown display definition %s on line %d" %
  74. (' '.join(comment), lines))
  75. if cols is None and rows is None:
  76. if not no_warning:
  77. print(yellow("[W]: No display definition on line %d" % lines))
  78. cols = len(translation) # propably fullscreen
  79. if rows is None:
  80. rows = 1
  81. elif rows > 1 and cols != 20:
  82. print(yellow("[W]: Multiple rows with odd number of columns on line %d" % lines))
  83. #Wrap text to 20 chars and rows
  84. source = src.readline()[:-1].strip('"')
  85. #print (source) #Debug
  86. translation = src.readline()[:-1].strip('"')
  87. if translation == '\\x00':
  88. # crude hack to handle intentionally-empty translations
  89. translation = ''
  90. # handle backslash sequences
  91. source = unescape(source)
  92. translation = unescape(translation)
  93. #print (translation) #Debug
  94. wrapped_source = list(textwrap.TextWrapper(width=cols).wrap(source))
  95. rows_count_source = len(wrapped_source)
  96. wrapped_translation = list(textwrap.TextWrapper(width=cols).wrap(translation))
  97. rows_count_translation = len(wrapped_translation)
  98. #End wrap text
  99. # Check for potential errors in the definition
  100. if not no_warning:
  101. if rows == 1 and (len(source) > cols or rows_count_source > rows):
  102. print(yellow('[W]: Source text longer than %d cols as defined on line %d:' % (cols, lines)))
  103. print_truncated(source, cols)
  104. print()
  105. elif rows_count_source > rows:
  106. print(yellow('[W]: Wrapped source text longer than %d rows as defined on line %d:' % (rows, lines)))
  107. print_wrapped(wrapped_source, rows, cols)
  108. print()
  109. # Check for translation lenght
  110. if (rows_count_translation > rows) or (rows == 1 and len(translation) > cols):
  111. print(red('[E]: Text is longer then definition on line %d: rows diff=%d cols=%d rows=%d'
  112. % (lines, rows_count_translation-rows, cols, rows)))
  113. if rows == 1:
  114. print(yellow(' source text:'))
  115. print_truncated(source, cols)
  116. print(yellow(' translated text:'))
  117. print_truncated(translation, cols)
  118. else:
  119. print(yellow(' source text:'))
  120. print_wrapped(wrapped_source, rows, cols)
  121. print(yellow(' translated text:'))
  122. print_wrapped(wrapped_translation, rows, cols)
  123. print()
  124. if len(src.readline()) != 1: # empty line
  125. break
  126. lines += 4
  127. print(green("End %s lang-check" % lang))
  128. def main():
  129. """Main function."""
  130. parser = ArgumentParser(
  131. description=__doc__,
  132. usage="%(prog)s lang")
  133. parser.add_argument(
  134. "lang", nargs='?', default="en", type=str,
  135. help="Check lang file (en|cs|de|es|fr|nl|it|pl)")
  136. parser.add_argument(
  137. "--no-warning", action="store_true",
  138. help="Disable warnings")
  139. args = parser.parse_args()
  140. try:
  141. parse_txt(args.lang, args.no_warning)
  142. return 0
  143. except Exception as exc:
  144. print_exc()
  145. parser.error("%s" % exc)
  146. return 1
  147. if __name__ == "__main__":
  148. exit(main())