make.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. os.makedirs("docs/usage", exist_ok=True)
  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, "underline": "~" * len("borg help " + topic)}
  60. doc.write(".. _borg_{topic}:\n\n".format(**params))
  61. doc.write("borg help {topic}\n{underline}\n\n".format(**params))
  62. doc.write(Archiver.helptext[topic])
  63. else:
  64. params = {
  65. "command": command,
  66. "command_": command.replace(" ", "_"),
  67. "underline": "-" * len("borg " + command),
  68. }
  69. doc.write(".. _borg_{command_}:\n\n".format(**params))
  70. doc.write(
  71. "borg {command}\n{underline}\n.. code-block:: none\n\n borg [common options] {command}".format(
  72. **params
  73. )
  74. )
  75. self.write_usage(parser, doc)
  76. epilog = parser.epilog
  77. parser.epilog = None
  78. self.write_options(parser, doc)
  79. doc.write("\n\nDescription\n~~~~~~~~~~~\n")
  80. doc.write(epilog)
  81. if "create" in choices:
  82. common_options = [group for group in choices["create"]._action_groups if group.title == "Common options"][0]
  83. with open("docs/usage/common-options.rst.inc", "w") as doc:
  84. self.write_options_group(common_options, doc, False, base_indent=0)
  85. return is_subcommand
  86. def write_usage(self, parser, fp):
  87. if any(len(o.option_strings) for o in parser._actions):
  88. fp.write(" [options]")
  89. for option in parser._actions:
  90. if option.option_strings:
  91. continue
  92. fp.write(" " + format_metavar(option))
  93. fp.write("\n\n")
  94. def write_options(self, parser, fp):
  95. def is_positional_group(group):
  96. return any(not o.option_strings for o in group._group_actions)
  97. # HTML output:
  98. # A table using some column-spans
  99. rows = []
  100. for group in parser._action_groups:
  101. if group.title == "Common options":
  102. # (no of columns used, columns, ...)
  103. rows.append((1, ".. class:: borg-common-opt-ref\n\n:ref:`common_options`"))
  104. else:
  105. if not group._group_actions:
  106. continue
  107. group_header = "**%s**" % group.title
  108. if group.description:
  109. group_header += " — " + group.description
  110. rows.append((1, group_header))
  111. if is_positional_group(group):
  112. for option in group._group_actions:
  113. rows.append((3, "", "``%s``" % option.metavar, option.help or ""))
  114. else:
  115. for option in group._group_actions:
  116. if option.metavar:
  117. option_fmt = "``%s " + option.metavar + "``"
  118. else:
  119. option_fmt = "``%s``"
  120. option_str = ", ".join(option_fmt % s for s in option.option_strings)
  121. option_desc = textwrap.dedent((option.help or "") % option.__dict__)
  122. rows.append((3, "", option_str, option_desc))
  123. fp.write(".. only:: html\n\n")
  124. table = io.StringIO()
  125. table.write(".. class:: borg-options-table\n\n")
  126. self.rows_to_table(rows, table.write)
  127. fp.write(textwrap.indent(table.getvalue(), " " * 4))
  128. # LaTeX output:
  129. # Regular rST option lists (irregular column widths)
  130. latex_options = io.StringIO()
  131. for group in parser._action_groups:
  132. if group.title == "Common options":
  133. latex_options.write("\n\n:ref:`common_options`\n")
  134. latex_options.write(" |")
  135. else:
  136. self.write_options_group(group, latex_options)
  137. fp.write("\n.. only:: latex\n\n")
  138. fp.write(textwrap.indent(latex_options.getvalue(), " " * 4))
  139. def rows_to_table(self, rows, write):
  140. def write_row_separator():
  141. write("+")
  142. for column_width in column_widths:
  143. write("-" * (column_width + 1))
  144. write("+")
  145. write("\n")
  146. # Find column count and width
  147. column_count = max(columns for columns, *_ in rows)
  148. column_widths = [0] * column_count
  149. for columns, *cells in rows:
  150. for i in range(columns):
  151. # "+ 1" because we want a space between the cell contents and the delimiting "|" in the output
  152. column_widths[i] = max(column_widths[i], len(cells[i]) + 1)
  153. for columns, *original_cells in rows:
  154. write_row_separator()
  155. # If a cell contains newlines, then the row must be split up in individual rows
  156. # where each cell contains no newline.
  157. rowspanning_cells = []
  158. original_cells = list(original_cells)
  159. while any("\n" in cell for cell in original_cells):
  160. cell_bloc = []
  161. for i, cell in enumerate(original_cells):
  162. pre, _, original_cells[i] = cell.partition("\n")
  163. cell_bloc.append(pre)
  164. rowspanning_cells.append(cell_bloc)
  165. rowspanning_cells.append(original_cells)
  166. for cells in rowspanning_cells:
  167. for i, column_width in enumerate(column_widths):
  168. if i < columns:
  169. write("| ")
  170. write(cells[i].ljust(column_width))
  171. else:
  172. write(" ")
  173. write("".ljust(column_width))
  174. write("|\n")
  175. write_row_separator()
  176. # This bit of JavaScript kills the <colgroup> that is invariably inserted by docutils,
  177. # but does absolutely no good here. It sets bogus column widths which cannot be overridden
  178. # with CSS alone.
  179. # Since this is HTML-only output, it would be possible to just generate a <table> directly,
  180. # but then we'd lose rST formatting.
  181. write(
  182. textwrap.dedent(
  183. """
  184. .. raw:: html
  185. <script type='text/javascript'>
  186. $(document).ready(function () {
  187. $('.borg-options-table colgroup').remove();
  188. })
  189. </script>
  190. """
  191. )
  192. )
  193. def write_options_group(self, group, fp, with_title=True, base_indent=4):
  194. def is_positional_group(group):
  195. return any(not o.option_strings for o in group._group_actions)
  196. indent = " " * base_indent
  197. if is_positional_group(group):
  198. for option in group._group_actions:
  199. fp.write(option.metavar + "\n")
  200. fp.write(textwrap.indent(option.help or "", " " * base_indent) + "\n")
  201. return
  202. if not group._group_actions:
  203. return
  204. if with_title:
  205. fp.write("\n\n")
  206. fp.write(group.title + "\n")
  207. opts = OrderedDict()
  208. for option in group._group_actions:
  209. if option.metavar:
  210. option_fmt = "%s " + option.metavar
  211. else:
  212. option_fmt = "%s"
  213. option_str = ", ".join(option_fmt % s for s in option.option_strings)
  214. option_desc = textwrap.dedent((option.help or "") % option.__dict__)
  215. opts[option_str] = textwrap.indent(option_desc, " " * 4)
  216. padding = len(max(opts)) + 1
  217. for option, desc in opts.items():
  218. fp.write(indent + option.ljust(padding) + desc + "\n")
  219. class BuildMan:
  220. """build man pages"""
  221. see_also = {
  222. "create": ("delete", "prune", "check", "patterns", "placeholders", "compression", "repo-create"),
  223. "recreate": ("patterns", "placeholders", "compression"),
  224. "list": ("info", "diff", "prune", "patterns", "repo-list"),
  225. "info": ("list", "diff", "repo-info"),
  226. "repo-create": (
  227. "repo-delete",
  228. "repo-list",
  229. "check",
  230. "benchmark-cpu",
  231. "key-import",
  232. "key-export",
  233. "key-change-passphrase",
  234. ),
  235. "key-import": ("key-export",),
  236. "key-export": ("key-import",),
  237. "mount": ("umount", "extract"), # Would be cooler if these two were on the same page
  238. "umount": ("mount",),
  239. "extract": ("mount",),
  240. "delete": ("compact", "repo-delete"),
  241. "prune": ("compact",),
  242. }
  243. rst_prelude = textwrap.dedent(
  244. """
  245. .. role:: ref(title)
  246. .. |project_name| replace:: Borg
  247. """
  248. )
  249. usage_group = {
  250. "break-lock": "lock",
  251. "with-lock": "lock",
  252. "key_change-passphrase": "key",
  253. "key_change-location": "key",
  254. "key_export": "key",
  255. "key_import": "key",
  256. "export-tar": "tar",
  257. "import-tar": "tar",
  258. "benchmark_crud": "benchmark",
  259. "benchmark_cpu": "benchmark",
  260. "umount": "mount",
  261. }
  262. def run(self):
  263. print("building man pages (in docs/man)", file=sys.stderr)
  264. import borg
  265. borg.doc_mode = "build_man"
  266. os.makedirs("docs/man", exist_ok=True)
  267. # allows us to build docs without the C modules fully loaded during help generation
  268. from borg.archiver import Archiver
  269. parser = Archiver(prog="borg").build_parser()
  270. borgfs_parser = Archiver(prog="borgfs").build_parser()
  271. self.generate_level("", parser, Archiver, {"borgfs": borgfs_parser})
  272. self.build_topic_pages(Archiver)
  273. self.build_intro_page()
  274. return 0
  275. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  276. is_subcommand = False
  277. choices = {}
  278. for action in parser._actions:
  279. if action.choices is not None and "SubParsersAction" in str(action.__class__):
  280. is_subcommand = True
  281. for cmd, parser in action.choices.items():
  282. choices[prefix + cmd] = parser
  283. if extra_choices is not None:
  284. choices.update(extra_choices)
  285. if prefix and not choices:
  286. return
  287. for command, parser in sorted(choices.items()):
  288. if command.startswith("debug") or command == "help":
  289. continue
  290. if command == "borgfs":
  291. man_title = command
  292. else:
  293. man_title = "borg-" + command.replace(" ", "-")
  294. print("building man page", man_title + "(1)", file=sys.stderr)
  295. is_intermediary = self.generate_level(command + " ", parser, Archiver)
  296. doc, write = self.new_doc()
  297. self.write_man_header(write, man_title, parser.description)
  298. self.write_heading(write, "SYNOPSIS")
  299. if is_intermediary:
  300. subparsers = [action for action in parser._actions if "SubParsersAction" in str(action.__class__)][0]
  301. for subcommand in subparsers.choices:
  302. write("| borg", "[common options]", command, subcommand, "...")
  303. self.see_also.setdefault(command, []).append(f"{command}-{subcommand}")
  304. else:
  305. if command == "borgfs":
  306. write(command, end="")
  307. else:
  308. write("borg", "[common options]", command, end="")
  309. self.write_usage(write, parser)
  310. write("\n")
  311. description, _, notes = parser.epilog.partition("\n.. man NOTES")
  312. if description:
  313. self.write_heading(write, "DESCRIPTION")
  314. write(description)
  315. if not is_intermediary:
  316. self.write_heading(write, "OPTIONS")
  317. write("See `borg-common(1)` for common options of Borg commands.")
  318. write()
  319. self.write_options(write, parser)
  320. self.write_examples(write, command)
  321. if notes:
  322. self.write_heading(write, "NOTES")
  323. write(notes)
  324. self.write_see_also(write, man_title)
  325. self.gen_man_page(man_title, doc.getvalue())
  326. # Generate the borg-common(1) man page with the common options.
  327. if "create" in choices:
  328. doc, write = self.new_doc()
  329. man_title = "borg-common"
  330. self.write_man_header(write, man_title, "Common options of Borg commands")
  331. common_options = [group for group in choices["create"]._action_groups if group.title == "Common options"][0]
  332. self.write_heading(write, "SYNOPSIS")
  333. self.write_options_group(write, common_options)
  334. self.write_see_also(write, man_title)
  335. self.gen_man_page(man_title, doc.getvalue())
  336. return is_subcommand
  337. def build_topic_pages(self, Archiver):
  338. for topic, text in Archiver.helptext.items():
  339. doc, write = self.new_doc()
  340. man_title = "borg-" + topic
  341. print("building man page", man_title + "(1)", file=sys.stderr)
  342. self.write_man_header(write, man_title, "Details regarding " + topic)
  343. self.write_heading(write, "DESCRIPTION")
  344. write(text)
  345. self.gen_man_page(man_title, doc.getvalue())
  346. def build_intro_page(self):
  347. doc, write = self.new_doc()
  348. man_title = "borg"
  349. print("building man page borg(1)", file=sys.stderr)
  350. with open("docs/man_intro.rst") as fd:
  351. man_intro = fd.read()
  352. self.write_man_header(write, man_title, "deduplicating and encrypting backup tool")
  353. self.gen_man_page(man_title, doc.getvalue() + man_intro)
  354. def new_doc(self):
  355. doc = io.StringIO(self.rst_prelude)
  356. doc.read()
  357. write = self.printer(doc)
  358. return doc, write
  359. def printer(self, fd):
  360. def write(*args, **kwargs):
  361. print(*args, file=fd, **kwargs)
  362. return write
  363. def write_heading(self, write, header, char="-", double_sided=False):
  364. write()
  365. if double_sided:
  366. write(char * len(header))
  367. write(header)
  368. write(char * len(header))
  369. write()
  370. def write_man_header(self, write, title, description):
  371. self.write_heading(write, title, "=", double_sided=True)
  372. self.write_heading(write, description, double_sided=True)
  373. # man page metadata
  374. write(":Author: The Borg Collective")
  375. source_date_epoch = int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
  376. write(":Date:", datetime.fromtimestamp(source_date_epoch, timezone.utc).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)
  454. cython_sources = """
  455. src/borg/compress.pyx
  456. src/borg/crypto/low_level.pyx
  457. src/borg/chunker.pyx
  458. src/borg/hashindex.pyx
  459. src/borg/item.pyx
  460. src/borg/checksums.pyx
  461. src/borg/platform/posix.pyx
  462. src/borg/platform/linux.pyx
  463. src/borg/platform/syncfilerange.pyx
  464. src/borg/platform/darwin.pyx
  465. src/borg/platform/freebsd.pyx
  466. src/borg/platform/windows.pyx
  467. """.strip().splitlines()
  468. def rm(file):
  469. try:
  470. os.unlink(file)
  471. except FileNotFoundError:
  472. return False
  473. else:
  474. return True
  475. class Clean:
  476. def run(self):
  477. for source in cython_sources:
  478. genc = source.replace(".pyx", ".c")
  479. rm(genc)
  480. compiled_glob = source.replace(".pyx", ".cpython*")
  481. for compiled in sorted(glob.glob(compiled_glob)):
  482. rm(compiled)
  483. return 0
  484. def usage():
  485. print(
  486. textwrap.dedent(
  487. """
  488. Usage:
  489. python scripts/make.py clean # clean workdir (remove generated files)
  490. python scripts/make.py build_usage # build usage documentation
  491. python scripts/make.py build_man # build man pages
  492. """
  493. )
  494. )
  495. def main(argv):
  496. if len(argv) < 2 or len(argv) == 2 and argv[1] in ("-h", "--help"):
  497. usage()
  498. return 0
  499. command = argv[1]
  500. if command == "clean":
  501. return Clean().run()
  502. if command == "build_usage":
  503. return BuildUsage().run()
  504. if command == "build_man":
  505. return BuildMan().run()
  506. usage()
  507. return 1
  508. if __name__ == "__main__":
  509. rc = main(sys.argv)
  510. sys.exit(rc)