setup.py 12 KB

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