2
0

setup.py 13 KB

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