setup.py 33 KB

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