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