setup.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # borgbackup - main setup code (see also setup.cfg and other setup_*.py files)
  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. is_openbsd = sys.platform.startswith("openbsd")
  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 enable explicitly
  33. cflags = ["-Wall", "-Wextra", "-Wpointer-arith"]
  34. compress_source = "src/borg/compress.pyx"
  35. crypto_ll_source = "src/borg/crypto/low_level.pyx"
  36. chunker_source = "src/borg/chunker.pyx"
  37. hashindex_source = "src/borg/hashindex.pyx"
  38. item_source = "src/borg/item.pyx"
  39. checksums_source = "src/borg/checksums.pyx"
  40. platform_posix_source = "src/borg/platform/posix.pyx"
  41. platform_linux_source = "src/borg/platform/linux.pyx"
  42. platform_syncfilerange_source = "src/borg/platform/syncfilerange.pyx"
  43. platform_darwin_source = "src/borg/platform/darwin.pyx"
  44. platform_freebsd_source = "src/borg/platform/freebsd.pyx"
  45. platform_windows_source = "src/borg/platform/windows.pyx"
  46. cython_sources = [
  47. compress_source,
  48. crypto_ll_source,
  49. chunker_source,
  50. hashindex_source,
  51. item_source,
  52. checksums_source,
  53. platform_posix_source,
  54. platform_linux_source,
  55. platform_syncfilerange_source,
  56. platform_freebsd_source,
  57. platform_darwin_source,
  58. platform_windows_source,
  59. ]
  60. if cythonize:
  61. Sdist = sdist
  62. else:
  63. class Sdist(sdist):
  64. def __init__(self, *args, **kwargs):
  65. raise Exception("Cython is required to run sdist")
  66. cython_c_files = [fn.replace(".pyx", ".c") for fn in cython_sources]
  67. if not on_rtd and not all(os.path.exists(path) for path in cython_c_files):
  68. raise ImportError("The GIT version of Borg needs Cython. Install Cython or use a released version.")
  69. cmdclass = {"build_ext": build_ext, "sdist": Sdist}
  70. ext_modules = []
  71. if not on_rtd:
  72. def members_appended(*ds):
  73. result = defaultdict(list)
  74. for d in ds:
  75. for k, v in d.items():
  76. assert isinstance(v, list)
  77. result[k].extend(v)
  78. return result
  79. try:
  80. import pkgconfig as pc
  81. except ImportError:
  82. print("Warning: can not import pkgconfig python package.")
  83. pc = None
  84. def lib_ext_kwargs(pc, prefix_env_var, lib_name, lib_pkg_name, pc_version, lib_subdir="lib"):
  85. system_prefix = os.environ.get(prefix_env_var)
  86. if system_prefix:
  87. print(f"Detected and preferring {lib_pkg_name} [via {prefix_env_var}]")
  88. return dict(
  89. include_dirs=[os.path.join(system_prefix, "include")],
  90. library_dirs=[os.path.join(system_prefix, lib_subdir)],
  91. libraries=[lib_name],
  92. )
  93. if pc and pc.installed(lib_pkg_name, pc_version):
  94. print(f"Detected and preferring {lib_pkg_name} [via pkg-config]")
  95. return pc.parse(lib_pkg_name)
  96. raise Exception(
  97. f"Could not find {lib_name} lib/headers, please set {prefix_env_var} "
  98. f"or ensure {lib_pkg_name}.pc is in PKG_CONFIG_PATH."
  99. )
  100. crypto_extra_objects = []
  101. if is_win32:
  102. crypto_ext_lib = lib_ext_kwargs(pc, "BORG_OPENSSL_PREFIX", "libcrypto", "libcrypto", ">=1.1.1", lib_subdir="")
  103. elif is_openbsd:
  104. # Use openssl (not libressl) because we need AES-OCB via EVP api. Link
  105. # it statically to avoid conflicting with shared libcrypto from the base
  106. # OS pulled in via dependencies.
  107. crypto_ext_lib = {"include_dirs": ["/usr/local/include/eopenssl30"]}
  108. crypto_extra_objects += ["/usr/local/lib/eopenssl30/libcrypto.a"]
  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.3.1"),
  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.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())