setup.py 16 KB

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