setup.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # borgbackup - main setup code (extension building here, rest see pyproject.toml)
  2. import os
  3. import re
  4. import sys
  5. from collections import defaultdict
  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, Extension
  12. from setuptools.command.sdist import sdist
  13. try:
  14. from Cython.Build import cythonize
  15. cythonize_import_error_msg = None
  16. except ImportError as exc:
  17. # either there is no Cython installed or there is some issue with it.
  18. cythonize = None
  19. cythonize_import_error_msg = "ImportError: " + str(exc)
  20. if "failed to map segment from shared object" in cythonize_import_error_msg:
  21. cythonize_import_error_msg += " Check if the borg build uses a +exec filesystem."
  22. sys.path += [os.path.dirname(__file__)]
  23. is_win32 = sys.platform.startswith("win32")
  24. # Number of threads to use for cythonize, not used on windows
  25. cpu_threads = multiprocessing.cpu_count() if multiprocessing and multiprocessing.get_start_method() != "spawn" else None
  26. # How the build process finds the system libs:
  27. #
  28. # 1. if BORG_{LIBXXX,OPENSSL}_PREFIX is set, it will use headers and libs from there.
  29. # 2. if not and pkg-config can locate the lib, the lib located by
  30. # pkg-config will be used. We use the pkg-config tool via the pkgconfig
  31. # python package, which must be installed before invoking setup.py.
  32. # if pkgconfig is not installed, this step is skipped.
  33. # 3. otherwise raise a fatal error.
  34. # Are we building on ReadTheDocs?
  35. on_rtd = os.environ.get("READTHEDOCS")
  36. # Extra cflags for all extensions, usually just warnings we want to enable explicitly
  37. cflags = ["-Wall", "-Wextra", "-Wpointer-arith"]
  38. compress_source = "src/borg/compress.pyx"
  39. crypto_ll_source = "src/borg/crypto/low_level.pyx"
  40. chunker_source = "src/borg/chunker.pyx"
  41. hashindex_source = "src/borg/hashindex.pyx"
  42. item_source = "src/borg/item.pyx"
  43. checksums_source = "src/borg/algorithms/checksums.pyx"
  44. platform_posix_source = "src/borg/platform/posix.pyx"
  45. platform_linux_source = "src/borg/platform/linux.pyx"
  46. platform_syncfilerange_source = "src/borg/platform/syncfilerange.pyx"
  47. platform_darwin_source = "src/borg/platform/darwin.pyx"
  48. platform_freebsd_source = "src/borg/platform/freebsd.pyx"
  49. platform_windows_source = "src/borg/platform/windows.pyx"
  50. cython_sources = [
  51. compress_source,
  52. crypto_ll_source,
  53. chunker_source,
  54. hashindex_source,
  55. item_source,
  56. checksums_source,
  57. platform_posix_source,
  58. platform_linux_source,
  59. platform_syncfilerange_source,
  60. platform_freebsd_source,
  61. platform_darwin_source,
  62. platform_windows_source,
  63. ]
  64. if cythonize:
  65. Sdist = sdist
  66. else:
  67. class Sdist(sdist):
  68. def __init__(self, *args, **kwargs):
  69. raise Exception("Cython is required to run sdist")
  70. cython_c_files = [fn.replace(".pyx", ".c") for fn in cython_sources]
  71. if not on_rtd and not all(os.path.exists(path) for path in cython_c_files):
  72. raise ImportError("The GIT version of Borg needs a working Cython. " +
  73. "Install or fix Cython or use a released borg version. " +
  74. "Importing cythonize failed with: " + cythonize_import_error_msg)
  75. cmdclass = {"build_ext": build_ext, "sdist": Sdist}
  76. ext_modules = []
  77. if not on_rtd:
  78. def members_appended(*ds):
  79. result = defaultdict(list)
  80. for d in ds:
  81. for k, v in d.items():
  82. assert isinstance(v, list)
  83. result[k].extend(v)
  84. return result
  85. try:
  86. import pkgconfig as pc
  87. except ImportError:
  88. print("Warning: can not import pkgconfig python package.")
  89. pc = None
  90. def lib_ext_kwargs(pc, prefix_env_var, lib_name, lib_pkg_name, pc_version, lib_subdir="lib"):
  91. system_prefix = os.environ.get(prefix_env_var)
  92. if system_prefix:
  93. print(f"Detected and preferring {lib_pkg_name} [via {prefix_env_var}]")
  94. return dict(
  95. include_dirs=[os.path.join(system_prefix, "include")],
  96. library_dirs=[os.path.join(system_prefix, lib_subdir)],
  97. libraries=[lib_name],
  98. )
  99. if pc and pc.installed(lib_pkg_name, pc_version):
  100. print(f"Detected and preferring {lib_pkg_name} [via pkg-config]")
  101. return pc.parse(lib_pkg_name)
  102. raise Exception(
  103. f"Could not find {lib_name} lib/headers, please set {prefix_env_var} "
  104. f"or ensure {lib_pkg_name}.pc is in PKG_CONFIG_PATH."
  105. )
  106. crypto_extra_objects = []
  107. if is_win32:
  108. crypto_ext_lib = lib_ext_kwargs(pc, "BORG_OPENSSL_PREFIX", "libcrypto", "libcrypto", ">=1.1.1", lib_subdir="")
  109. else:
  110. crypto_ext_lib = lib_ext_kwargs(pc, "BORG_OPENSSL_PREFIX", "crypto", "libcrypto", ">=1.1.1")
  111. crypto_ext_kwargs = members_appended(
  112. dict(sources=[crypto_ll_source]),
  113. crypto_ext_lib,
  114. dict(extra_compile_args=cflags),
  115. dict(extra_objects=crypto_extra_objects),
  116. )
  117. compress_ext_kwargs = members_appended(
  118. dict(sources=[compress_source]),
  119. lib_ext_kwargs(pc, "BORG_LIBLZ4_PREFIX", "lz4", "liblz4", ">= 1.7.0"),
  120. lib_ext_kwargs(pc, "BORG_LIBZSTD_PREFIX", "zstd", "libzstd", ">= 1.3.0"),
  121. dict(extra_compile_args=cflags),
  122. )
  123. checksums_ext_kwargs = members_appended(
  124. dict(sources=[checksums_source]),
  125. lib_ext_kwargs(pc, "BORG_LIBXXHASH_PREFIX", "xxhash", "libxxhash", ">= 0.7.3"),
  126. dict(extra_compile_args=cflags),
  127. )
  128. if sys.platform == "linux":
  129. linux_ext_kwargs = members_appended(
  130. dict(sources=[platform_linux_source]),
  131. lib_ext_kwargs(pc, "BORG_LIBACL_PREFIX", "acl", "libacl", ">= 2.2.47"),
  132. dict(extra_compile_args=cflags),
  133. )
  134. else:
  135. linux_ext_kwargs = members_appended(
  136. dict(sources=[platform_linux_source], libraries=["acl"], extra_compile_args=cflags)
  137. )
  138. # note: _chunker.c and _hashindex.c are relatively complex/large pieces of handwritten C code,
  139. # thus we undef NDEBUG for them, so the compiled code will contain and execute assert().
  140. ext_modules += [
  141. Extension("borg.crypto.low_level", **crypto_ext_kwargs),
  142. Extension("borg.compress", **compress_ext_kwargs),
  143. Extension("borg.hashindex", [hashindex_source], extra_compile_args=cflags, undef_macros=["NDEBUG"]),
  144. Extension("borg.item", [item_source], extra_compile_args=cflags),
  145. Extension("borg.chunker", [chunker_source], extra_compile_args=cflags, undef_macros=["NDEBUG"]),
  146. Extension("borg.algorithms.checksums", **checksums_ext_kwargs),
  147. ]
  148. posix_ext = Extension("borg.platform.posix", [platform_posix_source], extra_compile_args=cflags)
  149. linux_ext = Extension("borg.platform.linux", **linux_ext_kwargs)
  150. syncfilerange_ext = Extension(
  151. "borg.platform.syncfilerange", [platform_syncfilerange_source], extra_compile_args=cflags
  152. )
  153. freebsd_ext = Extension("borg.platform.freebsd", [platform_freebsd_source], extra_compile_args=cflags)
  154. darwin_ext = Extension("borg.platform.darwin", [platform_darwin_source], extra_compile_args=cflags)
  155. windows_ext = Extension("borg.platform.windows", [platform_windows_source], extra_compile_args=cflags)
  156. if not is_win32:
  157. ext_modules.append(posix_ext)
  158. else:
  159. ext_modules.append(windows_ext)
  160. if sys.platform == "linux":
  161. ext_modules.append(linux_ext)
  162. ext_modules.append(syncfilerange_ext)
  163. elif sys.platform.startswith("freebsd"):
  164. ext_modules.append(freebsd_ext)
  165. elif sys.platform == "darwin":
  166. ext_modules.append(darwin_ext)
  167. # sometimes there's no need to cythonize
  168. # this breaks chained commands like 'clean sdist'
  169. cythonizing = (
  170. len(sys.argv) > 1
  171. and sys.argv[1] not in (("clean", "egg_info", "--help-commands", "--version"))
  172. and "--help" not in sys.argv[1:]
  173. )
  174. if cythonize and cythonizing:
  175. # 3str is the default in Cython3 and we do not support older Cython releases.
  176. # we only set this to avoid the related FutureWarning from Cython3.
  177. cython_opts = dict(compiler_directives={"language_level": "3str"})
  178. if not is_win32:
  179. # compile .pyx extensions to .c in parallel, does not work on windows
  180. cython_opts["nthreads"] = cpu_threads
  181. # generate C code from Cython for ALL supported platforms, so we have them in the sdist.
  182. # the sdist does not require Cython at install time, so we need all as C.
  183. cythonize([posix_ext, linux_ext, syncfilerange_ext, freebsd_ext, darwin_ext, windows_ext], **cython_opts)
  184. # generate C code from Cython for THIS platform (and for all platform-independent Cython parts).
  185. ext_modules = cythonize(ext_modules, **cython_opts)
  186. def long_desc_from_readme():
  187. with open("README.rst") as fd:
  188. long_description = fd.read()
  189. # remove header, but have one \n before first headline
  190. start = long_description.find("What is BorgBackup?")
  191. assert start >= 0
  192. long_description = "\n" + long_description[start:]
  193. # remove badges
  194. long_description = re.compile(r"^\.\. start-badges.*^\.\. end-badges", re.M | re.S).sub("", long_description)
  195. # remove unknown directives
  196. long_description = re.compile(r"^\.\. highlight:: \w+$", re.M).sub("", long_description)
  197. return long_description
  198. setup(cmdclass=cmdclass, ext_modules=ext_modules, long_description=long_desc_from_readme())