setup.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. from glob import glob
  7. try:
  8. import multiprocessing
  9. except ImportError:
  10. multiprocessing = None
  11. from setuptools.command.build_ext import build_ext
  12. from setuptools import setup, Extension, Command
  13. from setuptools.command.sdist import sdist
  14. try:
  15. from Cython.Build import cythonize
  16. except ImportError:
  17. cythonize = None
  18. sys.path += [os.path.dirname(__file__)]
  19. import setup_docs
  20. is_win32 = sys.platform.startswith("win32")
  21. is_openbsd = sys.platform.startswith("openbsd")
  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/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 Cython. Install Cython or use a released version.")
  71. def rm(file):
  72. try:
  73. os.unlink(file)
  74. print("rm", file)
  75. except FileNotFoundError:
  76. pass
  77. class Clean(Command):
  78. user_options = []
  79. def initialize_options(self):
  80. pass
  81. def finalize_options(self):
  82. pass
  83. def run(self):
  84. for source in cython_sources:
  85. genc = source.replace(".pyx", ".c")
  86. rm(genc)
  87. compiled_glob = source.replace(".pyx", ".cpython*")
  88. for compiled in sorted(glob(compiled_glob)):
  89. rm(compiled)
  90. cmdclass = {
  91. "build_ext": build_ext,
  92. "build_usage": setup_docs.build_usage,
  93. "build_man": setup_docs.build_man,
  94. "sdist": Sdist,
  95. "clean2": Clean,
  96. }
  97. ext_modules = []
  98. if not on_rtd:
  99. def members_appended(*ds):
  100. result = defaultdict(list)
  101. for d in ds:
  102. for k, v in d.items():
  103. assert isinstance(v, list)
  104. result[k].extend(v)
  105. return result
  106. try:
  107. import pkgconfig as pc
  108. except ImportError:
  109. print("Warning: can not import pkgconfig python package.")
  110. pc = None
  111. def lib_ext_kwargs(pc, prefix_env_var, lib_name, lib_pkg_name, pc_version, lib_subdir="lib"):
  112. system_prefix = os.environ.get(prefix_env_var)
  113. if system_prefix:
  114. print(f"Detected and preferring {lib_pkg_name} [via {prefix_env_var}]")
  115. return dict(
  116. include_dirs=[os.path.join(system_prefix, "include")],
  117. library_dirs=[os.path.join(system_prefix, lib_subdir)],
  118. libraries=[lib_name],
  119. )
  120. if pc and pc.installed(lib_pkg_name, pc_version):
  121. print(f"Detected and preferring {lib_pkg_name} [via pkg-config]")
  122. return pc.parse(lib_pkg_name)
  123. raise Exception(
  124. f"Could not find {lib_name} lib/headers, please set {prefix_env_var} "
  125. f"or ensure {lib_pkg_name}.pc is in PKG_CONFIG_PATH."
  126. )
  127. crypto_extra_objects = []
  128. if is_win32:
  129. crypto_ext_lib = lib_ext_kwargs(pc, "BORG_OPENSSL_PREFIX", "libcrypto", "libcrypto", ">=1.1.1", lib_subdir="")
  130. elif is_openbsd:
  131. # Use openssl (not libressl) because we need AES-OCB via EVP api. Link
  132. # it statically to avoid conflicting with shared libcrypto from the base
  133. # OS pulled in via dependencies.
  134. crypto_ext_lib = {"include_dirs": ["/usr/local/include/eopenssl30"]}
  135. crypto_extra_objects += ["/usr/local/lib/eopenssl30/libcrypto.a"]
  136. else:
  137. crypto_ext_lib = lib_ext_kwargs(pc, "BORG_OPENSSL_PREFIX", "crypto", "libcrypto", ">=1.1.1")
  138. crypto_ext_kwargs = members_appended(
  139. dict(sources=[crypto_ll_source]),
  140. crypto_ext_lib,
  141. dict(extra_compile_args=cflags),
  142. dict(extra_objects=crypto_extra_objects),
  143. )
  144. compress_ext_kwargs = members_appended(
  145. dict(sources=[compress_source]),
  146. lib_ext_kwargs(pc, "BORG_LIBLZ4_PREFIX", "lz4", "liblz4", ">= 1.7.0"),
  147. lib_ext_kwargs(pc, "BORG_LIBZSTD_PREFIX", "zstd", "libzstd", ">= 1.3.0"),
  148. dict(extra_compile_args=cflags),
  149. )
  150. checksums_ext_kwargs = members_appended(
  151. dict(sources=[checksums_source]),
  152. lib_ext_kwargs(pc, "BORG_LIBXXHASH_PREFIX", "xxhash", "libxxhash", ">= 0.7.3"),
  153. dict(extra_compile_args=cflags),
  154. )
  155. if sys.platform == "linux":
  156. linux_ext_kwargs = members_appended(
  157. dict(sources=[platform_linux_source]),
  158. lib_ext_kwargs(pc, "BORG_LIBACL_PREFIX", "acl", "libacl", ">=2.3.1"),
  159. dict(extra_compile_args=cflags),
  160. )
  161. else:
  162. linux_ext_kwargs = members_appended(
  163. dict(sources=[platform_linux_source], libraries=["acl"], extra_compile_args=cflags)
  164. )
  165. # note: _chunker.c and _hashindex.c are relatively complex/large pieces of handwritten C code,
  166. # thus we undef NDEBUG for them, so the compiled code will contain and execute assert().
  167. ext_modules += [
  168. Extension("borg.crypto.low_level", **crypto_ext_kwargs),
  169. Extension("borg.compress", **compress_ext_kwargs),
  170. Extension("borg.hashindex", [hashindex_source], extra_compile_args=cflags, undef_macros=["NDEBUG"]),
  171. Extension("borg.item", [item_source], extra_compile_args=cflags),
  172. Extension("borg.chunker", [chunker_source], extra_compile_args=cflags, undef_macros=["NDEBUG"]),
  173. Extension("borg.checksums", **checksums_ext_kwargs),
  174. ]
  175. posix_ext = Extension("borg.platform.posix", [platform_posix_source], extra_compile_args=cflags)
  176. linux_ext = Extension("borg.platform.linux", **linux_ext_kwargs)
  177. syncfilerange_ext = Extension(
  178. "borg.platform.syncfilerange", [platform_syncfilerange_source], extra_compile_args=cflags
  179. )
  180. freebsd_ext = Extension("borg.platform.freebsd", [platform_freebsd_source], extra_compile_args=cflags)
  181. darwin_ext = Extension("borg.platform.darwin", [platform_darwin_source], extra_compile_args=cflags)
  182. windows_ext = Extension("borg.platform.windows", [platform_windows_source], extra_compile_args=cflags)
  183. if not is_win32:
  184. ext_modules.append(posix_ext)
  185. else:
  186. ext_modules.append(windows_ext)
  187. if sys.platform == "linux":
  188. ext_modules.append(linux_ext)
  189. ext_modules.append(syncfilerange_ext)
  190. elif sys.platform.startswith("freebsd"):
  191. ext_modules.append(freebsd_ext)
  192. elif sys.platform == "darwin":
  193. ext_modules.append(darwin_ext)
  194. # sometimes there's no need to cythonize
  195. # this breaks chained commands like 'clean sdist'
  196. cythonizing = (
  197. len(sys.argv) > 1
  198. and sys.argv[1] not in (("clean", "clean2", "egg_info", "--help-commands", "--version"))
  199. and "--help" not in sys.argv[1:]
  200. )
  201. if cythonize and cythonizing:
  202. # 3str is the default in Cython3 and we do not support older Cython releases.
  203. # we only set this to avoid the related FutureWarning from Cython3.
  204. cython_opts = dict(compiler_directives={"language_level": "3str"})
  205. if not is_win32:
  206. # compile .pyx extensions to .c in parallel, does not work on windows
  207. cython_opts["nthreads"] = cpu_threads
  208. # generate C code from Cython for ALL supported platforms, so we have them in the sdist.
  209. # the sdist does not require Cython at install time, so we need all as C.
  210. cythonize([posix_ext, linux_ext, syncfilerange_ext, freebsd_ext, darwin_ext, windows_ext], **cython_opts)
  211. # generate C code from Cython for THIS platform (and for all platform-independent Cython parts).
  212. ext_modules = cythonize(ext_modules, **cython_opts)
  213. def long_desc_from_readme():
  214. with open("README.rst") as fd:
  215. long_description = fd.read()
  216. # remove header, but have one \n before first headline
  217. start = long_description.find("What is BorgBackup?")
  218. assert start >= 0
  219. long_description = "\n" + long_description[start:]
  220. # remove badges
  221. long_description = re.compile(r"^\.\. start-badges.*^\.\. end-badges", re.M | re.S).sub("", long_description)
  222. # remove unknown directives
  223. long_description = re.compile(r"^\.\. highlight:: \w+$", re.M).sub("", long_description)
  224. return long_description
  225. setup(cmdclass=cmdclass, ext_modules=ext_modules, long_description=long_desc_from_readme())