make.py 21 KB

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