setup.py 16 KB

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