setup.py 32 KB

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