1
0

set-page-title.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: MIT
  3. """
  4. A Python script to add or update the page title for all translations of a page.
  5. Note: If the current directory or one of its parents is called "tldr", the script will assume it is the tldr root, i.e., the directory that contains a clone of https://github.com/tldr-pages/tldr
  6. If the script doesn't find it in the current path, the environment variable TLDR_ROOT will be used as the tldr root. Also, ensure 'git' is available.
  7. Usage:
  8. python3 scripts/set-page-title.py [-p PAGE] [-S] [-l LANGUAGE] [-s] [-n] [TITLE]
  9. Options:
  10. -p, --page PAGE
  11. Specify the page in the format "platform/command". This option allows setting the title for a specific page.
  12. -S, --sync
  13. Synchronize each translation's title (if exists) with that of the English page.
  14. -l, --language LANGUAGE
  15. Specify the language, a POSIX Locale Name in the form of "ll" or "ll_CC" (e.g. "fr" or "pt_BR").
  16. -s, --stage
  17. Stage modified pages (requires 'git' on $PATH and TLDR_ROOT to be a Git repository).
  18. -n, --dry-run
  19. Show what changes would be made without actually modifying the page.
  20. Positional Argument:
  21. TITLE The title to be set as the title.
  22. Examples:
  23. 1. Set the title for a specific page:
  24. python3 scripts/set-page-title.py -p common/tar tar
  25. python3 scripts/set-page-title.py --page common/tar tar
  26. 2. Synchronize titles across translations:
  27. python3 scripts/set-page-title.py -S
  28. python3 scripts/set-page-title.py --sync
  29. 3. Read English pages and synchronize the title for Brazilian Portuguese pages only:
  30. python3 scripts/set-page-title.py -S -l pt_BR
  31. python3 scripts/set-page-title.py --sync --language pt_BR
  32. 4. Synchronize titles across translations and stage modified pages for commit:
  33. python3 scripts/set-page-title.py -Ss
  34. python3 scripts/set-page-title.py --sync --stage
  35. 5. Show what changes would be made across translations:
  36. python3 scripts/set-page-title.py -Sn
  37. python3 scripts/set-page-title.py --sync --dry-run
  38. """
  39. from pathlib import Path
  40. from _common import (
  41. IGNORE_FILES,
  42. Colors,
  43. get_tldr_root,
  44. get_pages_dir,
  45. get_target_paths,
  46. get_locale,
  47. get_status,
  48. stage,
  49. create_colored_line,
  50. create_argument_parser,
  51. )
  52. def set_page_title(
  53. path: Path, title: str, dry_run: bool = False, language_to_update: str = ""
  54. ) -> str:
  55. """
  56. Write a title in a page to disk.
  57. Parameters:
  58. path (string): Path to a page
  59. title (string): The title to insert.
  60. dry_run (bool): Whether to perform a dry-run, i.e. only show the changes that would be made.
  61. language_to_update (string): Optionally, the language of the translation to be updated.
  62. Returns:
  63. str: Execution status
  64. "" if the page does not need an update or if the locale does not match language_to_update.
  65. "\x1b[36mtitle added"
  66. "\x1b[34mtitle updated"
  67. "\x1b[36mtitle would be added"
  68. "\x1b[34mtitle would updated"
  69. """
  70. locale = get_locale(path)
  71. if language_to_update != "" and locale != language_to_update:
  72. # return empty status to indicate that no changes were made
  73. return ""
  74. new_line = f"# {title}\n"
  75. # Read the content of the Markdown file
  76. with path.open(encoding="utf-8") as f:
  77. lines = f.readlines()
  78. if lines[0] == new_line:
  79. # return empty status to indicate that no changes were made
  80. return ""
  81. status = get_status("updated", dry_run, "title")
  82. if not dry_run: # Only write to the path during a non-dry-run
  83. lines[0] = new_line
  84. with path.open("w", encoding="utf-8") as f:
  85. f.writelines(lines)
  86. return status
  87. def get_page_title(path: Path) -> str:
  88. """
  89. Determine whether the given path has a title.
  90. Parameters:
  91. path (Path): Path to a page
  92. Returns:
  93. str: "" If the path doesn't exit or does not have a title,
  94. otherwise return the page title.
  95. """
  96. if not path.exists():
  97. return ""
  98. with path.open(encoding="utf-8") as f:
  99. first_line = f.readline().strip()
  100. return first_line.split("#", 1)[-1].strip()
  101. def sync(
  102. root: Path,
  103. pages_dirs: list[Path],
  104. command: str,
  105. title: str,
  106. dry_run: bool = False,
  107. language_to_update: str = "",
  108. ) -> list[str]:
  109. """
  110. Synchronize a page title into all translations.
  111. Parameters:
  112. root (Path): TLDR_ROOT
  113. pages_dirs (list of Path's): Path's of page entry and platform, e.g. "page.fr/common".
  114. command (str): A command like "tar".
  115. title (str): A title like "tar".
  116. dry_run (bool): Whether to perform a dry-run, i.e. only show the changes that would be made.
  117. language_to_update (str): Optionally, the language of the translation to be updated.
  118. Returns:
  119. list (list of Path's): A list of Path's to be staged into git, using by --stage option.
  120. """
  121. paths = []
  122. for page_dir in pages_dirs:
  123. path = root / page_dir / command
  124. if path.exists():
  125. status = set_page_title(path, title, dry_run, language_to_update)
  126. if status != "":
  127. rel_path = "/".join(path.parts[-3:])
  128. paths.append(rel_path)
  129. print(create_colored_line(Colors.GREEN, f"{rel_path} {status}"))
  130. return paths
  131. def main():
  132. parser = create_argument_parser("Sets the title for all translations of a page")
  133. parser.add_argument("title", type=str, nargs="?", default="")
  134. args = parser.parse_args()
  135. root = get_tldr_root()
  136. pages_dirs = get_pages_dir(root)
  137. target_paths = []
  138. # Use '--page' option
  139. if args.page != "":
  140. target_paths += get_target_paths(args.page, pages_dirs)
  141. for path in target_paths:
  142. rel_path = "/".join(path.parts[-3:])
  143. status = set_page_title(path, args.title)
  144. if status != "":
  145. print(create_colored_line(Colors.GREEN, f"{rel_path} {status}"))
  146. # Use '--sync' option
  147. elif args.sync:
  148. pages_dirs.remove(root / "pages")
  149. en_path = root / "pages"
  150. platforms = [i.name for i in en_path.iterdir() if i.name not in IGNORE_FILES]
  151. for platform in platforms:
  152. platform_path = en_path / platform
  153. commands = [
  154. f"{platform}/{page.name}"
  155. for page in platform_path.iterdir()
  156. if page.name not in IGNORE_FILES
  157. ]
  158. for command in commands:
  159. title = get_page_title(root / "pages" / command)
  160. if title != "":
  161. target_paths += sync(
  162. root, pages_dirs, command, title, args.dry_run, args.language
  163. )
  164. # Use '--stage' option
  165. if args.stage and not args.dry_run and len(target_paths) > 0:
  166. stage(target_paths)
  167. if __name__ == "__main__":
  168. main()