setup_docs.py 21 KB

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