setup.py 13 KB

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