setup_docs.py 21 KB

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