setup.py 12 KB

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