setup.py 13 KB

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