setup_docs.py 22 KB

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