setup_docs.py 21 KB

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