setup.py 33 KB

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