setup.py 8.9 KB

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