setup.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # borgbackup - main setup code (see also setup.cfg and other setup_*.py files)
  2. import os
  3. import sys
  4. from collections import defaultdict
  5. from glob import glob
  6. try:
  7. import multiprocessing
  8. except ImportError:
  9. multiprocessing = None
  10. from setuptools.command.build_ext import build_ext
  11. from setuptools import setup, find_packages, Extension, Command
  12. from setuptools.command.sdist import sdist
  13. try:
  14. from Cython.Build import cythonize
  15. except ImportError:
  16. cythonize = None
  17. sys.path += [os.path.dirname(__file__)]
  18. import setup_docs
  19. is_win32 = sys.platform.startswith('win32')
  20. # Number of threads to use for cythonize, not used on windows
  21. cpu_threads = multiprocessing.cpu_count() if multiprocessing and multiprocessing.get_start_method() != 'spawn' else None
  22. # How the build process finds the system libs:
  23. #
  24. # 1. if BORG_{LIBXXX,OPENSSL}_PREFIX is set, it will use headers and libs from there.
  25. # 2. if not and pkg-config can locate the lib, the lib located by
  26. # pkg-config will be used. We use the pkg-config tool via the pkgconfig
  27. # python package, which must be installed before invoking setup.py.
  28. # if pkgconfig is not installed, this step is skipped.
  29. # 3. otherwise raise a fatal error.
  30. # Are we building on ReadTheDocs?
  31. on_rtd = os.environ.get('READTHEDOCS')
  32. # Extra cflags for all extensions, usually just warnings we want to explicitly enable
  33. cflags = [
  34. '-Wall',
  35. '-Wextra',
  36. '-Wpointer-arith',
  37. ]
  38. compress_source = 'src/borg/compress.pyx'
  39. crypto_ll_source = 'src/borg/crypto/low_level.pyx'
  40. crypto_helpers = 'src/borg/crypto/_crypto_helpers.c'
  41. chunker_source = 'src/borg/chunker.pyx'
  42. hashindex_source = 'src/borg/hashindex.pyx'
  43. item_source = 'src/borg/item.pyx'
  44. checksums_source = 'src/borg/checksums.pyx'
  45. platform_posix_source = 'src/borg/platform/posix.pyx'
  46. platform_linux_source = 'src/borg/platform/linux.pyx'
  47. platform_syncfilerange_source = 'src/borg/platform/syncfilerange.pyx'
  48. platform_darwin_source = 'src/borg/platform/darwin.pyx'
  49. platform_freebsd_source = 'src/borg/platform/freebsd.pyx'
  50. platform_windows_source = 'src/borg/platform/windows.pyx'
  51. cython_sources = [
  52. compress_source,
  53. crypto_ll_source,
  54. chunker_source,
  55. hashindex_source,
  56. item_source,
  57. checksums_source,
  58. platform_posix_source,
  59. platform_linux_source,
  60. platform_syncfilerange_source,
  61. platform_freebsd_source,
  62. platform_darwin_source,
  63. platform_windows_source,
  64. ]
  65. if cythonize:
  66. Sdist = sdist
  67. else:
  68. class Sdist(sdist):
  69. def __init__(self, *args, **kwargs):
  70. raise Exception('Cython is required to run sdist')
  71. cython_c_files = [fn.replace('.pyx', '.c') for fn in cython_sources]
  72. if not on_rtd and not all(os.path.exists(path) for path in cython_c_files):
  73. raise ImportError('The GIT version of Borg needs Cython. Install Cython or use a released version.')
  74. def rm(file):
  75. try:
  76. os.unlink(file)
  77. print('rm', file)
  78. except FileNotFoundError:
  79. pass
  80. class Clean(Command):
  81. user_options = []
  82. def initialize_options(self):
  83. pass
  84. def finalize_options(self):
  85. pass
  86. def run(self):
  87. for source in cython_sources:
  88. genc = source.replace('.pyx', '.c')
  89. rm(genc)
  90. compiled_glob = source.replace('.pyx', '.cpython*')
  91. for compiled in sorted(glob(compiled_glob)):
  92. rm(compiled)
  93. cmdclass = {
  94. 'build_ext': build_ext,
  95. 'build_usage': setup_docs.build_usage,
  96. 'build_man': setup_docs.build_man,
  97. 'sdist': Sdist,
  98. 'clean2': Clean,
  99. }
  100. ext_modules = []
  101. if not on_rtd:
  102. def members_appended(*ds):
  103. result = defaultdict(list)
  104. for d in ds:
  105. for k, v in d.items():
  106. assert isinstance(v, list)
  107. result[k].extend(v)
  108. return result
  109. try:
  110. import pkgconfig as pc
  111. except ImportError:
  112. print('Warning: can not import pkgconfig python package.')
  113. pc = None
  114. def lib_ext_kwargs(pc, prefix_env_var, lib_name, lib_pkg_name, pc_version, lib_subdir='lib'):
  115. system_prefix = os.environ.get(prefix_env_var)
  116. if system_prefix:
  117. print(f"Detected and preferring {lib_pkg_name} [via {prefix_env_var}]")
  118. return dict(include_dirs=[os.path.join(system_prefix, 'include')],
  119. library_dirs=[os.path.join(system_prefix, lib_subdir)],
  120. libraries=[lib_name])
  121. if pc and pc.installed(lib_pkg_name, pc_version):
  122. print(f"Detected and preferring {lib_pkg_name} [via pkg-config]")
  123. return pc.parse(lib_pkg_name)
  124. raise Exception(
  125. f"Could not find {lib_name} lib/headers, please set {prefix_env_var} "
  126. f"or ensure {lib_pkg_name}.pc is in PKG_CONFIG_PATH."
  127. )
  128. if is_win32:
  129. crypto_ext_lib = lib_ext_kwargs(
  130. pc, 'BORG_OPENSSL_PREFIX', 'libcrypto', 'libcrypto', '>=1.1.1', lib_subdir='')
  131. else:
  132. crypto_ext_lib = lib_ext_kwargs(
  133. pc, 'BORG_OPENSSL_PREFIX', 'crypto', 'libcrypto', '>=1.1.1')
  134. crypto_ext_kwargs = members_appended(
  135. dict(sources=[crypto_ll_source, crypto_helpers]),
  136. crypto_ext_lib,
  137. dict(extra_compile_args=cflags),
  138. )
  139. compress_ext_kwargs = members_appended(
  140. dict(sources=[compress_source]),
  141. lib_ext_kwargs(pc, 'BORG_LIBLZ4_PREFIX', 'lz4', 'liblz4', '>= 1.7.0'),
  142. lib_ext_kwargs(pc, 'BORG_LIBZSTD_PREFIX', 'zstd', 'libzstd', '>= 1.3.0'),
  143. dict(extra_compile_args=cflags),
  144. )
  145. checksums_ext_kwargs = members_appended(
  146. dict(sources=[checksums_source]),
  147. lib_ext_kwargs(pc, 'BORG_LIBXXHASH_PREFIX', 'xxhash', 'libxxhash', '>= 0.7.3'),
  148. lib_ext_kwargs(pc, 'BORG_LIBDEFLATE_PREFIX', 'deflate', 'libdeflate', '>= 1.5'),
  149. dict(extra_compile_args=cflags),
  150. )
  151. ext_modules += [
  152. Extension('borg.crypto.low_level', **crypto_ext_kwargs),
  153. Extension('borg.compress', **compress_ext_kwargs),
  154. Extension('borg.hashindex', [hashindex_source], extra_compile_args=cflags),
  155. Extension('borg.item', [item_source], extra_compile_args=cflags),
  156. Extension('borg.chunker', [chunker_source], extra_compile_args=cflags),
  157. Extension('borg.checksums', **checksums_ext_kwargs),
  158. ]
  159. posix_ext = Extension('borg.platform.posix', [platform_posix_source], extra_compile_args=cflags)
  160. linux_ext = Extension('borg.platform.linux', [platform_linux_source], libraries=['acl'], extra_compile_args=cflags)
  161. syncfilerange_ext = Extension('borg.platform.syncfilerange', [platform_syncfilerange_source], extra_compile_args=cflags)
  162. freebsd_ext = Extension('borg.platform.freebsd', [platform_freebsd_source], extra_compile_args=cflags)
  163. darwin_ext = Extension('borg.platform.darwin', [platform_darwin_source], extra_compile_args=cflags)
  164. windows_ext = Extension('borg.platform.windows', [platform_windows_source], extra_compile_args=cflags)
  165. if not is_win32:
  166. ext_modules.append(posix_ext)
  167. else:
  168. ext_modules.append(windows_ext)
  169. if sys.platform == 'linux':
  170. ext_modules.append(linux_ext)
  171. ext_modules.append(syncfilerange_ext)
  172. elif sys.platform.startswith('freebsd'):
  173. ext_modules.append(freebsd_ext)
  174. elif sys.platform == 'darwin':
  175. ext_modules.append(darwin_ext)
  176. # sometimes there's no need to cythonize
  177. # this breaks chained commands like 'clean sdist'
  178. cythonizing = len(sys.argv) > 1 and sys.argv[1] not in (
  179. ('clean', 'clean2', 'egg_info', '--help-commands', '--version')) and '--help' not in sys.argv[1:]
  180. if cythonize and cythonizing:
  181. cython_opts = dict(
  182. # default language_level will be '3str' starting from Cython 3.0.0,
  183. # but old cython versions (< 0.29) do not know that, thus we use 3 for now.
  184. compiler_directives={'language_level': 3},
  185. )
  186. if not is_win32:
  187. # compile .pyx extensions to .c in parallel, does not work on windows
  188. cython_opts['nthreads'] = cpu_threads
  189. # generate C code from Cython for ALL supported platforms, so we have them in the sdist.
  190. # the sdist does not require Cython at install time, so we need all as C.
  191. cythonize([posix_ext, linux_ext, syncfilerange_ext, freebsd_ext, darwin_ext, windows_ext], **cython_opts)
  192. # generate C code from Cython for THIS platform (and for all platform-independent Cython parts).
  193. ext_modules = cythonize(ext_modules, **cython_opts)
  194. setup(
  195. cmdclass=cmdclass,
  196. ext_modules=ext_modules,
  197. long_description=setup_docs.long_desc_from_readme()
  198. )