setup.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. # -*- encoding: utf-8 *-*
  2. import os
  3. import io
  4. import re
  5. import sys
  6. from collections import OrderedDict
  7. from datetime import datetime
  8. from glob import glob
  9. from distutils.command.build import build
  10. from distutils.core import Command
  11. import textwrap
  12. import setup_lz4
  13. import setup_zstd
  14. import setup_b2
  15. # True: use the shared liblz4 (>= 1.7.0 / r129) from the system, False: use the bundled lz4 code
  16. prefer_system_liblz4 = True
  17. # True: use the shared libzstd (>= 1.3.0) from the system, False: use the bundled zstd code
  18. prefer_system_libzstd = False
  19. # True: use the shared libb2 from the system, False: use the bundled blake2 code
  20. prefer_system_libb2 = True
  21. min_python = (3, 4)
  22. my_python = sys.version_info
  23. if my_python < min_python:
  24. print("Borg requires Python %d.%d or later" % min_python)
  25. sys.exit(1)
  26. # Are we building on ReadTheDocs?
  27. on_rtd = os.environ.get('READTHEDOCS')
  28. install_requires = [
  29. # we are rather picky about msgpack versions, because a good working msgpack is
  30. # very important for borg, see https://github.com/borgbackup/borg/issues/3753
  31. # best versions seem to be 0.4.6, 0.4.7, 0.4.8 and 0.5.6:
  32. 'msgpack-python >=0.4.6, <=0.5.6, !=0.5.0, !=0.5.1, !=0.5.2, !=0.5.3, !=0.5.4, !=0.5.5',
  33. # if you can't satisfy the above requirement, these are versions that might
  34. # also work ok, IF you make sure to use the COMPILED version of msgpack-python,
  35. # NOT the PURE PYTHON fallback implementation: ==0.5.1, ==0.5.4
  36. # using any other version is not supported by borg development, feel free to
  37. # do it on your own risk (and after own testing).
  38. ]
  39. # note for package maintainers: if you package borgbackup for distribution,
  40. # please add llfuse as a *requirement* on all platforms that have a working
  41. # llfuse package. "borg mount" needs llfuse to work.
  42. # if you do not have llfuse, do not require it, most of borgbackup will work.
  43. extras_require = {
  44. # llfuse 0.40 (tested, proven, ok), needs FUSE version >= 2.8.0
  45. # llfuse 0.41 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  46. # llfuse 0.41.1 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  47. # llfuse 0.42 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  48. # llfuse 1.0 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  49. # llfuse 1.1.1 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  50. # llfuse 1.2 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  51. # llfuse 1.3 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  52. # llfuse 2.0 will break API
  53. 'fuse': ['llfuse<2.0', ],
  54. }
  55. if sys.platform.startswith('freebsd'):
  56. # llfuse was frequently broken / did not build on freebsd
  57. # llfuse 0.41.1, 1.1 are ok
  58. extras_require['fuse'] = ['llfuse <2.0, !=0.42.*, !=0.43, !=1.0', ]
  59. if my_python >= (3, 7):
  60. extras_require['fuse'][0] += ', >=1.3.4'
  61. from setuptools import setup, find_packages, Extension
  62. from setuptools.command.sdist import sdist
  63. from distutils.command.clean import clean
  64. compress_source = 'src/borg/compress.pyx'
  65. crypto_ll_source = 'src/borg/crypto/low_level.pyx'
  66. chunker_source = 'src/borg/chunker.pyx'
  67. hashindex_source = 'src/borg/hashindex.pyx'
  68. item_source = 'src/borg/item.pyx'
  69. checksums_source = 'src/borg/algorithms/checksums.pyx'
  70. platform_posix_source = 'src/borg/platform/posix.pyx'
  71. platform_linux_source = 'src/borg/platform/linux.pyx'
  72. platform_darwin_source = 'src/borg/platform/darwin.pyx'
  73. platform_freebsd_source = 'src/borg/platform/freebsd.pyx'
  74. cython_sources = [
  75. compress_source,
  76. crypto_ll_source,
  77. chunker_source,
  78. hashindex_source,
  79. item_source,
  80. checksums_source,
  81. platform_posix_source,
  82. platform_linux_source,
  83. platform_freebsd_source,
  84. platform_darwin_source,
  85. ]
  86. try:
  87. from Cython.Distutils import build_ext
  88. import Cython.Compiler.Main as cython_compiler
  89. class Sdist(sdist):
  90. def __init__(self, *args, **kwargs):
  91. for src in cython_sources:
  92. cython_compiler.compile(src, cython_compiler.default_options)
  93. super().__init__(*args, **kwargs)
  94. def make_distribution(self):
  95. self.filelist.extend([
  96. 'src/borg/compress.c',
  97. 'src/borg/crypto/low_level.c',
  98. 'src/borg/chunker.c', 'src/borg/_chunker.c',
  99. 'src/borg/hashindex.c', 'src/borg/_hashindex.c',
  100. 'src/borg/cache_sync/cache_sync.c', 'src/borg/cache_sync/sysdep.h', 'src/borg/cache_sync/unpack.h',
  101. 'src/borg/cache_sync/unpack_define.h', 'src/borg/cache_sync/unpack_template.h',
  102. 'src/borg/item.c',
  103. 'src/borg/algorithms/checksums.c',
  104. 'src/borg/algorithms/crc32_dispatch.c', 'src/borg/algorithms/crc32_clmul.c', 'src/borg/algorithms/crc32_slice_by_8.c',
  105. 'src/borg/algorithms/xxh64/xxhash.h', 'src/borg/algorithms/xxh64/xxhash.c',
  106. 'src/borg/platform/posix.c',
  107. 'src/borg/platform/linux.c',
  108. 'src/borg/platform/freebsd.c',
  109. 'src/borg/platform/darwin.c',
  110. ])
  111. super().make_distribution()
  112. except ImportError:
  113. class Sdist(sdist):
  114. def __init__(self, *args, **kwargs):
  115. raise Exception('Cython is required to run sdist')
  116. compress_source = compress_source.replace('.pyx', '.c')
  117. crypto_ll_source = crypto_ll_source.replace('.pyx', '.c')
  118. chunker_source = chunker_source.replace('.pyx', '.c')
  119. hashindex_source = hashindex_source.replace('.pyx', '.c')
  120. item_source = item_source.replace('.pyx', '.c')
  121. checksums_source = checksums_source.replace('.pyx', '.c')
  122. platform_posix_source = platform_posix_source.replace('.pyx', '.c')
  123. platform_linux_source = platform_linux_source.replace('.pyx', '.c')
  124. platform_freebsd_source = platform_freebsd_source.replace('.pyx', '.c')
  125. platform_darwin_source = platform_darwin_source.replace('.pyx', '.c')
  126. from distutils.command.build_ext import build_ext
  127. if not on_rtd and not all(os.path.exists(path) for path in [
  128. compress_source, crypto_ll_source, chunker_source, hashindex_source, item_source, checksums_source,
  129. platform_posix_source, platform_linux_source, platform_freebsd_source, platform_darwin_source]):
  130. raise ImportError('The GIT version of Borg needs Cython. Install Cython or use a released version.')
  131. def detect_openssl(prefixes):
  132. for prefix in prefixes:
  133. filename = os.path.join(prefix, 'include', 'openssl', 'evp.h')
  134. if os.path.exists(filename):
  135. with open(filename, 'rb') as fd:
  136. if b'PKCS5_PBKDF2_HMAC(' in fd.read():
  137. return prefix
  138. include_dirs = []
  139. library_dirs = []
  140. define_macros = []
  141. possible_openssl_prefixes = ['/usr', '/usr/local', '/usr/local/opt/openssl', '/usr/local/ssl', '/usr/local/openssl',
  142. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  143. if os.environ.get('BORG_OPENSSL_PREFIX'):
  144. possible_openssl_prefixes.insert(0, os.environ.get('BORG_OPENSSL_PREFIX'))
  145. ssl_prefix = detect_openssl(possible_openssl_prefixes)
  146. if not ssl_prefix:
  147. raise Exception('Unable to find OpenSSL >= 1.0 headers. (Looked here: {})'.format(', '.join(possible_openssl_prefixes)))
  148. include_dirs.append(os.path.join(ssl_prefix, 'include'))
  149. library_dirs.append(os.path.join(ssl_prefix, 'lib'))
  150. possible_liblz4_prefixes = ['/usr', '/usr/local', '/usr/local/opt/lz4', '/usr/local/lz4',
  151. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  152. if os.environ.get('BORG_LIBLZ4_PREFIX'):
  153. possible_liblz4_prefixes.insert(0, os.environ.get('BORG_LIBLZ4_PREFIX'))
  154. liblz4_prefix = setup_lz4.lz4_system_prefix(possible_liblz4_prefixes)
  155. if prefer_system_liblz4 and liblz4_prefix:
  156. print('Detected and preferring liblz4 over bundled LZ4')
  157. define_macros.append(('BORG_USE_LIBLZ4', 'YES'))
  158. liblz4_system = True
  159. else:
  160. liblz4_system = False
  161. possible_libb2_prefixes = ['/usr', '/usr/local', '/usr/local/opt/libb2', '/usr/local/libb2',
  162. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  163. if os.environ.get('BORG_LIBB2_PREFIX'):
  164. possible_libb2_prefixes.insert(0, os.environ.get('BORG_LIBB2_PREFIX'))
  165. libb2_prefix = setup_b2.b2_system_prefix(possible_libb2_prefixes)
  166. if prefer_system_libb2 and libb2_prefix:
  167. print('Detected and preferring libb2 over bundled BLAKE2')
  168. define_macros.append(('BORG_USE_LIBB2', 'YES'))
  169. libb2_system = True
  170. else:
  171. libb2_system = False
  172. possible_libzstd_prefixes = ['/usr', '/usr/local', '/usr/local/opt/libzstd', '/usr/local/libzstd',
  173. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  174. if os.environ.get('BORG_LIBZSTD_PREFIX'):
  175. possible_libzstd_prefixes.insert(0, os.environ.get('BORG_LIBZSTD_PREFIX'))
  176. libzstd_prefix = setup_zstd.zstd_system_prefix(possible_libzstd_prefixes)
  177. if prefer_system_libzstd and libzstd_prefix:
  178. print('Detected and preferring libzstd over bundled ZSTD')
  179. define_macros.append(('BORG_USE_LIBZSTD', 'YES'))
  180. libzstd_system = True
  181. else:
  182. libzstd_system = False
  183. with open('README.rst', 'r') as fd:
  184. long_description = fd.read()
  185. # remove badges
  186. long_description = re.compile(r'^\.\. start-badges.*^\.\. end-badges', re.M | re.S).sub('', long_description)
  187. # remove |substitutions|
  188. long_description = re.compile(r'\|screencast\|').sub('', long_description)
  189. # remove unknown directives
  190. long_description = re.compile(r'^\.\. highlight:: \w+$', re.M).sub('', long_description)
  191. def format_metavar(option):
  192. if option.nargs in ('*', '...'):
  193. return '[%s...]' % option.metavar
  194. elif option.nargs == '?':
  195. return '[%s]' % option.metavar
  196. elif option.nargs is None:
  197. return option.metavar
  198. else:
  199. raise ValueError('Can\'t format metavar %s, unknown nargs %s!' % (option.metavar, option.nargs))
  200. class build_usage(Command):
  201. description = "generate usage for each command"
  202. user_options = [
  203. ('output=', 'O', 'output directory'),
  204. ]
  205. def initialize_options(self):
  206. pass
  207. def finalize_options(self):
  208. pass
  209. def run(self):
  210. print('generating usage docs')
  211. import borg
  212. borg.doc_mode = 'build_man'
  213. if not os.path.exists('docs/usage'):
  214. os.mkdir('docs/usage')
  215. # allows us to build docs without the C modules fully loaded during help generation
  216. from borg.archiver import Archiver
  217. parser = Archiver(prog='borg').build_parser()
  218. # borgfs has a separate man page to satisfy debian's "every program from a package
  219. # must have a man page" requirement, but it doesn't need a separate HTML docs page
  220. #borgfs_parser = Archiver(prog='borgfs').build_parser()
  221. self.generate_level("", parser, Archiver)
  222. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  223. is_subcommand = False
  224. choices = {}
  225. for action in parser._actions:
  226. if action.choices is not None and 'SubParsersAction' in str(action.__class__):
  227. is_subcommand = True
  228. for cmd, parser in action.choices.items():
  229. choices[prefix + cmd] = parser
  230. if extra_choices is not None:
  231. choices.update(extra_choices)
  232. if prefix and not choices:
  233. return
  234. print('found commands: %s' % list(choices.keys()))
  235. for command, parser in sorted(choices.items()):
  236. if command.startswith('debug'):
  237. print('skipping', command)
  238. continue
  239. print('generating help for %s' % command)
  240. if self.generate_level(command + " ", parser, Archiver):
  241. continue
  242. with open('docs/usage/%s.rst.inc' % command.replace(" ", "_"), 'w') as doc:
  243. doc.write(".. IMPORTANT: this file is auto-generated from borg's built-in help, do not edit!\n\n")
  244. if command == 'help':
  245. for topic in Archiver.helptext:
  246. params = {"topic": topic,
  247. "underline": '~' * len('borg help ' + topic)}
  248. doc.write(".. _borg_{topic}:\n\n".format(**params))
  249. doc.write("borg help {topic}\n{underline}\n\n".format(**params))
  250. doc.write(Archiver.helptext[topic])
  251. else:
  252. params = {"command": command,
  253. "command_": command.replace(' ', '_'),
  254. "underline": '-' * len('borg ' + command)}
  255. doc.write(".. _borg_{command_}:\n\n".format(**params))
  256. doc.write("borg {command}\n{underline}\n.. code-block:: none\n\n borg [common options] {command}".format(**params))
  257. self.write_usage(parser, doc)
  258. epilog = parser.epilog
  259. parser.epilog = None
  260. self.write_options(parser, doc)
  261. doc.write("\n\nDescription\n~~~~~~~~~~~\n")
  262. doc.write(epilog)
  263. if 'create' in choices:
  264. common_options = [group for group in choices['create']._action_groups if group.title == 'Common options'][0]
  265. with open('docs/usage/common-options.rst.inc', 'w') as doc:
  266. self.write_options_group(common_options, doc, False, base_indent=0)
  267. return is_subcommand
  268. def write_usage(self, parser, fp):
  269. if any(len(o.option_strings) for o in parser._actions):
  270. fp.write(' [options]')
  271. for option in parser._actions:
  272. if option.option_strings:
  273. continue
  274. fp.write(' ' + format_metavar(option))
  275. fp.write('\n\n')
  276. def write_options(self, parser, fp):
  277. def is_positional_group(group):
  278. return any(not o.option_strings for o in group._group_actions)
  279. # HTML output:
  280. # A table using some column-spans
  281. def html_write(s):
  282. for line in s.splitlines():
  283. fp.write(' ' + line + '\n')
  284. rows = []
  285. for group in parser._action_groups:
  286. if group.title == 'Common options':
  287. # (no of columns used, columns, ...)
  288. rows.append((1, '.. class:: borg-common-opt-ref\n\n:ref:`common_options`'))
  289. else:
  290. if not group._group_actions:
  291. continue
  292. group_header = '**%s**' % group.title
  293. if group.description:
  294. group_header += ' — ' + group.description
  295. rows.append((1, group_header))
  296. if is_positional_group(group):
  297. for option in group._group_actions:
  298. rows.append((3, '', '``%s``' % option.metavar, option.help or ''))
  299. else:
  300. for option in group._group_actions:
  301. if option.metavar:
  302. option_fmt = '``%s ' + option.metavar + '``'
  303. else:
  304. option_fmt = '``%s``'
  305. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  306. option_desc = textwrap.dedent((option.help or '') % option.__dict__)
  307. rows.append((3, '', option_str, option_desc))
  308. fp.write('.. only:: html\n\n')
  309. table = io.StringIO()
  310. table.write('.. class:: borg-options-table\n\n')
  311. self.rows_to_table(rows, table.write)
  312. fp.write(textwrap.indent(table.getvalue(), ' ' * 4))
  313. # LaTeX output:
  314. # Regular rST option lists (irregular column widths)
  315. latex_options = io.StringIO()
  316. for group in parser._action_groups:
  317. if group.title == 'Common options':
  318. latex_options.write('\n\n:ref:`common_options`\n')
  319. latex_options.write(' |')
  320. else:
  321. self.write_options_group(group, latex_options)
  322. fp.write('\n.. only:: latex\n\n')
  323. fp.write(textwrap.indent(latex_options.getvalue(), ' ' * 4))
  324. def rows_to_table(self, rows, write):
  325. def write_row_separator():
  326. write('+')
  327. for column_width in column_widths:
  328. write('-' * (column_width + 1))
  329. write('+')
  330. write('\n')
  331. # Find column count and width
  332. column_count = max(columns for columns, *_ in rows)
  333. column_widths = [0] * column_count
  334. for columns, *cells in rows:
  335. for i in range(columns):
  336. # "+ 1" because we want a space between the cell contents and the delimiting "|" in the output
  337. column_widths[i] = max(column_widths[i], len(cells[i]) + 1)
  338. for columns, *original_cells in rows:
  339. write_row_separator()
  340. # If a cell contains newlines, then the row must be split up in individual rows
  341. # where each cell contains no newline.
  342. rowspanning_cells = []
  343. original_cells = list(original_cells)
  344. while any('\n' in cell for cell in original_cells):
  345. cell_bloc = []
  346. for i, cell in enumerate(original_cells):
  347. pre, _, original_cells[i] = cell.partition('\n')
  348. cell_bloc.append(pre)
  349. rowspanning_cells.append(cell_bloc)
  350. rowspanning_cells.append(original_cells)
  351. for cells in rowspanning_cells:
  352. for i, column_width in enumerate(column_widths):
  353. if i < columns:
  354. write('| ')
  355. write(cells[i].ljust(column_width))
  356. else:
  357. write(' ')
  358. write(''.ljust(column_width))
  359. write('|\n')
  360. write_row_separator()
  361. # This bit of JavaScript kills the <colgroup> that is invariably inserted by docutils,
  362. # but does absolutely no good here. It sets bogus column widths which cannot be overridden
  363. # with CSS alone.
  364. # Since this is HTML-only output, it would be possible to just generate a <table> directly,
  365. # but then we'd lose rST formatting.
  366. write(textwrap.dedent("""
  367. .. raw:: html
  368. <script type='text/javascript'>
  369. $(document).ready(function () {
  370. $('.borg-options-table colgroup').remove();
  371. })
  372. </script>
  373. """))
  374. def write_options_group(self, group, fp, with_title=True, base_indent=4):
  375. def is_positional_group(group):
  376. return any(not o.option_strings for o in group._group_actions)
  377. indent = ' ' * base_indent
  378. if is_positional_group(group):
  379. for option in group._group_actions:
  380. fp.write(option.metavar + '\n')
  381. fp.write(textwrap.indent(option.help or '', ' ' * base_indent) + '\n')
  382. return
  383. if not group._group_actions:
  384. return
  385. if with_title:
  386. fp.write('\n\n')
  387. fp.write(group.title + '\n')
  388. opts = OrderedDict()
  389. for option in group._group_actions:
  390. if option.metavar:
  391. option_fmt = '%s ' + option.metavar
  392. else:
  393. option_fmt = '%s'
  394. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  395. option_desc = textwrap.dedent((option.help or '') % option.__dict__)
  396. opts[option_str] = textwrap.indent(option_desc, ' ' * 4)
  397. padding = len(max(opts)) + 1
  398. for option, desc in opts.items():
  399. fp.write(indent + option.ljust(padding) + desc + '\n')
  400. class build_man(Command):
  401. description = 'build man pages'
  402. user_options = []
  403. see_also = {
  404. 'create': ('delete', 'prune', 'check', 'patterns', 'placeholders', 'compression'),
  405. 'recreate': ('patterns', 'placeholders', 'compression'),
  406. 'list': ('info', 'diff', 'prune', 'patterns'),
  407. 'info': ('list', 'diff'),
  408. 'init': ('create', 'delete', 'check', 'list', 'key-import', 'key-export', 'key-change-passphrase'),
  409. 'key-import': ('key-export', ),
  410. 'key-export': ('key-import', ),
  411. 'mount': ('umount', 'extract'), # Would be cooler if these two were on the same page
  412. 'umount': ('mount', ),
  413. 'extract': ('mount', ),
  414. }
  415. rst_prelude = textwrap.dedent("""
  416. .. role:: ref(title)
  417. .. |project_name| replace:: Borg
  418. """)
  419. usage_group = {
  420. 'break-lock': 'lock',
  421. 'with-lock': 'lock',
  422. 'change-passphrase': 'key',
  423. 'key_change-passphrase': 'key',
  424. 'key_export': 'key',
  425. 'key_import': 'key',
  426. 'key_migrate-to-repokey': 'key',
  427. 'export-tar': 'tar',
  428. 'benchmark_crud': 'benchmark',
  429. 'umount': 'mount',
  430. }
  431. def initialize_options(self):
  432. pass
  433. def finalize_options(self):
  434. pass
  435. def run(self):
  436. print('building man pages (in docs/man)', file=sys.stderr)
  437. import borg
  438. borg.doc_mode = 'build_man'
  439. os.makedirs('docs/man', exist_ok=True)
  440. # allows us to build docs without the C modules fully loaded during help generation
  441. from borg.archiver import Archiver
  442. parser = Archiver(prog='borg').build_parser()
  443. borgfs_parser = Archiver(prog='borgfs').build_parser()
  444. self.generate_level('', parser, Archiver, {'borgfs': borgfs_parser})
  445. self.build_topic_pages(Archiver)
  446. self.build_intro_page()
  447. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  448. is_subcommand = False
  449. choices = {}
  450. for action in parser._actions:
  451. if action.choices is not None and 'SubParsersAction' in str(action.__class__):
  452. is_subcommand = True
  453. for cmd, parser in action.choices.items():
  454. choices[prefix + cmd] = parser
  455. if extra_choices is not None:
  456. choices.update(extra_choices)
  457. if prefix and not choices:
  458. return
  459. for command, parser in sorted(choices.items()):
  460. if command.startswith('debug') or command == 'help':
  461. continue
  462. if command == "borgfs":
  463. man_title = command
  464. else:
  465. man_title = 'borg-' + command.replace(' ', '-')
  466. print('building man page', man_title + '(1)', file=sys.stderr)
  467. is_intermediary = self.generate_level(command + ' ', parser, Archiver)
  468. doc, write = self.new_doc()
  469. self.write_man_header(write, man_title, parser.description)
  470. self.write_heading(write, 'SYNOPSIS')
  471. if is_intermediary:
  472. subparsers = [action for action in parser._actions if 'SubParsersAction' in str(action.__class__)][0]
  473. for subcommand in subparsers.choices:
  474. write('| borg', '[common options]', command, subcommand, '...')
  475. self.see_also.setdefault(command, []).append('%s-%s' % (command, subcommand))
  476. else:
  477. if command == "borgfs":
  478. write(command, end='')
  479. else:
  480. write('borg', '[common options]', command, end='')
  481. self.write_usage(write, parser)
  482. write('\n')
  483. description, _, notes = parser.epilog.partition('\n.. man NOTES')
  484. if description:
  485. self.write_heading(write, 'DESCRIPTION')
  486. write(description)
  487. if not is_intermediary:
  488. self.write_heading(write, 'OPTIONS')
  489. write('See `borg-common(1)` for common options of Borg commands.')
  490. write()
  491. self.write_options(write, parser)
  492. self.write_examples(write, command)
  493. if notes:
  494. self.write_heading(write, 'NOTES')
  495. write(notes)
  496. self.write_see_also(write, man_title)
  497. self.gen_man_page(man_title, doc.getvalue())
  498. # Generate the borg-common(1) man page with the common options.
  499. if 'create' in choices:
  500. doc, write = self.new_doc()
  501. man_title = 'borg-common'
  502. self.write_man_header(write, man_title, 'Common options of Borg commands')
  503. common_options = [group for group in choices['create']._action_groups if group.title == 'Common options'][0]
  504. self.write_heading(write, 'SYNOPSIS')
  505. self.write_options_group(write, common_options)
  506. self.write_see_also(write, man_title)
  507. self.gen_man_page(man_title, doc.getvalue())
  508. return is_subcommand
  509. def build_topic_pages(self, Archiver):
  510. for topic, text in Archiver.helptext.items():
  511. doc, write = self.new_doc()
  512. man_title = 'borg-' + topic
  513. print('building man page', man_title + '(1)', file=sys.stderr)
  514. self.write_man_header(write, man_title, 'Details regarding ' + topic)
  515. self.write_heading(write, 'DESCRIPTION')
  516. write(text)
  517. self.gen_man_page(man_title, doc.getvalue())
  518. def build_intro_page(self):
  519. print('building man page borg(1)', file=sys.stderr)
  520. with open('docs/man_intro.rst') as fd:
  521. man_intro = fd.read()
  522. self.gen_man_page('borg', self.rst_prelude + man_intro)
  523. def new_doc(self):
  524. doc = io.StringIO(self.rst_prelude)
  525. doc.read()
  526. write = self.printer(doc)
  527. return doc, write
  528. def printer(self, fd):
  529. def write(*args, **kwargs):
  530. print(*args, file=fd, **kwargs)
  531. return write
  532. def write_heading(self, write, header, char='-', double_sided=False):
  533. write()
  534. if double_sided:
  535. write(char * len(header))
  536. write(header)
  537. write(char * len(header))
  538. write()
  539. def write_man_header(self, write, title, description):
  540. self.write_heading(write, title, '=', double_sided=True)
  541. self.write_heading(write, description, double_sided=True)
  542. # man page metadata
  543. write(':Author: The Borg Collective')
  544. write(':Date:', datetime.utcnow().date().isoformat())
  545. write(':Manual section: 1')
  546. write(':Manual group: borg backup tool')
  547. write()
  548. def write_examples(self, write, command):
  549. command = command.replace(' ', '_')
  550. with open('docs/usage/%s.rst' % self.usage_group.get(command, command)) as fd:
  551. usage = fd.read()
  552. usage_include = '.. include:: %s.rst.inc' % command
  553. begin = usage.find(usage_include)
  554. end = usage.find('.. include', begin + 1)
  555. # If a command has a dedicated anchor, it will occur before the command's include.
  556. if 0 < usage.find('.. _', begin + 1) < end:
  557. end = usage.find('.. _', begin + 1)
  558. examples = usage[begin:end]
  559. examples = examples.replace(usage_include, '')
  560. examples = examples.replace('Examples\n~~~~~~~~', '')
  561. examples = examples.replace('Miscellaneous Help\n------------------', '')
  562. examples = examples.replace('``docs/misc/prune-example.txt``:', '``docs/misc/prune-example.txt``.')
  563. examples = examples.replace('.. highlight:: none\n', '') # we don't support highlight
  564. examples = re.sub('^(~+)$', lambda matches: '+' * len(matches.group(0)), examples, flags=re.MULTILINE)
  565. examples = examples.strip()
  566. if examples:
  567. self.write_heading(write, 'EXAMPLES', '-')
  568. write(examples)
  569. def write_see_also(self, write, man_title):
  570. see_also = self.see_also.get(man_title.replace('borg-', ''), ())
  571. see_also = ['`borg-%s(1)`' % s for s in see_also]
  572. see_also.insert(0, '`borg-common(1)`')
  573. self.write_heading(write, 'SEE ALSO')
  574. write(', '.join(see_also))
  575. def gen_man_page(self, name, rst):
  576. from docutils.writers import manpage
  577. from docutils.core import publish_string
  578. from docutils.nodes import inline
  579. from docutils.parsers.rst import roles
  580. def issue(name, rawtext, text, lineno, inliner, options={}, content=[]):
  581. return [inline(rawtext, '#' + text)], []
  582. roles.register_local_role('issue', issue)
  583. # We give the source_path so that docutils can find relative includes
  584. # as-if the document where located in the docs/ directory.
  585. man_page = publish_string(source=rst, source_path='docs/%s.rst' % name, writer=manpage.Writer())
  586. with open('docs/man/%s.1' % name, 'wb') as fd:
  587. fd.write(man_page)
  588. def write_usage(self, write, parser):
  589. if any(len(o.option_strings) for o in parser._actions):
  590. write(' [options] ', end='')
  591. for option in parser._actions:
  592. if option.option_strings:
  593. continue
  594. write(format_metavar(option), end=' ')
  595. def write_options(self, write, parser):
  596. for group in parser._action_groups:
  597. if group.title == 'Common options' or not group._group_actions:
  598. continue
  599. title = 'arguments' if group.title == 'positional arguments' else group.title
  600. self.write_heading(write, title, '+')
  601. self.write_options_group(write, group)
  602. def write_options_group(self, write, group):
  603. def is_positional_group(group):
  604. return any(not o.option_strings for o in group._group_actions)
  605. if is_positional_group(group):
  606. for option in group._group_actions:
  607. write(option.metavar)
  608. write(textwrap.indent(option.help or '', ' ' * 4))
  609. return
  610. opts = OrderedDict()
  611. for option in group._group_actions:
  612. if option.metavar:
  613. option_fmt = '%s ' + option.metavar
  614. else:
  615. option_fmt = '%s'
  616. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  617. option_desc = textwrap.dedent((option.help or '') % option.__dict__)
  618. opts[option_str] = textwrap.indent(option_desc, ' ' * 4)
  619. padding = len(max(opts)) + 1
  620. for option, desc in opts.items():
  621. write(option.ljust(padding), desc)
  622. def rm(file):
  623. try:
  624. os.unlink(file)
  625. print('rm', file)
  626. except FileNotFoundError:
  627. pass
  628. class Clean(clean):
  629. def run(self):
  630. super().run()
  631. for source in cython_sources:
  632. genc = source.replace('.pyx', '.c')
  633. rm(genc)
  634. compiled_glob = source.replace('.pyx', '.cpython*')
  635. for compiled in sorted(glob(compiled_glob)):
  636. rm(compiled)
  637. cmdclass = {
  638. 'build_ext': build_ext,
  639. 'build_usage': build_usage,
  640. 'build_man': build_man,
  641. 'sdist': Sdist,
  642. 'clean': Clean,
  643. }
  644. ext_modules = []
  645. if not on_rtd:
  646. compress_ext_kwargs = dict(sources=[compress_source], include_dirs=include_dirs, library_dirs=library_dirs,
  647. define_macros=define_macros)
  648. compress_ext_kwargs = setup_lz4.lz4_ext_kwargs(bundled_path='src/borg/algorithms/lz4',
  649. system_prefix=liblz4_prefix, system=liblz4_system,
  650. **compress_ext_kwargs)
  651. compress_ext_kwargs = setup_zstd.zstd_ext_kwargs(bundled_path='src/borg/algorithms/zstd',
  652. system_prefix=libzstd_prefix, system=libzstd_system,
  653. multithreaded=False, legacy=False, **compress_ext_kwargs)
  654. crypto_ext_kwargs = dict(sources=[crypto_ll_source], libraries=['crypto'],
  655. include_dirs=include_dirs, library_dirs=library_dirs, define_macros=define_macros)
  656. crypto_ext_kwargs = setup_b2.b2_ext_kwargs(bundled_path='src/borg/algorithms/blake2',
  657. system_prefix=libb2_prefix, system=libb2_system,
  658. **crypto_ext_kwargs)
  659. ext_modules += [
  660. Extension('borg.compress', **compress_ext_kwargs),
  661. Extension('borg.crypto.low_level', **crypto_ext_kwargs),
  662. Extension('borg.hashindex', [hashindex_source]),
  663. Extension('borg.item', [item_source]),
  664. Extension('borg.chunker', [chunker_source]),
  665. Extension('borg.algorithms.checksums', [checksums_source]),
  666. ]
  667. if not sys.platform.startswith(('win32', )):
  668. ext_modules.append(Extension('borg.platform.posix', [platform_posix_source]))
  669. if sys.platform == 'linux':
  670. ext_modules.append(Extension('borg.platform.linux', [platform_linux_source], libraries=['acl']))
  671. elif sys.platform.startswith('freebsd'):
  672. ext_modules.append(Extension('borg.platform.freebsd', [platform_freebsd_source]))
  673. elif sys.platform == 'darwin':
  674. ext_modules.append(Extension('borg.platform.darwin', [platform_darwin_source]))
  675. setup(
  676. name='borgbackup',
  677. use_scm_version={
  678. 'write_to': 'src/borg/_version.py',
  679. },
  680. author='The Borg Collective (see AUTHORS file)',
  681. author_email='borgbackup@python.org',
  682. url='https://borgbackup.readthedocs.io/',
  683. description='Deduplicated, encrypted, authenticated and compressed backups',
  684. long_description=long_description,
  685. license='BSD',
  686. platforms=['Linux', 'MacOS X', 'FreeBSD', 'OpenBSD', 'NetBSD', ],
  687. classifiers=[
  688. 'Development Status :: 4 - Beta',
  689. 'Environment :: Console',
  690. 'Intended Audience :: System Administrators',
  691. 'License :: OSI Approved :: BSD License',
  692. 'Operating System :: POSIX :: BSD :: FreeBSD',
  693. 'Operating System :: POSIX :: BSD :: OpenBSD',
  694. 'Operating System :: POSIX :: BSD :: NetBSD',
  695. 'Operating System :: MacOS :: MacOS X',
  696. 'Operating System :: POSIX :: Linux',
  697. 'Programming Language :: Python',
  698. 'Programming Language :: Python :: 3',
  699. 'Programming Language :: Python :: 3.4',
  700. 'Programming Language :: Python :: 3.5',
  701. 'Programming Language :: Python :: 3.6',
  702. 'Topic :: Security :: Cryptography',
  703. 'Topic :: System :: Archiving :: Backup',
  704. ],
  705. packages=find_packages('src'),
  706. package_dir={'': 'src'},
  707. zip_safe=False,
  708. entry_points={
  709. 'console_scripts': [
  710. 'borg = borg.archiver:main',
  711. 'borgfs = borg.archiver:main',
  712. ]
  713. },
  714. # See also the MANIFEST.in file.
  715. # We want to install all the files in the package directories...
  716. include_package_data=True,
  717. # ...except the source files which have been compiled (C extensions):
  718. exclude_package_data={
  719. '': ['*.c', '*.h', '*.pyx', ],
  720. },
  721. cmdclass=cmdclass,
  722. ext_modules=ext_modules,
  723. setup_requires=['setuptools_scm>=1.7'],
  724. install_requires=install_requires,
  725. extras_require=extras_require,
  726. )