setup.py 15 KB

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