make.py 22 KB

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