setup.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. 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. if command == 'help':
  151. for topic in Archiver.helptext:
  152. params = {"topic": topic,
  153. "underline": '~' * len('borg help ' + topic)}
  154. doc.write(".. _borg_{topic}:\n\n".format(**params))
  155. doc.write("borg help {topic}\n{underline}\n::\n\n".format(**params))
  156. doc.write(Archiver.helptext[topic])
  157. else:
  158. params = {"command": command,
  159. "underline": '-' * len('borg ' + command)}
  160. doc.write(".. _borg_{command}:\n\n".format(**params))
  161. doc.write("borg {command}\n{underline}\n::\n\n borg {command}".format(**params))
  162. self.write_usage(parser, doc)
  163. epilog = parser.epilog
  164. parser.epilog = None
  165. self.write_options(parser, doc)
  166. doc.write("\n\nDescription\n~~~~~~~~~~~\n")
  167. doc.write(epilog)
  168. common_options = [group for group in choices['create']._action_groups if group.title == 'Common options'][0]
  169. with open('docs/usage/common-options.rst.inc', 'w') as doc:
  170. self.write_options_group(common_options, doc, False)
  171. def write_usage(self, parser, fp):
  172. if any(len(o.option_strings) for o in parser._actions):
  173. fp.write(' <options>')
  174. for option in parser._actions:
  175. if option.option_strings:
  176. continue
  177. fp.write(' ' + option.metavar)
  178. def write_options(self, parser, fp):
  179. for group in parser._action_groups:
  180. if group.title == 'Common options':
  181. fp.write('\n\n`Common options`_\n')
  182. fp.write(' |')
  183. else:
  184. self.write_options_group(group, fp)
  185. def write_options_group(self, group, fp, with_title=True):
  186. def is_positional_group(group):
  187. return any(not o.option_strings for o in group._group_actions)
  188. def get_help(option):
  189. text = textwrap.dedent((option.help or '') % option.__dict__)
  190. return '\n'.join('| ' + line for line in text.splitlines())
  191. def shipout(text):
  192. fp.write(textwrap.indent('\n'.join(text), ' ' * 4))
  193. if not group._group_actions:
  194. return
  195. if with_title:
  196. fp.write('\n\n')
  197. fp.write(group.title + '\n')
  198. text = []
  199. if is_positional_group(group):
  200. for option in group._group_actions:
  201. text.append(option.metavar)
  202. text.append(textwrap.indent(option.help or '', ' ' * 4))
  203. shipout(text)
  204. return
  205. options = []
  206. for option in group._group_actions:
  207. if option.metavar:
  208. option_fmt = '``%%s %s``' % option.metavar
  209. else:
  210. option_fmt = '``%s``'
  211. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  212. options.append((option_str, option))
  213. for option_str, option in options:
  214. help = textwrap.indent(get_help(option), ' ' * 4)
  215. text.append(option_str)
  216. text.append(help)
  217. shipout(text)
  218. class build_api(Command):
  219. description = "generate a basic api.rst file based on the modules available"
  220. user_options = [
  221. ('output=', 'O', 'output directory'),
  222. ]
  223. def initialize_options(self):
  224. pass
  225. def finalize_options(self):
  226. pass
  227. def run(self):
  228. print("auto-generating API documentation")
  229. with open("docs/api.rst", "w") as doc:
  230. doc.write("""
  231. API Documentation
  232. =================
  233. """)
  234. for mod in glob('src/borg/*.py') + glob('src/borg/*.pyx'):
  235. print("examining module %s" % mod)
  236. mod = mod.replace('.pyx', '').replace('.py', '').replace('/', '.')
  237. if "._" not in mod:
  238. doc.write("""
  239. .. automodule:: %s
  240. :members:
  241. :undoc-members:
  242. """ % mod)
  243. cmdclass = {
  244. 'build_ext': build_ext,
  245. 'build_api': build_api,
  246. 'build_usage': build_usage,
  247. 'sdist': Sdist
  248. }
  249. ext_modules = []
  250. if not on_rtd:
  251. ext_modules += [
  252. Extension('borg.compress', [compress_source], libraries=['lz4'], include_dirs=include_dirs, library_dirs=library_dirs),
  253. Extension('borg.crypto', [crypto_source], libraries=['crypto'], include_dirs=include_dirs, library_dirs=library_dirs),
  254. Extension('borg.chunker', [chunker_source]),
  255. Extension('borg.hashindex', [hashindex_source])
  256. ]
  257. if sys.platform.startswith(('linux', 'freebsd', 'darwin')):
  258. ext_modules.append(Extension('borg.platform.posix', [platform_posix_source]))
  259. if sys.platform == 'linux':
  260. ext_modules.append(Extension('borg.platform.linux', [platform_linux_source], libraries=['acl']))
  261. elif sys.platform.startswith('freebsd'):
  262. ext_modules.append(Extension('borg.platform.freebsd', [platform_freebsd_source]))
  263. elif sys.platform == 'darwin':
  264. ext_modules.append(Extension('borg.platform.darwin', [platform_darwin_source]))
  265. setup(
  266. name='borgbackup',
  267. use_scm_version={
  268. 'write_to': 'src/borg/_version.py',
  269. },
  270. author='The Borg Collective (see AUTHORS file)',
  271. author_email='borgbackup@python.org',
  272. url='https://borgbackup.readthedocs.io/',
  273. description='Deduplicated, encrypted, authenticated and compressed backups',
  274. long_description=long_description,
  275. license='BSD',
  276. platforms=['Linux', 'MacOS X', 'FreeBSD', 'OpenBSD', 'NetBSD', ],
  277. classifiers=[
  278. 'Development Status :: 4 - Beta',
  279. 'Environment :: Console',
  280. 'Intended Audience :: System Administrators',
  281. 'License :: OSI Approved :: BSD License',
  282. 'Operating System :: POSIX :: BSD :: FreeBSD',
  283. 'Operating System :: POSIX :: BSD :: OpenBSD',
  284. 'Operating System :: POSIX :: BSD :: NetBSD',
  285. 'Operating System :: MacOS :: MacOS X',
  286. 'Operating System :: POSIX :: Linux',
  287. 'Programming Language :: Python',
  288. 'Programming Language :: Python :: 3',
  289. 'Programming Language :: Python :: 3.4',
  290. 'Programming Language :: Python :: 3.5',
  291. 'Topic :: Security :: Cryptography',
  292. 'Topic :: System :: Archiving :: Backup',
  293. ],
  294. packages=find_packages('src'),
  295. package_dir={'': 'src'},
  296. include_package_data=True,
  297. zip_safe=False,
  298. entry_points={
  299. 'console_scripts': [
  300. 'borg = borg.archiver:main',
  301. 'borgfs = borg.archiver:main',
  302. ]
  303. },
  304. cmdclass=cmdclass,
  305. ext_modules=ext_modules,
  306. setup_requires=['setuptools_scm>=1.7'],
  307. install_requires=install_requires,
  308. extras_require=extras_require,
  309. )