setup_docs.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. 'delete': ('compact', ),
  235. 'prune': ('compact', ),
  236. }
  237. rst_prelude = textwrap.dedent("""
  238. .. role:: ref(title)
  239. .. |project_name| replace:: Borg
  240. """)
  241. usage_group = {
  242. 'break-lock': 'lock',
  243. 'with-lock': 'lock',
  244. 'key_change-passphrase': 'key',
  245. 'key_export': 'key',
  246. 'key_import': 'key',
  247. 'key_migrate-to-repokey': 'key',
  248. 'export-tar': 'tar',
  249. 'benchmark_crud': 'benchmark',
  250. 'umount': 'mount',
  251. }
  252. def initialize_options(self):
  253. pass
  254. def finalize_options(self):
  255. pass
  256. def run(self):
  257. print('building man pages (in docs/man)', file=sys.stderr)
  258. import borg
  259. borg.doc_mode = 'build_man'
  260. os.makedirs('docs/man', exist_ok=True)
  261. # allows us to build docs without the C modules fully loaded during help generation
  262. from borg.archiver import Archiver
  263. parser = Archiver(prog='borg').build_parser()
  264. borgfs_parser = Archiver(prog='borgfs').build_parser()
  265. self.generate_level('', parser, Archiver, {'borgfs': borgfs_parser})
  266. self.build_topic_pages(Archiver)
  267. self.build_intro_page()
  268. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  269. is_subcommand = False
  270. choices = {}
  271. for action in parser._actions:
  272. if action.choices is not None and 'SubParsersAction' in str(action.__class__):
  273. is_subcommand = True
  274. for cmd, parser in action.choices.items():
  275. choices[prefix + cmd] = parser
  276. if extra_choices is not None:
  277. choices.update(extra_choices)
  278. if prefix and not choices:
  279. return
  280. for command, parser in sorted(choices.items()):
  281. if command.startswith('debug') or command == 'help':
  282. continue
  283. if command == "borgfs":
  284. man_title = command
  285. else:
  286. man_title = 'borg-' + command.replace(' ', '-')
  287. print('building man page', man_title + '(1)', file=sys.stderr)
  288. is_intermediary = self.generate_level(command + ' ', parser, Archiver)
  289. doc, write = self.new_doc()
  290. self.write_man_header(write, man_title, parser.description)
  291. self.write_heading(write, 'SYNOPSIS')
  292. if is_intermediary:
  293. subparsers = [action for action in parser._actions if 'SubParsersAction' in str(action.__class__)][0]
  294. for subcommand in subparsers.choices:
  295. write('| borg', '[common options]', command, subcommand, '...')
  296. self.see_also.setdefault(command, []).append('%s-%s' % (command, subcommand))
  297. else:
  298. if command == "borgfs":
  299. write(command, end='')
  300. else:
  301. write('borg', '[common options]', command, end='')
  302. self.write_usage(write, parser)
  303. write('\n')
  304. description, _, notes = parser.epilog.partition('\n.. man NOTES')
  305. if description:
  306. self.write_heading(write, 'DESCRIPTION')
  307. write(description)
  308. if not is_intermediary:
  309. self.write_heading(write, 'OPTIONS')
  310. write('See `borg-common(1)` for common options of Borg commands.')
  311. write()
  312. self.write_options(write, parser)
  313. self.write_examples(write, command)
  314. if notes:
  315. self.write_heading(write, 'NOTES')
  316. write(notes)
  317. self.write_see_also(write, man_title)
  318. self.gen_man_page(man_title, doc.getvalue())
  319. # Generate the borg-common(1) man page with the common options.
  320. if 'create' in choices:
  321. doc, write = self.new_doc()
  322. man_title = 'borg-common'
  323. self.write_man_header(write, man_title, 'Common options of Borg commands')
  324. common_options = [group for group in choices['create']._action_groups if group.title == 'Common options'][0]
  325. self.write_heading(write, 'SYNOPSIS')
  326. self.write_options_group(write, common_options)
  327. self.write_see_also(write, man_title)
  328. self.gen_man_page(man_title, doc.getvalue())
  329. return is_subcommand
  330. def build_topic_pages(self, Archiver):
  331. for topic, text in Archiver.helptext.items():
  332. doc, write = self.new_doc()
  333. man_title = 'borg-' + topic
  334. print('building man page', man_title + '(1)', file=sys.stderr)
  335. self.write_man_header(write, man_title, 'Details regarding ' + topic)
  336. self.write_heading(write, 'DESCRIPTION')
  337. write(text)
  338. self.gen_man_page(man_title, doc.getvalue())
  339. def build_intro_page(self):
  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.gen_man_page('borg', self.rst_prelude + man_intro)
  344. def new_doc(self):
  345. doc = io.StringIO(self.rst_prelude)
  346. doc.read()
  347. write = self.printer(doc)
  348. return doc, write
  349. def printer(self, fd):
  350. def write(*args, **kwargs):
  351. print(*args, file=fd, **kwargs)
  352. return write
  353. def write_heading(self, write, header, char='-', double_sided=False):
  354. write()
  355. if double_sided:
  356. write(char * len(header))
  357. write(header)
  358. write(char * len(header))
  359. write()
  360. def write_man_header(self, write, title, description):
  361. self.write_heading(write, title, '=', double_sided=True)
  362. self.write_heading(write, description, double_sided=True)
  363. # man page metadata
  364. write(':Author: The Borg Collective')
  365. write(':Date:', datetime.utcnow().date().isoformat())
  366. write(':Manual section: 1')
  367. write(':Manual group: borg backup tool')
  368. write()
  369. def write_examples(self, write, command):
  370. command = command.replace(' ', '_')
  371. with open('docs/usage/%s.rst' % self.usage_group.get(command, command)) as fd:
  372. usage = fd.read()
  373. usage_include = '.. include:: %s.rst.inc' % command
  374. begin = usage.find(usage_include)
  375. end = usage.find('.. include', begin + 1)
  376. # If a command has a dedicated anchor, it will occur before the command's include.
  377. if 0 < usage.find('.. _', begin + 1) < end:
  378. end = usage.find('.. _', begin + 1)
  379. examples = usage[begin:end]
  380. examples = examples.replace(usage_include, '')
  381. examples = examples.replace('Examples\n~~~~~~~~', '')
  382. examples = examples.replace('Miscellaneous Help\n------------------', '')
  383. examples = examples.replace('``docs/misc/prune-example.txt``:', '``docs/misc/prune-example.txt``.')
  384. examples = examples.replace('.. highlight:: none\n', '') # we don't support highlight
  385. examples = re.sub('^(~+)$', lambda matches: '+' * len(matches.group(0)), examples, flags=re.MULTILINE)
  386. examples = examples.strip()
  387. if examples:
  388. self.write_heading(write, 'EXAMPLES', '-')
  389. write(examples)
  390. def write_see_also(self, write, man_title):
  391. see_also = self.see_also.get(man_title.replace('borg-', ''), ())
  392. see_also = ['`borg-%s(1)`' % s for s in see_also]
  393. see_also.insert(0, '`borg-common(1)`')
  394. self.write_heading(write, 'SEE ALSO')
  395. write(', '.join(see_also))
  396. def gen_man_page(self, name, rst):
  397. from docutils.writers import manpage
  398. from docutils.core import publish_string
  399. from docutils.nodes import inline
  400. from docutils.parsers.rst import roles
  401. def issue(name, rawtext, text, lineno, inliner, options={}, content=[]):
  402. return [inline(rawtext, '#' + text)], []
  403. roles.register_local_role('issue', issue)
  404. # We give the source_path so that docutils can find relative includes
  405. # as-if the document where located in the docs/ directory.
  406. man_page = publish_string(source=rst, source_path='docs/%s.rst' % name, writer=manpage.Writer())
  407. with open('docs/man/%s.1' % name, 'wb') as fd:
  408. fd.write(man_page)
  409. def write_usage(self, write, parser):
  410. if any(len(o.option_strings) for o in parser._actions):
  411. write(' [options] ', end='')
  412. for option in parser._actions:
  413. if option.option_strings:
  414. continue
  415. write(format_metavar(option), end=' ')
  416. def write_options(self, write, parser):
  417. for group in parser._action_groups:
  418. if group.title == 'Common options' or not group._group_actions:
  419. continue
  420. title = 'arguments' if group.title == 'positional arguments' else group.title
  421. self.write_heading(write, title, '+')
  422. self.write_options_group(write, group)
  423. def write_options_group(self, write, group):
  424. def is_positional_group(group):
  425. return any(not o.option_strings for o in group._group_actions)
  426. if is_positional_group(group):
  427. for option in group._group_actions:
  428. write(option.metavar)
  429. write(textwrap.indent(option.help or '', ' ' * 4))
  430. return
  431. opts = OrderedDict()
  432. for option in group._group_actions:
  433. if option.metavar:
  434. option_fmt = '%s ' + option.metavar
  435. else:
  436. option_fmt = '%s'
  437. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  438. option_desc = textwrap.dedent((option.help or '') % option.__dict__)
  439. opts[option_str] = textwrap.indent(option_desc, ' ' * 4)
  440. padding = len(max(opts)) + 1
  441. for option, desc in opts.items():
  442. write(option.ljust(padding), desc)