setup.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # -*- encoding: utf-8 *-*
  2. import os
  3. import re
  4. import sys
  5. from glob import glob
  6. from distutils.command.build import build
  7. from distutils.core import Command
  8. import textwrap
  9. min_python = (3, 4)
  10. my_python = sys.version_info
  11. if my_python < min_python:
  12. print("Borg requires Python %d.%d or later" % min_python)
  13. sys.exit(1)
  14. # Are we building on ReadTheDocs?
  15. on_rtd = os.environ.get('READTHEDOCS')
  16. # msgpack pure python data corruption was fixed in 0.4.6.
  17. # Also, we might use some rather recent API features.
  18. install_requires = ['msgpack-python>=0.4.6', ]
  19. # note for package maintainers: if you package borgbackup for distribution,
  20. # please add llfuse as a *requirement* on all platforms that have a working
  21. # llfuse package. "borg mount" needs llfuse to work.
  22. # if you do not have llfuse, do not require it, most of borgbackup will work.
  23. extras_require = {
  24. # llfuse 0.40 (tested, proven, ok), needs FUSE version >= 2.8.0
  25. # llfuse 0.41 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  26. # llfuse 0.41.1 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  27. # llfuse 0.42 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  28. # llfuse 1.0 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  29. # llfuse 1.1.1 (tested shortly, looks ok), needs FUSE version >= 2.8.0
  30. # llfuse 2.0 will break API
  31. 'fuse': ['llfuse<2.0', ],
  32. }
  33. if sys.platform.startswith('freebsd'):
  34. # llfuse was frequently broken / did not build on freebsd
  35. # llfuse 0.41.1, 1.1 are ok
  36. extras_require['fuse'] = ['llfuse <2.0, !=0.42.*, !=0.43, !=1.0', ]
  37. from setuptools import setup, find_packages, Extension
  38. from setuptools.command.sdist import sdist
  39. compress_source = 'src/borg/compress.pyx'
  40. crypto_source = 'src/borg/crypto.pyx'
  41. chunker_source = 'src/borg/chunker.pyx'
  42. hashindex_source = 'src/borg/hashindex.pyx'
  43. item_source = 'src/borg/item.pyx'
  44. crc32_source = 'src/borg/crc32.pyx'
  45. platform_posix_source = 'src/borg/platform/posix.pyx'
  46. platform_linux_source = 'src/borg/platform/linux.pyx'
  47. platform_darwin_source = 'src/borg/platform/darwin.pyx'
  48. platform_freebsd_source = 'src/borg/platform/freebsd.pyx'
  49. cython_sources = [
  50. compress_source,
  51. crypto_source,
  52. chunker_source,
  53. hashindex_source,
  54. item_source,
  55. crc32_source,
  56. platform_posix_source,
  57. platform_linux_source,
  58. platform_freebsd_source,
  59. platform_darwin_source,
  60. ]
  61. try:
  62. from Cython.Distutils import build_ext
  63. import Cython.Compiler.Main as cython_compiler
  64. class Sdist(sdist):
  65. def __init__(self, *args, **kwargs):
  66. for src in cython_sources:
  67. cython_compiler.compile(src, cython_compiler.default_options)
  68. super().__init__(*args, **kwargs)
  69. def make_distribution(self):
  70. self.filelist.extend([
  71. 'src/borg/compress.c',
  72. 'src/borg/crypto.c',
  73. 'src/borg/chunker.c', 'src/borg/_chunker.c',
  74. 'src/borg/hashindex.c', 'src/borg/_hashindex.c',
  75. 'src/borg/item.c',
  76. 'src/borg/crc32.c',
  77. 'src/borg/_crc32/crc32.c', 'src/borg/_crc32/clmul.c', 'src/borg/_crc32/slice_by_8.c',
  78. 'src/borg/platform/posix.c',
  79. 'src/borg/platform/linux.c',
  80. 'src/borg/platform/freebsd.c',
  81. 'src/borg/platform/darwin.c',
  82. ])
  83. super().make_distribution()
  84. except ImportError:
  85. class Sdist(sdist):
  86. def __init__(self, *args, **kwargs):
  87. raise Exception('Cython is required to run sdist')
  88. compress_source = compress_source.replace('.pyx', '.c')
  89. crypto_source = crypto_source.replace('.pyx', '.c')
  90. chunker_source = chunker_source.replace('.pyx', '.c')
  91. hashindex_source = hashindex_source.replace('.pyx', '.c')
  92. item_source = item_source.replace('.pyx', '.c')
  93. crc32_source = crc32_source.replace('.pyx', '.c')
  94. platform_posix_source = platform_posix_source.replace('.pyx', '.c')
  95. platform_linux_source = platform_linux_source.replace('.pyx', '.c')
  96. platform_freebsd_source = platform_freebsd_source.replace('.pyx', '.c')
  97. platform_darwin_source = platform_darwin_source.replace('.pyx', '.c')
  98. from distutils.command.build_ext import build_ext
  99. if not on_rtd and not all(os.path.exists(path) for path in [
  100. compress_source, crypto_source, chunker_source, hashindex_source, item_source, crc32_source,
  101. platform_posix_source, platform_linux_source, platform_freebsd_source, platform_darwin_source]):
  102. raise ImportError('The GIT version of Borg needs Cython. Install Cython or use a released version.')
  103. def detect_openssl(prefixes):
  104. for prefix in prefixes:
  105. filename = os.path.join(prefix, 'include', 'openssl', 'evp.h')
  106. if os.path.exists(filename):
  107. with open(filename, 'r') as fd:
  108. if 'PKCS5_PBKDF2_HMAC(' in fd.read():
  109. return prefix
  110. def detect_lz4(prefixes):
  111. for prefix in prefixes:
  112. filename = os.path.join(prefix, 'include', 'lz4.h')
  113. if os.path.exists(filename):
  114. with open(filename, 'r') as fd:
  115. if 'LZ4_decompress_safe' in fd.read():
  116. return prefix
  117. def detect_libb2(prefixes):
  118. for prefix in prefixes:
  119. filename = os.path.join(prefix, 'include', 'blake2.h')
  120. if os.path.exists(filename):
  121. with open(filename, 'r') as fd:
  122. if 'blake2b_init' in fd.read():
  123. return prefix
  124. include_dirs = []
  125. library_dirs = []
  126. define_macros = []
  127. crypto_libraries = ['crypto']
  128. possible_openssl_prefixes = ['/usr', '/usr/local', '/usr/local/opt/openssl', '/usr/local/ssl', '/usr/local/openssl',
  129. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  130. if os.environ.get('BORG_OPENSSL_PREFIX'):
  131. possible_openssl_prefixes.insert(0, os.environ.get('BORG_OPENSSL_PREFIX'))
  132. ssl_prefix = detect_openssl(possible_openssl_prefixes)
  133. if not ssl_prefix:
  134. raise Exception('Unable to find OpenSSL >= 1.0 headers. (Looked here: {})'.format(', '.join(possible_openssl_prefixes)))
  135. include_dirs.append(os.path.join(ssl_prefix, 'include'))
  136. library_dirs.append(os.path.join(ssl_prefix, 'lib'))
  137. possible_lz4_prefixes = ['/usr', '/usr/local', '/usr/local/opt/lz4', '/usr/local/lz4',
  138. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  139. if os.environ.get('BORG_LZ4_PREFIX'):
  140. possible_lz4_prefixes.insert(0, os.environ.get('BORG_LZ4_PREFIX'))
  141. lz4_prefix = detect_lz4(possible_lz4_prefixes)
  142. if lz4_prefix:
  143. include_dirs.append(os.path.join(lz4_prefix, 'include'))
  144. library_dirs.append(os.path.join(lz4_prefix, 'lib'))
  145. elif not on_rtd:
  146. raise Exception('Unable to find LZ4 headers. (Looked here: {})'.format(', '.join(possible_lz4_prefixes)))
  147. possible_libb2_prefixes = ['/usr', '/usr/local', '/usr/local/opt/libb2', '/usr/local/libb2',
  148. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  149. if os.environ.get('BORG_LIBB2_PREFIX'):
  150. possible_libb2_prefixes.insert(0, os.environ.get('BORG_LIBB2_PREFIX'))
  151. libb2_prefix = detect_libb2(possible_libb2_prefixes)
  152. if libb2_prefix:
  153. print('Detected and preferring libb2 over bundled BLAKE2')
  154. include_dirs.append(os.path.join(libb2_prefix, 'include'))
  155. library_dirs.append(os.path.join(libb2_prefix, 'lib'))
  156. crypto_libraries.append('b2')
  157. define_macros.append(('BORG_USE_LIBB2', 'YES'))
  158. with open('README.rst', 'r') as fd:
  159. long_description = fd.read()
  160. # remove badges
  161. long_description = re.compile(r'^\.\. start-badges.*^\.\. end-badges', re.M | re.S).sub('', long_description)
  162. # remove |substitutions|
  163. long_description = re.compile(r'\|screencast\|').sub('', long_description)
  164. # remove unknown directives
  165. long_description = re.compile(r'^\.\. highlight:: \w+$', re.M).sub('', long_description)
  166. class build_usage(Command):
  167. description = "generate usage for each command"
  168. user_options = [
  169. ('output=', 'O', 'output directory'),
  170. ]
  171. def initialize_options(self):
  172. pass
  173. def finalize_options(self):
  174. pass
  175. def run(self):
  176. print('generating usage docs')
  177. if not os.path.exists('docs/usage'):
  178. os.mkdir('docs/usage')
  179. # allows us to build docs without the C modules fully loaded during help generation
  180. from borg.archiver import Archiver
  181. parser = Archiver(prog='borg').parser
  182. self.generate_level("", parser, Archiver)
  183. def generate_level(self, prefix, parser, Archiver):
  184. is_subcommand = False
  185. choices = {}
  186. for action in parser._actions:
  187. if action.choices is not None and 'SubParsersAction' in str(action.__class__):
  188. is_subcommand = True
  189. for cmd, parser in action.choices.items():
  190. choices[prefix + cmd] = parser
  191. if prefix and not choices:
  192. return
  193. print('found commands: %s' % list(choices.keys()))
  194. for command, parser in sorted(choices.items()):
  195. if command.startswith('debug'):
  196. print('skipping', command)
  197. continue
  198. print('generating help for %s' % command)
  199. if self.generate_level(command + " ", parser, Archiver):
  200. continue
  201. with open('docs/usage/%s.rst.inc' % command.replace(" ", "_"), 'w') as doc:
  202. doc.write(".. IMPORTANT: this file is auto-generated from borg's built-in help, do not edit!\n\n")
  203. if command == 'help':
  204. for topic in Archiver.helptext:
  205. params = {"topic": topic,
  206. "underline": '~' * len('borg help ' + topic)}
  207. doc.write(".. _borg_{topic}:\n\n".format(**params))
  208. doc.write("borg help {topic}\n{underline}\n\n".format(**params))
  209. doc.write(Archiver.helptext[topic])
  210. else:
  211. params = {"command": command,
  212. "command_": command.replace(' ', '_'),
  213. "underline": '-' * len('borg ' + command)}
  214. doc.write(".. _borg_{command_}:\n\n".format(**params))
  215. doc.write("borg {command}\n{underline}\n::\n\n borg {command}".format(**params))
  216. self.write_usage(parser, doc)
  217. epilog = parser.epilog
  218. parser.epilog = None
  219. self.write_options(parser, doc)
  220. doc.write("\n\nDescription\n~~~~~~~~~~~\n")
  221. doc.write(epilog)
  222. if 'create' in choices:
  223. common_options = [group for group in choices['create']._action_groups if group.title == 'Common options'][0]
  224. with open('docs/usage/common-options.rst.inc', 'w') as doc:
  225. self.write_options_group(common_options, doc, False)
  226. return is_subcommand
  227. def write_usage(self, parser, fp):
  228. if any(len(o.option_strings) for o in parser._actions):
  229. fp.write(' <options>')
  230. for option in parser._actions:
  231. if option.option_strings:
  232. continue
  233. fp.write(' ' + option.metavar)
  234. def write_options(self, parser, fp):
  235. for group in parser._action_groups:
  236. if group.title == 'Common options':
  237. fp.write('\n\n`Common options`_\n')
  238. fp.write(' |')
  239. else:
  240. self.write_options_group(group, fp)
  241. def write_options_group(self, group, fp, with_title=True):
  242. def is_positional_group(group):
  243. return any(not o.option_strings for o in group._group_actions)
  244. def get_help(option):
  245. text = textwrap.dedent((option.help or '') % option.__dict__)
  246. return '\n'.join('| ' + line for line in text.splitlines())
  247. def shipout(text):
  248. fp.write(textwrap.indent('\n'.join(text), ' ' * 4))
  249. if not group._group_actions:
  250. return
  251. if with_title:
  252. fp.write('\n\n')
  253. fp.write(group.title + '\n')
  254. text = []
  255. if is_positional_group(group):
  256. for option in group._group_actions:
  257. text.append(option.metavar)
  258. text.append(textwrap.indent(option.help or '', ' ' * 4))
  259. shipout(text)
  260. return
  261. options = []
  262. for option in group._group_actions:
  263. if option.metavar:
  264. option_fmt = '``%%s %s``' % option.metavar
  265. else:
  266. option_fmt = '``%s``'
  267. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  268. options.append((option_str, option))
  269. for option_str, option in options:
  270. help = textwrap.indent(get_help(option), ' ' * 4)
  271. text.append(option_str)
  272. text.append(help)
  273. shipout(text)
  274. class build_api(Command):
  275. description = "generate a basic api.rst file based on the modules available"
  276. user_options = [
  277. ('output=', 'O', 'output directory'),
  278. ]
  279. def initialize_options(self):
  280. pass
  281. def finalize_options(self):
  282. pass
  283. def run(self):
  284. print("auto-generating API documentation")
  285. with open("docs/api.rst", "w") as doc:
  286. doc.write("""
  287. API Documentation
  288. =================
  289. """)
  290. for mod in glob('src/borg/*.py') + glob('src/borg/*.pyx'):
  291. print("examining module %s" % mod)
  292. mod = mod.replace('.pyx', '').replace('.py', '').replace('/', '.')
  293. if "._" not in mod:
  294. doc.write("""
  295. .. automodule:: %s
  296. :members:
  297. :undoc-members:
  298. """ % mod)
  299. cmdclass = {
  300. 'build_ext': build_ext,
  301. 'build_api': build_api,
  302. 'build_usage': build_usage,
  303. 'sdist': Sdist
  304. }
  305. ext_modules = []
  306. if not on_rtd:
  307. ext_modules += [
  308. Extension('borg.compress', [compress_source], libraries=['lz4'], include_dirs=include_dirs, library_dirs=library_dirs, define_macros=define_macros),
  309. Extension('borg.crypto', [crypto_source], libraries=crypto_libraries, include_dirs=include_dirs, library_dirs=library_dirs, define_macros=define_macros),
  310. Extension('borg.chunker', [chunker_source]),
  311. Extension('borg.hashindex', [hashindex_source]),
  312. Extension('borg.item', [item_source]),
  313. Extension('borg.crc32', [crc32_source]),
  314. ]
  315. if not sys.platform.startswith(('win32', )):
  316. ext_modules.append(Extension('borg.platform.posix', [platform_posix_source]))
  317. if sys.platform == 'linux':
  318. ext_modules.append(Extension('borg.platform.linux', [platform_linux_source], libraries=['acl']))
  319. elif sys.platform.startswith('freebsd'):
  320. ext_modules.append(Extension('borg.platform.freebsd', [platform_freebsd_source]))
  321. elif sys.platform == 'darwin':
  322. ext_modules.append(Extension('borg.platform.darwin', [platform_darwin_source]))
  323. setup(
  324. name='borgbackup',
  325. use_scm_version={
  326. 'write_to': 'src/borg/_version.py',
  327. },
  328. author='The Borg Collective (see AUTHORS file)',
  329. author_email='borgbackup@python.org',
  330. url='https://borgbackup.readthedocs.io/',
  331. description='Deduplicated, encrypted, authenticated and compressed backups',
  332. long_description=long_description,
  333. license='BSD',
  334. platforms=['Linux', 'MacOS X', 'FreeBSD', 'OpenBSD', 'NetBSD', ],
  335. classifiers=[
  336. 'Development Status :: 4 - Beta',
  337. 'Environment :: Console',
  338. 'Intended Audience :: System Administrators',
  339. 'License :: OSI Approved :: BSD License',
  340. 'Operating System :: POSIX :: BSD :: FreeBSD',
  341. 'Operating System :: POSIX :: BSD :: OpenBSD',
  342. 'Operating System :: POSIX :: BSD :: NetBSD',
  343. 'Operating System :: MacOS :: MacOS X',
  344. 'Operating System :: POSIX :: Linux',
  345. 'Programming Language :: Python',
  346. 'Programming Language :: Python :: 3',
  347. 'Programming Language :: Python :: 3.4',
  348. 'Programming Language :: Python :: 3.5',
  349. 'Programming Language :: Python :: 3.6',
  350. 'Topic :: Security :: Cryptography',
  351. 'Topic :: System :: Archiving :: Backup',
  352. ],
  353. packages=find_packages('src'),
  354. package_dir={'': 'src'},
  355. include_package_data=True,
  356. zip_safe=False,
  357. entry_points={
  358. 'console_scripts': [
  359. 'borg = borg.archiver:main',
  360. 'borgfs = borg.archiver:main',
  361. ]
  362. },
  363. cmdclass=cmdclass,
  364. ext_modules=ext_modules,
  365. setup_requires=['setuptools_scm>=1.7'],
  366. install_requires=install_requires,
  367. extras_require=extras_require,
  368. )