make.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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", "rcreate"),
  223. "recreate": ("patterns", "placeholders", "compression"),
  224. "list": ("info", "diff", "prune", "patterns", "rlist"),
  225. "info": ("list", "diff", "rinfo"),
  226. "rcreate": ("rdelete", "rlist", "check", "benchmark-cpu", "key-import", "key-export", "key-change-passphrase"),
  227. "key-import": ("key-export",),
  228. "key-export": ("key-import",),
  229. "mount": ("umount", "extract"), # Would be cooler if these two were on the same page
  230. "umount": ("mount",),
  231. "extract": ("mount",),
  232. "delete": ("compact", "rdelete"),
  233. "prune": ("compact",),
  234. }
  235. rst_prelude = textwrap.dedent(
  236. """
  237. .. role:: ref(title)
  238. .. |project_name| replace:: Borg
  239. """
  240. )
  241. usage_group = {
  242. "break-lock": "lock",
  243. "with-lock": "lock",
  244. "key_change-passphrase": "key",
  245. "key_change-location": "key",
  246. "key_export": "key",
  247. "key_import": "key",
  248. "export-tar": "tar",
  249. "import-tar": "tar",
  250. "benchmark_crud": "benchmark",
  251. "benchmark_cpu": "benchmark",
  252. "umount": "mount",
  253. }
  254. def run(self):
  255. print("building man pages (in docs/man)", file=sys.stderr)
  256. import borg
  257. borg.doc_mode = "build_man"
  258. os.makedirs("docs/man", exist_ok=True)
  259. # allows us to build docs without the C modules fully loaded during help generation
  260. from borg.archiver import Archiver
  261. parser = Archiver(prog="borg").build_parser()
  262. borgfs_parser = Archiver(prog="borgfs").build_parser()
  263. self.generate_level("", parser, Archiver, {"borgfs": borgfs_parser})
  264. self.build_topic_pages(Archiver)
  265. self.build_intro_page()
  266. return 0
  267. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  268. is_subcommand = False
  269. choices = {}
  270. for action in parser._actions:
  271. if action.choices is not None and "SubParsersAction" in str(action.__class__):
  272. is_subcommand = True
  273. for cmd, parser in action.choices.items():
  274. choices[prefix + cmd] = parser
  275. if extra_choices is not None:
  276. choices.update(extra_choices)
  277. if prefix and not choices:
  278. return
  279. for command, parser in sorted(choices.items()):
  280. if command.startswith("debug") or command == "help":
  281. continue
  282. if command == "borgfs":
  283. man_title = command
  284. else:
  285. man_title = "borg-" + command.replace(" ", "-")
  286. print("building man page", man_title + "(1)", file=sys.stderr)
  287. is_intermediary = self.generate_level(command + " ", parser, Archiver)
  288. doc, write = self.new_doc()
  289. self.write_man_header(write, man_title, parser.description)
  290. self.write_heading(write, "SYNOPSIS")
  291. if is_intermediary:
  292. subparsers = [action for action in parser._actions if "SubParsersAction" in str(action.__class__)][0]
  293. for subcommand in subparsers.choices:
  294. write("| borg", "[common options]", command, subcommand, "...")
  295. self.see_also.setdefault(command, []).append(f"{command}-{subcommand}")
  296. else:
  297. if command == "borgfs":
  298. write(command, end="")
  299. else:
  300. write("borg", "[common options]", command, end="")
  301. self.write_usage(write, parser)
  302. write("\n")
  303. description, _, notes = parser.epilog.partition("\n.. man NOTES")
  304. if description:
  305. self.write_heading(write, "DESCRIPTION")
  306. write(description)
  307. if not is_intermediary:
  308. self.write_heading(write, "OPTIONS")
  309. write("See `borg-common(1)` for common options of Borg commands.")
  310. write()
  311. self.write_options(write, parser)
  312. self.write_examples(write, command)
  313. if notes:
  314. self.write_heading(write, "NOTES")
  315. write(notes)
  316. self.write_see_also(write, man_title)
  317. self.gen_man_page(man_title, doc.getvalue())
  318. # Generate the borg-common(1) man page with the common options.
  319. if "create" in choices:
  320. doc, write = self.new_doc()
  321. man_title = "borg-common"
  322. self.write_man_header(write, man_title, "Common options of Borg commands")
  323. common_options = [group for group in choices["create"]._action_groups if group.title == "Common options"][0]
  324. self.write_heading(write, "SYNOPSIS")
  325. self.write_options_group(write, common_options)
  326. self.write_see_also(write, man_title)
  327. self.gen_man_page(man_title, doc.getvalue())
  328. return is_subcommand
  329. def build_topic_pages(self, Archiver):
  330. for topic, text in Archiver.helptext.items():
  331. doc, write = self.new_doc()
  332. man_title = "borg-" + topic
  333. print("building man page", man_title + "(1)", file=sys.stderr)
  334. self.write_man_header(write, man_title, "Details regarding " + topic)
  335. self.write_heading(write, "DESCRIPTION")
  336. write(text)
  337. self.gen_man_page(man_title, doc.getvalue())
  338. def build_intro_page(self):
  339. doc, write = self.new_doc()
  340. man_title = "borg"
  341. print("building man page borg(1)", file=sys.stderr)
  342. with open("docs/man_intro.rst") as fd:
  343. man_intro = fd.read()
  344. self.write_man_header(write, man_title, "deduplicating and encrypting backup tool")
  345. self.gen_man_page(man_title, doc.getvalue() + man_intro)
  346. def new_doc(self):
  347. doc = io.StringIO(self.rst_prelude)
  348. doc.read()
  349. write = self.printer(doc)
  350. return doc, write
  351. def printer(self, fd):
  352. def write(*args, **kwargs):
  353. print(*args, file=fd, **kwargs)
  354. return write
  355. def write_heading(self, write, header, char="-", double_sided=False):
  356. write()
  357. if double_sided:
  358. write(char * len(header))
  359. write(header)
  360. write(char * len(header))
  361. write()
  362. def write_man_header(self, write, title, description):
  363. self.write_heading(write, title, "=", double_sided=True)
  364. self.write_heading(write, description, double_sided=True)
  365. # man page metadata
  366. write(":Author: The Borg Collective")
  367. source_date_epoch = int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
  368. write(":Date:", datetime.fromtimestamp(source_date_epoch, timezone.utc).date().isoformat())
  369. write(":Manual section: 1")
  370. write(":Manual group: borg backup tool")
  371. write()
  372. def write_examples(self, write, command):
  373. command = command.replace(" ", "_")
  374. with open("docs/usage/%s.rst" % self.usage_group.get(command, command)) as fd:
  375. usage = fd.read()
  376. usage_include = ".. include:: %s.rst.inc" % command
  377. begin = usage.find(usage_include)
  378. end = usage.find(".. include", begin + 1)
  379. # If a command has a dedicated anchor, it will occur before the command's include.
  380. if 0 < usage.find(".. _", begin + 1) < end:
  381. end = usage.find(".. _", begin + 1)
  382. examples = usage[begin:end]
  383. examples = examples.replace(usage_include, "")
  384. examples = examples.replace("Examples\n~~~~~~~~", "")
  385. examples = examples.replace("Miscellaneous Help\n------------------", "")
  386. examples = examples.replace("``docs/misc/prune-example.txt``:", "``docs/misc/prune-example.txt``.")
  387. examples = examples.replace(".. highlight:: none\n", "") # we don't support highlight
  388. examples = re.sub("^(~+)$", lambda matches: "+" * len(matches.group(0)), examples, flags=re.MULTILINE)
  389. examples = examples.strip()
  390. if examples:
  391. self.write_heading(write, "EXAMPLES", "-")
  392. write(examples)
  393. def write_see_also(self, write, man_title):
  394. see_also = self.see_also.get(man_title.replace("borg-", ""), ())
  395. see_also = ["`borg-%s(1)`" % s for s in see_also]
  396. see_also.insert(0, "`borg-common(1)`")
  397. self.write_heading(write, "SEE ALSO")
  398. write(", ".join(see_also))
  399. def gen_man_page(self, name, rst):
  400. from docutils.writers import manpage
  401. from docutils.core import publish_string
  402. from docutils.nodes import inline
  403. from docutils.parsers.rst import roles
  404. def issue(name, rawtext, text, lineno, inliner, options={}, content=[]):
  405. return [inline(rawtext, "#" + text)], []
  406. roles.register_local_role("issue", issue)
  407. # We give the source_path so that docutils can find relative includes
  408. # as-if the document where located in the docs/ directory.
  409. man_page = publish_string(source=rst, source_path="docs/%s.rst" % name, writer=manpage.Writer())
  410. with open("docs/man/%s.1" % name, "wb") as fd:
  411. fd.write(man_page)
  412. def write_usage(self, write, parser):
  413. if any(len(o.option_strings) for o in parser._actions):
  414. write(" [options] ", end="")
  415. for option in parser._actions:
  416. if option.option_strings:
  417. continue
  418. write(format_metavar(option), end=" ")
  419. def write_options(self, write, parser):
  420. for group in parser._action_groups:
  421. if group.title == "Common options" or not group._group_actions:
  422. continue
  423. title = "arguments" if group.title == "positional arguments" else group.title
  424. self.write_heading(write, title, "+")
  425. self.write_options_group(write, group)
  426. def write_options_group(self, write, group):
  427. def is_positional_group(group):
  428. return any(not o.option_strings for o in group._group_actions)
  429. if is_positional_group(group):
  430. for option in group._group_actions:
  431. write(option.metavar)
  432. write(textwrap.indent(option.help or "", " " * 4))
  433. return
  434. opts = OrderedDict()
  435. for option in group._group_actions:
  436. if option.metavar:
  437. option_fmt = "%s " + option.metavar
  438. else:
  439. option_fmt = "%s"
  440. option_str = ", ".join(option_fmt % s for s in option.option_strings)
  441. option_desc = textwrap.dedent((option.help or "") % option.__dict__)
  442. opts[option_str] = textwrap.indent(option_desc, " " * 4)
  443. padding = len(max(opts)) + 1
  444. for option, desc in opts.items():
  445. write(option.ljust(padding), desc)
  446. cython_sources = """
  447. src/borg/compress.pyx
  448. src/borg/crypto/low_level.pyx
  449. src/borg/chunker.pyx
  450. src/borg/hashindex.pyx
  451. src/borg/item.pyx
  452. src/borg/checksums.pyx
  453. src/borg/platform/posix.pyx
  454. src/borg/platform/linux.pyx
  455. src/borg/platform/syncfilerange.pyx
  456. src/borg/platform/darwin.pyx
  457. src/borg/platform/freebsd.pyx
  458. src/borg/platform/windows.pyx
  459. """.strip().splitlines()
  460. def rm(file):
  461. try:
  462. os.unlink(file)
  463. except FileNotFoundError:
  464. return False
  465. else:
  466. return True
  467. class Clean:
  468. def run(self):
  469. for source in cython_sources:
  470. genc = source.replace(".pyx", ".c")
  471. rm(genc)
  472. compiled_glob = source.replace(".pyx", ".cpython*")
  473. for compiled in sorted(glob.glob(compiled_glob)):
  474. rm(compiled)
  475. return 0
  476. def usage():
  477. print(
  478. textwrap.dedent(
  479. """
  480. Usage:
  481. python scripts/make.py clean # clean workdir (remove generated files)
  482. python scripts/make.py build_usage # build usage documentation
  483. python scripts/make.py build_man # build man pages
  484. """
  485. )
  486. )
  487. def main(argv):
  488. if len(argv) < 2 or len(argv) == 2 and argv[1] in ("-h", "--help"):
  489. usage()
  490. return 0
  491. command = argv[1]
  492. if command == "clean":
  493. return Clean().run()
  494. if command == "build_usage":
  495. return BuildUsage().run()
  496. if command == "build_man":
  497. return BuildMan().run()
  498. usage()
  499. return 1
  500. if __name__ == "__main__":
  501. rc = main(sys.argv)
  502. sys.exit(rc)