setup_docs.py 22 KB

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