setup.py 9.2 KB

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