setup.py 32 KB

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