gendocs.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. # Support code for building docs (build_usage, build_man)
  2. import os
  3. import io
  4. import re
  5. import sys
  6. import textwrap
  7. from collections import OrderedDict
  8. from datetime import datetime, timezone
  9. import time
  10. def format_metavar(option):
  11. if option.nargs in ("*", "..."):
  12. return "[%s...]" % option.metavar
  13. elif option.nargs == "?":
  14. return "[%s]" % option.metavar
  15. elif option.nargs is None:
  16. return option.metavar
  17. else:
  18. raise ValueError(f"Can't format metavar {option.metavar}, unknown nargs {option.nargs}!")
  19. class BuildUsage:
  20. """generate usage docs for each command"""
  21. def run(self):
  22. print("generating usage docs")
  23. import borg
  24. borg.doc_mode = "build_man"
  25. os.makedirs("docs/usage", exist_ok=True)
  26. # allows us to build docs without the C modules fully loaded during help generation
  27. from borg.archiver import Archiver
  28. parser = Archiver(prog="borg").build_parser()
  29. # borgfs has a separate man page to satisfy debian's "every program from a package
  30. # must have a man page" requirement, but it doesn't need a separate HTML docs page
  31. # borgfs_parser = Archiver(prog='borgfs').build_parser()
  32. self.generate_level("", parser, Archiver)
  33. return 0
  34. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  35. is_subcommand = False
  36. choices = {}
  37. for action in parser._actions:
  38. if action.choices is not None and "SubParsersAction" in str(action.__class__):
  39. is_subcommand = True
  40. for cmd, parser in action.choices.items():
  41. choices[prefix + cmd] = parser
  42. if extra_choices is not None:
  43. choices.update(extra_choices)
  44. if prefix and not choices:
  45. return
  46. print("found commands: %s" % list(choices.keys()))
  47. for command, parser in sorted(choices.items()):
  48. if command.startswith("debug"):
  49. print("skipping", command)
  50. continue
  51. print("generating help for %s" % command)
  52. if self.generate_level(command + " ", parser, Archiver):
  53. continue
  54. with open("docs/usage/%s.rst.inc" % command.replace(" ", "_"), "w") as doc:
  55. doc.write(".. IMPORTANT: this file is auto-generated from borg's built-in help, do not edit!\n\n")
  56. if command == "help":
  57. for topic in Archiver.helptext:
  58. params = {"topic": topic, "underline": "~" * len("borg help " + topic)}
  59. doc.write(".. _borg_{topic}:\n\n".format(**params))
  60. doc.write("borg help {topic}\n{underline}\n\n".format(**params))
  61. doc.write(Archiver.helptext[topic])
  62. else:
  63. params = {
  64. "command": command,
  65. "command_": command.replace(" ", "_"),
  66. "underline": "-" * len("borg " + command),
  67. }
  68. doc.write(".. _borg_{command_}:\n\n".format(**params))
  69. doc.write(
  70. "borg {command}\n{underline}\n.. code-block:: none\n\n borg [common options] {command}".format(
  71. **params
  72. )
  73. )
  74. self.write_usage(parser, doc)
  75. epilog = parser.epilog
  76. parser.epilog = None
  77. self.write_options(parser, doc)
  78. doc.write("\n\nDescription\n~~~~~~~~~~~\n")
  79. doc.write(epilog)
  80. if "create" in choices:
  81. common_options = [group for group in choices["create"]._action_groups if group.title == "Common options"][0]
  82. with open("docs/usage/common-options.rst.inc", "w") as doc:
  83. self.write_options_group(common_options, doc, False, base_indent=0)
  84. return is_subcommand
  85. def write_usage(self, parser, fp):
  86. if any(len(o.option_strings) for o in parser._actions):
  87. fp.write(" [options]")
  88. for option in parser._actions:
  89. if option.option_strings:
  90. continue
  91. fp.write(" " + format_metavar(option))
  92. fp.write("\n\n")
  93. def write_options(self, parser, fp):
  94. def is_positional_group(group):
  95. return any(not o.option_strings for o in group._group_actions)
  96. # HTML output:
  97. # A table using some column-spans
  98. rows = []
  99. for group in parser._action_groups:
  100. if group.title == "Common options":
  101. # (no of columns used, columns, ...)
  102. rows.append((1, ".. class:: borg-common-opt-ref\n\n:ref:`common_options`"))
  103. else:
  104. if not group._group_actions:
  105. continue
  106. group_header = "**%s**" % group.title
  107. if group.description:
  108. group_header += " — " + group.description
  109. rows.append((1, group_header))
  110. if is_positional_group(group):
  111. for option in group._group_actions:
  112. rows.append((3, "", "``%s``" % option.metavar, option.help or ""))
  113. else:
  114. for option in group._group_actions:
  115. if option.metavar:
  116. option_fmt = "``%s " + option.metavar + "``"
  117. else:
  118. option_fmt = "``%s``"
  119. option_str = ", ".join(option_fmt % s for s in option.option_strings)
  120. option_desc = textwrap.dedent((option.help or "") % option.__dict__)
  121. rows.append((3, "", option_str, option_desc))
  122. fp.write(".. only:: html\n\n")
  123. table = io.StringIO()
  124. table.write(".. class:: borg-options-table\n\n")
  125. self.rows_to_table(rows, table.write)
  126. fp.write(textwrap.indent(table.getvalue(), " " * 4))
  127. # LaTeX output:
  128. # Regular rST option lists (irregular column widths)
  129. latex_options = io.StringIO()
  130. for group in parser._action_groups:
  131. if group.title == "Common options":
  132. latex_options.write("\n\n:ref:`common_options`\n")
  133. latex_options.write(" |")
  134. else:
  135. self.write_options_group(group, latex_options)
  136. fp.write("\n.. only:: latex\n\n")
  137. fp.write(textwrap.indent(latex_options.getvalue(), " " * 4))
  138. def rows_to_table(self, rows, write):
  139. def write_row_separator():
  140. write("+")
  141. for column_width in column_widths:
  142. write("-" * (column_width + 1))
  143. write("+")
  144. write("\n")
  145. # Find column count and width
  146. column_count = max(columns for columns, *_ in rows)
  147. column_widths = [0] * column_count
  148. for columns, *cells in rows:
  149. for i in range(columns):
  150. # "+ 1" because we want a space between the cell contents and the delimiting "|" in the output
  151. column_widths[i] = max(column_widths[i], len(cells[i]) + 1)
  152. for columns, *original_cells in rows:
  153. write_row_separator()
  154. # If a cell contains newlines, then the row must be split up in individual rows
  155. # where each cell contains no newline.
  156. rowspanning_cells = []
  157. original_cells = list(original_cells)
  158. while any("\n" in cell for cell in original_cells):
  159. cell_bloc = []
  160. for i, cell in enumerate(original_cells):
  161. pre, _, original_cells[i] = cell.partition("\n")
  162. cell_bloc.append(pre)
  163. rowspanning_cells.append(cell_bloc)
  164. rowspanning_cells.append(original_cells)
  165. for cells in rowspanning_cells:
  166. for i, column_width in enumerate(column_widths):
  167. if i < columns:
  168. write("| ")
  169. write(cells[i].ljust(column_width))
  170. else:
  171. write(" ")
  172. write("".ljust(column_width))
  173. write("|\n")
  174. write_row_separator()
  175. # This bit of JavaScript kills the <colgroup> that is invariably inserted by docutils,
  176. # but does absolutely no good here. It sets bogus column widths which cannot be overridden
  177. # with CSS alone.
  178. # Since this is HTML-only output, it would be possible to just generate a <table> directly,
  179. # but then we'd lose rST formatting.
  180. write(
  181. textwrap.dedent(
  182. """
  183. .. raw:: html
  184. <script type='text/javascript'>
  185. $(document).ready(function () {
  186. $('.borg-options-table colgroup').remove();
  187. })
  188. </script>
  189. """
  190. )
  191. )
  192. def write_options_group(self, group, fp, with_title=True, base_indent=4):
  193. def is_positional_group(group):
  194. return any(not o.option_strings for o in group._group_actions)
  195. indent = " " * base_indent
  196. if is_positional_group(group):
  197. for option in group._group_actions:
  198. fp.write(option.metavar + "\n")
  199. fp.write(textwrap.indent(option.help or "", " " * base_indent) + "\n")
  200. return
  201. if not group._group_actions:
  202. return
  203. if with_title:
  204. fp.write("\n\n")
  205. fp.write(group.title + "\n")
  206. opts = OrderedDict()
  207. for option in group._group_actions:
  208. if option.metavar:
  209. option_fmt = "%s " + option.metavar
  210. else:
  211. option_fmt = "%s"
  212. option_str = ", ".join(option_fmt % s for s in option.option_strings)
  213. option_desc = textwrap.dedent((option.help or "") % option.__dict__)
  214. opts[option_str] = textwrap.indent(option_desc, " " * 4)
  215. padding = len(max(opts)) + 1
  216. for option, desc in opts.items():
  217. fp.write(indent + option.ljust(padding) + desc + "\n")
  218. class BuildMan:
  219. """build man pages"""
  220. see_also = {
  221. "create": ("delete", "prune", "check", "patterns", "placeholders", "compression", "rcreate"),
  222. "recreate": ("patterns", "placeholders", "compression"),
  223. "list": ("info", "diff", "prune", "patterns", "rlist"),
  224. "info": ("list", "diff", "rinfo"),
  225. "rcreate": ("rdelete", "rlist", "check", "benchmark-cpu", "key-import", "key-export", "key-change-passphrase"),
  226. "key-import": ("key-export",),
  227. "key-export": ("key-import",),
  228. "mount": ("umount", "extract"), # Would be cooler if these two were on the same page
  229. "umount": ("mount",),
  230. "extract": ("mount",),
  231. "delete": ("compact", "rdelete"),
  232. "prune": ("compact",),
  233. }
  234. rst_prelude = textwrap.dedent(
  235. """
  236. .. role:: ref(title)
  237. .. |project_name| replace:: Borg
  238. """
  239. )
  240. usage_group = {
  241. "break-lock": "lock",
  242. "with-lock": "lock",
  243. "key_change-passphrase": "key",
  244. "key_change-location": "key",
  245. "key_export": "key",
  246. "key_import": "key",
  247. "export-tar": "tar",
  248. "import-tar": "tar",
  249. "benchmark_crud": "benchmark",
  250. "benchmark_cpu": "benchmark",
  251. "umount": "mount",
  252. }
  253. def run(self):
  254. print("building man pages (in docs/man)", file=sys.stderr)
  255. import borg
  256. borg.doc_mode = "build_man"
  257. os.makedirs("docs/man", exist_ok=True)
  258. # allows us to build docs without the C modules fully loaded during help generation
  259. from borg.archiver import Archiver
  260. parser = Archiver(prog="borg").build_parser()
  261. borgfs_parser = Archiver(prog="borgfs").build_parser()
  262. self.generate_level("", parser, Archiver, {"borgfs": borgfs_parser})
  263. self.build_topic_pages(Archiver)
  264. self.build_intro_page()
  265. return 0
  266. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  267. is_subcommand = False
  268. choices = {}
  269. for action in parser._actions:
  270. if action.choices is not None and "SubParsersAction" in str(action.__class__):
  271. is_subcommand = True
  272. for cmd, parser in action.choices.items():
  273. choices[prefix + cmd] = parser
  274. if extra_choices is not None:
  275. choices.update(extra_choices)
  276. if prefix and not choices:
  277. return
  278. for command, parser in sorted(choices.items()):
  279. if command.startswith("debug") or command == "help":
  280. continue
  281. if command == "borgfs":
  282. man_title = command
  283. else:
  284. man_title = "borg-" + command.replace(" ", "-")
  285. print("building man page", man_title + "(1)", file=sys.stderr)
  286. is_intermediary = self.generate_level(command + " ", parser, Archiver)
  287. doc, write = self.new_doc()
  288. self.write_man_header(write, man_title, parser.description)
  289. self.write_heading(write, "SYNOPSIS")
  290. if is_intermediary:
  291. subparsers = [action for action in parser._actions if "SubParsersAction" in str(action.__class__)][0]
  292. for subcommand in subparsers.choices:
  293. write("| borg", "[common options]", command, subcommand, "...")
  294. self.see_also.setdefault(command, []).append(f"{command}-{subcommand}")
  295. else:
  296. if command == "borgfs":
  297. write(command, end="")
  298. else:
  299. write("borg", "[common options]", command, end="")
  300. self.write_usage(write, parser)
  301. write("\n")
  302. description, _, notes = parser.epilog.partition("\n.. man NOTES")
  303. if description:
  304. self.write_heading(write, "DESCRIPTION")
  305. write(description)
  306. if not is_intermediary:
  307. self.write_heading(write, "OPTIONS")
  308. write("See `borg-common(1)` for common options of Borg commands.")
  309. write()
  310. self.write_options(write, parser)
  311. self.write_examples(write, command)
  312. if notes:
  313. self.write_heading(write, "NOTES")
  314. write(notes)
  315. self.write_see_also(write, man_title)
  316. self.gen_man_page(man_title, doc.getvalue())
  317. # Generate the borg-common(1) man page with the common options.
  318. if "create" in choices:
  319. doc, write = self.new_doc()
  320. man_title = "borg-common"
  321. self.write_man_header(write, man_title, "Common options of Borg commands")
  322. common_options = [group for group in choices["create"]._action_groups if group.title == "Common options"][0]
  323. self.write_heading(write, "SYNOPSIS")
  324. self.write_options_group(write, common_options)
  325. self.write_see_also(write, man_title)
  326. self.gen_man_page(man_title, doc.getvalue())
  327. return is_subcommand
  328. def build_topic_pages(self, Archiver):
  329. for topic, text in Archiver.helptext.items():
  330. doc, write = self.new_doc()
  331. man_title = "borg-" + topic
  332. print("building man page", man_title + "(1)", file=sys.stderr)
  333. self.write_man_header(write, man_title, "Details regarding " + topic)
  334. self.write_heading(write, "DESCRIPTION")
  335. write(text)
  336. self.gen_man_page(man_title, doc.getvalue())
  337. def build_intro_page(self):
  338. doc, write = self.new_doc()
  339. man_title = "borg"
  340. print("building man page borg(1)", file=sys.stderr)
  341. with open("docs/man_intro.rst") as fd:
  342. man_intro = fd.read()
  343. self.write_man_header(write, man_title, "deduplicating and encrypting backup tool")
  344. self.gen_man_page(man_title, doc.getvalue() + man_intro)
  345. def new_doc(self):
  346. doc = io.StringIO(self.rst_prelude)
  347. doc.read()
  348. write = self.printer(doc)
  349. return doc, write
  350. def printer(self, fd):
  351. def write(*args, **kwargs):
  352. print(*args, file=fd, **kwargs)
  353. return write
  354. def write_heading(self, write, header, char="-", double_sided=False):
  355. write()
  356. if double_sided:
  357. write(char * len(header))
  358. write(header)
  359. write(char * len(header))
  360. write()
  361. def write_man_header(self, write, title, description):
  362. self.write_heading(write, title, "=", double_sided=True)
  363. self.write_heading(write, description, double_sided=True)
  364. # man page metadata
  365. write(":Author: The Borg Collective")
  366. source_date_epoch = int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
  367. write(":Date:", datetime.fromtimestamp(source_date_epoch, timezone.utc).date().isoformat())
  368. write(":Manual section: 1")
  369. write(":Manual group: borg backup tool")
  370. write()
  371. def write_examples(self, write, command):
  372. command = command.replace(" ", "_")
  373. with open("docs/usage/%s.rst" % self.usage_group.get(command, command)) as fd:
  374. usage = fd.read()
  375. usage_include = ".. include:: %s.rst.inc" % command
  376. begin = usage.find(usage_include)
  377. end = usage.find(".. include", begin + 1)
  378. # If a command has a dedicated anchor, it will occur before the command's include.
  379. if 0 < usage.find(".. _", begin + 1) < end:
  380. end = usage.find(".. _", begin + 1)
  381. examples = usage[begin:end]
  382. examples = examples.replace(usage_include, "")
  383. examples = examples.replace("Examples\n~~~~~~~~", "")
  384. examples = examples.replace("Miscellaneous Help\n------------------", "")
  385. examples = examples.replace("``docs/misc/prune-example.txt``:", "``docs/misc/prune-example.txt``.")
  386. examples = examples.replace(".. highlight:: none\n", "") # we don't support highlight
  387. examples = re.sub("^(~+)$", lambda matches: "+" * len(matches.group(0)), examples, flags=re.MULTILINE)
  388. examples = examples.strip()
  389. if examples:
  390. self.write_heading(write, "EXAMPLES", "-")
  391. write(examples)
  392. def write_see_also(self, write, man_title):
  393. see_also = self.see_also.get(man_title.replace("borg-", ""), ())
  394. see_also = ["`borg-%s(1)`" % s for s in see_also]
  395. see_also.insert(0, "`borg-common(1)`")
  396. self.write_heading(write, "SEE ALSO")
  397. write(", ".join(see_also))
  398. def gen_man_page(self, name, rst):
  399. from docutils.writers import manpage
  400. from docutils.core import publish_string
  401. from docutils.nodes import inline
  402. from docutils.parsers.rst import roles
  403. def issue(name, rawtext, text, lineno, inliner, options={}, content=[]):
  404. return [inline(rawtext, "#" + text)], []
  405. roles.register_local_role("issue", issue)
  406. # We give the source_path so that docutils can find relative includes
  407. # as-if the document where located in the docs/ directory.
  408. man_page = publish_string(source=rst, source_path="docs/%s.rst" % name, writer=manpage.Writer())
  409. with open("docs/man/%s.1" % name, "wb") as fd:
  410. fd.write(man_page)
  411. def write_usage(self, write, parser):
  412. if any(len(o.option_strings) for o in parser._actions):
  413. write(" [options] ", end="")
  414. for option in parser._actions:
  415. if option.option_strings:
  416. continue
  417. write(format_metavar(option), end=" ")
  418. def write_options(self, write, parser):
  419. for group in parser._action_groups:
  420. if group.title == "Common options" or not group._group_actions:
  421. continue
  422. title = "arguments" if group.title == "positional arguments" else group.title
  423. self.write_heading(write, title, "+")
  424. self.write_options_group(write, group)
  425. def write_options_group(self, write, group):
  426. def is_positional_group(group):
  427. return any(not o.option_strings for o in group._group_actions)
  428. if is_positional_group(group):
  429. for option in group._group_actions:
  430. write(option.metavar)
  431. write(textwrap.indent(option.help or "", " " * 4))
  432. return
  433. opts = OrderedDict()
  434. for option in group._group_actions:
  435. if option.metavar:
  436. option_fmt = "%s " + option.metavar
  437. else:
  438. option_fmt = "%s"
  439. option_str = ", ".join(option_fmt % s for s in option.option_strings)
  440. option_desc = textwrap.dedent((option.help or "") % option.__dict__)
  441. opts[option_str] = textwrap.indent(option_desc, " " * 4)
  442. padding = len(max(opts)) + 1
  443. for option, desc in opts.items():
  444. write(option.ljust(padding), desc)
  445. def usage():
  446. print(
  447. textwrap.dedent(
  448. """
  449. Usage:
  450. python scripts/gendocs.py build_usage # build usage documentation
  451. python scripts/gendocs.py build_man # build man pages
  452. """
  453. )
  454. )
  455. def main(argv):
  456. if len(argv) < 2 or len(argv) == 2 and argv[1] in ("-h", "--help"):
  457. usage()
  458. return 0
  459. command = argv[1]
  460. if command == "build_usage":
  461. return BuildUsage().run()
  462. if command == "build_man":
  463. return BuildMan().run()
  464. usage()
  465. return 1
  466. if __name__ == "__main__":
  467. rc = main(sys.argv)
  468. sys.exit(rc)