setup.py 33 KB

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