checktransupdate.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. """
  4. This script helps track the translation status of the documentation
  5. in different locales, e.g., zh_CN. More specially, it uses `git log`
  6. commit to find the latest english commit from the translation commit
  7. (order by author date) and the latest english commits from HEAD. If
  8. differences occur, report the file and commits that need to be updated.
  9. The usage is as follows:
  10. - ./scripts/checktransupdate.py -l zh_CN
  11. This will print all the files that need to be updated or translated in the zh_CN locale.
  12. - ./scripts/checktransupdate.py Documentation/translations/zh_CN/dev-tools/testing-overview.rst
  13. This will only print the status of the specified file.
  14. The output is something like:
  15. Documentation/dev-tools/kfence.rst
  16. No translation in the locale of zh_CN
  17. Documentation/translations/zh_CN/dev-tools/testing-overview.rst
  18. commit 42fb9cfd5b18 ("Documentation: dev-tools: Add link to RV docs")
  19. 1 commits needs resolving in total
  20. """
  21. import os
  22. import time
  23. import logging
  24. from argparse import ArgumentParser, ArgumentTypeError, BooleanOptionalAction
  25. from datetime import datetime
  26. def get_origin_path(file_path):
  27. """Get the origin path from the translation path"""
  28. paths = file_path.split("/")
  29. tidx = paths.index("translations")
  30. opaths = paths[:tidx]
  31. opaths += paths[tidx + 2 :]
  32. return "/".join(opaths)
  33. def get_latest_commit_from(file_path, commit):
  34. """Get the latest commit from the specified commit for the specified file"""
  35. command = f"git log --pretty=format:%H%n%aD%n%cD%n%n%B {commit} -1 -- {file_path}"
  36. logging.debug(command)
  37. pipe = os.popen(command)
  38. result = pipe.read()
  39. result = result.split("\n")
  40. if len(result) <= 1:
  41. return None
  42. logging.debug("Result: %s", result[0])
  43. return {
  44. "hash": result[0],
  45. "author_date": datetime.strptime(result[1], "%a, %d %b %Y %H:%M:%S %z"),
  46. "commit_date": datetime.strptime(result[2], "%a, %d %b %Y %H:%M:%S %z"),
  47. "message": result[4:],
  48. }
  49. def get_origin_from_trans(origin_path, t_from_head):
  50. """Get the latest origin commit from the translation commit"""
  51. o_from_t = get_latest_commit_from(origin_path, t_from_head["hash"])
  52. while o_from_t is not None and o_from_t["author_date"] > t_from_head["author_date"]:
  53. o_from_t = get_latest_commit_from(origin_path, o_from_t["hash"] + "^")
  54. if o_from_t is not None:
  55. logging.debug("tracked origin commit id: %s", o_from_t["hash"])
  56. return o_from_t
  57. def get_commits_count_between(opath, commit1, commit2):
  58. """Get the commits count between two commits for the specified file"""
  59. command = f"git log --pretty=format:%H {commit1}...{commit2} -- {opath}"
  60. logging.debug(command)
  61. pipe = os.popen(command)
  62. result = pipe.read().split("\n")
  63. # filter out empty lines
  64. result = list(filter(lambda x: x != "", result))
  65. return result
  66. def pretty_output(commit):
  67. """Pretty print the commit message"""
  68. command = f"git log --pretty='format:%h (\"%s\")' -1 {commit}"
  69. logging.debug(command)
  70. pipe = os.popen(command)
  71. return pipe.read()
  72. def valid_commit(commit):
  73. """Check if the commit is valid or not"""
  74. msg = pretty_output(commit)
  75. return "Merge tag" not in msg
  76. def check_per_file(file_path):
  77. """Check the translation status for the specified file"""
  78. opath = get_origin_path(file_path)
  79. if not os.path.isfile(opath):
  80. logging.error("Cannot find the origin path for {file_path}")
  81. return
  82. o_from_head = get_latest_commit_from(opath, "HEAD")
  83. t_from_head = get_latest_commit_from(file_path, "HEAD")
  84. if o_from_head is None or t_from_head is None:
  85. logging.error("Cannot find the latest commit for %s", file_path)
  86. return
  87. o_from_t = get_origin_from_trans(opath, t_from_head)
  88. if o_from_t is None:
  89. logging.error("Error: Cannot find the latest origin commit for %s", file_path)
  90. return
  91. if o_from_head["hash"] == o_from_t["hash"]:
  92. logging.debug("No update needed for %s", file_path)
  93. else:
  94. logging.info(file_path)
  95. commits = get_commits_count_between(
  96. opath, o_from_t["hash"], o_from_head["hash"]
  97. )
  98. count = 0
  99. for commit in commits:
  100. if valid_commit(commit):
  101. logging.info("commit %s", pretty_output(commit))
  102. count += 1
  103. logging.info("%d commits needs resolving in total\n", count)
  104. def valid_locales(locale):
  105. """Check if the locale is valid or not"""
  106. script_path = os.path.dirname(os.path.abspath(__file__))
  107. linux_path = os.path.join(script_path, "..")
  108. if not os.path.isdir(f"{linux_path}/Documentation/translations/{locale}"):
  109. raise ArgumentTypeError("Invalid locale: {locale}")
  110. return locale
  111. def list_files_with_excluding_folders(folder, exclude_folders, include_suffix):
  112. """List all files with the specified suffix in the folder and its subfolders"""
  113. files = []
  114. stack = [folder]
  115. while stack:
  116. pwd = stack.pop()
  117. # filter out the exclude folders
  118. if os.path.basename(pwd) in exclude_folders:
  119. continue
  120. # list all files and folders
  121. for item in os.listdir(pwd):
  122. ab_item = os.path.join(pwd, item)
  123. if os.path.isdir(ab_item):
  124. stack.append(ab_item)
  125. else:
  126. if ab_item.endswith(include_suffix):
  127. files.append(ab_item)
  128. return files
  129. class DmesgFormatter(logging.Formatter):
  130. """Custom dmesg logging formatter"""
  131. def format(self, record):
  132. timestamp = time.time()
  133. formatted_time = f"[{timestamp:>10.6f}]"
  134. log_message = f"{formatted_time} {record.getMessage()}"
  135. return log_message
  136. def config_logging(log_level, log_file="checktransupdate.log"):
  137. """configure logging based on the log level"""
  138. # set up the root logger
  139. logger = logging.getLogger()
  140. logger.setLevel(log_level)
  141. # Create console handler
  142. console_handler = logging.StreamHandler()
  143. console_handler.setLevel(log_level)
  144. # Create file handler
  145. file_handler = logging.FileHandler(log_file)
  146. file_handler.setLevel(log_level)
  147. # Create formatter and add it to the handlers
  148. formatter = DmesgFormatter()
  149. console_handler.setFormatter(formatter)
  150. file_handler.setFormatter(formatter)
  151. # Add the handler to the logger
  152. logger.addHandler(console_handler)
  153. logger.addHandler(file_handler)
  154. def main():
  155. """Main function of the script"""
  156. script_path = os.path.dirname(os.path.abspath(__file__))
  157. linux_path = os.path.join(script_path, "..")
  158. parser = ArgumentParser(description="Check the translation update")
  159. parser.add_argument(
  160. "-l",
  161. "--locale",
  162. default="zh_CN",
  163. type=valid_locales,
  164. help="Locale to check when files are not specified",
  165. )
  166. parser.add_argument(
  167. "--print-missing-translations",
  168. action=BooleanOptionalAction,
  169. default=True,
  170. help="Print files that do not have translations",
  171. )
  172. parser.add_argument(
  173. '--log',
  174. default='INFO',
  175. choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
  176. help='Set the logging level')
  177. parser.add_argument(
  178. '--logfile',
  179. default='checktransupdate.log',
  180. help='Set the logging file (default: checktransupdate.log)')
  181. parser.add_argument(
  182. "files", nargs="*", help="Files to check, if not specified, check all files"
  183. )
  184. args = parser.parse_args()
  185. # Configure logging based on the --log argument
  186. log_level = getattr(logging, args.log.upper(), logging.INFO)
  187. config_logging(log_level)
  188. # Get files related to linux path
  189. files = args.files
  190. if len(files) == 0:
  191. offical_files = list_files_with_excluding_folders(
  192. os.path.join(linux_path, "Documentation"), ["translations", "output"], "rst"
  193. )
  194. for file in offical_files:
  195. # split the path into parts
  196. path_parts = file.split(os.sep)
  197. # find the index of the "Documentation" directory
  198. kindex = path_parts.index("Documentation")
  199. # insert the translations and locale after the Documentation directory
  200. new_path_parts = path_parts[:kindex + 1] + ["translations", args.locale] \
  201. + path_parts[kindex + 1 :]
  202. # join the path parts back together
  203. new_file = os.sep.join(new_path_parts)
  204. if os.path.isfile(new_file):
  205. files.append(new_file)
  206. else:
  207. if args.print_missing_translations:
  208. logging.info(os.path.relpath(os.path.abspath(file), linux_path))
  209. logging.info("No translation in the locale of %s\n", args.locale)
  210. files = list(map(lambda x: os.path.relpath(os.path.abspath(x), linux_path), files))
  211. # cd to linux root directory
  212. os.chdir(linux_path)
  213. for file in files:
  214. check_per_file(file)
  215. if __name__ == "__main__":
  216. main()