setup.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. # -*- encoding: utf-8 *-*
  2. import os
  3. import io
  4. import re
  5. import sys
  6. import textwrap
  7. from collections import OrderedDict
  8. from datetime import datetime
  9. from glob import glob
  10. import setup_lz4
  11. import setup_zstd
  12. import setup_b2
  13. import setup_xxhash
  14. # True: use the shared liblz4 (>= 1.7.0 / r129) from the system, False: use the bundled lz4 code
  15. prefer_system_liblz4 = True
  16. # True: use the shared libzstd (>= 1.3.0) from the system, False: use the bundled zstd code
  17. prefer_system_libzstd = True
  18. # True: use the shared libb2 from the system, False: use the bundled blake2 code
  19. prefer_system_libb2 = True
  20. # True: use the shared libxxhash (>= 0.6.5 [>= 0.7.2 on ARM]) from the system, False: use the bundled xxhash code
  21. prefer_system_libxxhash = True
  22. # prefer_system_msgpack is another option, but you need to set it in src/borg/helpers.py.
  23. min_python = (3, 5)
  24. my_python = sys.version_info
  25. if my_python < min_python:
  26. print("Borg requires Python %d.%d or later" % min_python)
  27. sys.exit(1)
  28. # Are we building on ReadTheDocs?
  29. on_rtd = os.environ.get('READTHEDOCS')
  30. install_requires = [
  31. 'packaging',
  32. ]
  33. # note for package maintainers: if you package borgbackup for distribution,
  34. # please add llfuse as a *requirement* on all platforms that have a working
  35. # llfuse package. "borg mount" needs llfuse to work.
  36. # if you do not have llfuse, do not require it, most of borgbackup will work.
  37. extras_require = {
  38. 'fuse': [
  39. # 1.3.8 is the fixed version that works on py39 AND freebsd.
  40. # if you cythonize yourself and make sure llfuse works for your
  41. # OS and python version, you can use other versions than 1.3.8, too.
  42. 'llfuse >=1.3.4', # should nowadays pull 1.3.8 or better
  43. ],
  44. }
  45. from setuptools import setup, find_packages, Extension, Command
  46. from setuptools.command.sdist import sdist
  47. # Extra cflags for all extensions, usually just warnings we want to explicitly enable
  48. cflags = [
  49. '-Wall',
  50. '-Wextra',
  51. '-Wpointer-arith',
  52. ]
  53. compress_source = 'src/borg/compress.pyx'
  54. crypto_ll_source = 'src/borg/crypto/low_level.pyx'
  55. chunker_source = 'src/borg/chunker.pyx'
  56. hashindex_source = 'src/borg/hashindex.pyx'
  57. item_source = 'src/borg/item.pyx'
  58. checksums_source = 'src/borg/algorithms/checksums.pyx'
  59. platform_posix_source = 'src/borg/platform/posix.pyx'
  60. platform_linux_source = 'src/borg/platform/linux.pyx'
  61. platform_syncfilerange_source = 'src/borg/platform/syncfilerange.pyx'
  62. platform_darwin_source = 'src/borg/platform/darwin.pyx'
  63. platform_freebsd_source = 'src/borg/platform/freebsd.pyx'
  64. msgpack_packer_source = 'src/borg/algorithms/msgpack/_packer.pyx'
  65. msgpack_unpacker_source = 'src/borg/algorithms/msgpack/_unpacker.pyx'
  66. cython_c_sources = [
  67. # these .pyx will get compiled to .c
  68. compress_source,
  69. crypto_ll_source,
  70. chunker_source,
  71. hashindex_source,
  72. item_source,
  73. checksums_source,
  74. platform_posix_source,
  75. platform_linux_source,
  76. platform_syncfilerange_source,
  77. platform_freebsd_source,
  78. platform_darwin_source,
  79. ]
  80. cython_cpp_sources = [
  81. # these .pyx will get compiled to .cpp
  82. msgpack_packer_source,
  83. msgpack_unpacker_source,
  84. ]
  85. try:
  86. from Cython.Distutils import build_ext
  87. import Cython.Compiler.Main as cython_compiler
  88. class Sdist(sdist):
  89. def __init__(self, *args, **kwargs):
  90. for src in cython_c_sources:
  91. cython_compiler.compile(src, cython_compiler.default_options)
  92. for src in cython_cpp_sources:
  93. cython_compiler.compile(src, cplus=True)
  94. super().__init__(*args, **kwargs)
  95. def make_distribution(self):
  96. self.filelist.extend([
  97. 'src/borg/compress.c',
  98. 'src/borg/crypto/low_level.c',
  99. 'src/borg/chunker.c', 'src/borg/_chunker.c',
  100. 'src/borg/hashindex.c', 'src/borg/_hashindex.c',
  101. 'src/borg/cache_sync/cache_sync.c', 'src/borg/cache_sync/sysdep.h', 'src/borg/cache_sync/unpack.h',
  102. 'src/borg/cache_sync/unpack_define.h', 'src/borg/cache_sync/unpack_template.h',
  103. 'src/borg/item.c',
  104. 'src/borg/algorithms/checksums.c',
  105. 'src/borg/algorithms/crc32_dispatch.c', 'src/borg/algorithms/crc32_clmul.c', 'src/borg/algorithms/crc32_slice_by_8.c',
  106. 'src/borg/algorithms/xxh64/xxhash.h', 'src/borg/algorithms/xxh64/xxhash.c',
  107. 'src/borg/platform/posix.c',
  108. 'src/borg/platform/linux.c',
  109. 'src/borg/platform/syncfilerange.c',
  110. 'src/borg/platform/freebsd.c',
  111. 'src/borg/platform/darwin.c',
  112. 'src/borg/algorithms/msgpack/_packer.cpp',
  113. 'src/borg/algorithms/msgpack/_unpacker.cpp',
  114. ])
  115. super().make_distribution()
  116. except ImportError:
  117. class Sdist(sdist):
  118. def __init__(self, *args, **kwargs):
  119. raise Exception('Cython is required to run sdist')
  120. compress_source = compress_source.replace('.pyx', '.c')
  121. crypto_ll_source = crypto_ll_source.replace('.pyx', '.c')
  122. chunker_source = chunker_source.replace('.pyx', '.c')
  123. hashindex_source = hashindex_source.replace('.pyx', '.c')
  124. item_source = item_source.replace('.pyx', '.c')
  125. checksums_source = checksums_source.replace('.pyx', '.c')
  126. platform_posix_source = platform_posix_source.replace('.pyx', '.c')
  127. platform_linux_source = platform_linux_source.replace('.pyx', '.c')
  128. platform_syncfilerange_source = platform_syncfilerange_source.replace('.pyx', '.c')
  129. platform_freebsd_source = platform_freebsd_source.replace('.pyx', '.c')
  130. platform_darwin_source = platform_darwin_source.replace('.pyx', '.c')
  131. msgpack_packer_source = msgpack_packer_source.replace('.pyx', '.cpp')
  132. msgpack_unpacker_source = msgpack_unpacker_source.replace('.pyx', '.cpp')
  133. from setuptools.command.build_ext import build_ext
  134. if not on_rtd and not all(os.path.exists(path) for path in [
  135. compress_source, crypto_ll_source, chunker_source, hashindex_source, item_source, checksums_source,
  136. platform_posix_source, platform_linux_source, platform_syncfilerange_source, platform_freebsd_source, platform_darwin_source,
  137. msgpack_packer_source, msgpack_unpacker_source]):
  138. raise ImportError('The GIT version of Borg needs Cython. Install Cython or use a released version.')
  139. def detect_openssl(prefixes):
  140. for prefix in prefixes:
  141. filename = os.path.join(prefix, 'include', 'openssl', 'evp.h')
  142. if os.path.exists(filename):
  143. with open(filename, 'rb') as fd:
  144. if b'PKCS5_PBKDF2_HMAC(' in fd.read():
  145. return prefix
  146. include_dirs = []
  147. library_dirs = []
  148. define_macros = []
  149. possible_openssl_prefixes = ['/usr', '/usr/local', '/usr/local/opt/openssl', '/usr/local/ssl', '/usr/local/openssl',
  150. '/usr/local/borg', '/opt/local', '/opt/pkg', '/opt/homebrew/opt/openssl@1.1', ]
  151. if os.environ.get('BORG_OPENSSL_PREFIX'):
  152. possible_openssl_prefixes.insert(0, os.environ.get('BORG_OPENSSL_PREFIX'))
  153. ssl_prefix = detect_openssl(possible_openssl_prefixes)
  154. if not ssl_prefix:
  155. raise Exception('Unable to find OpenSSL >= 1.0 headers. (Looked here: {})'.format(', '.join(possible_openssl_prefixes)))
  156. include_dirs.append(os.path.join(ssl_prefix, 'include'))
  157. library_dirs.append(os.path.join(ssl_prefix, 'lib'))
  158. possible_liblz4_prefixes = ['/usr', '/usr/local', '/usr/local/opt/lz4', '/usr/local/lz4',
  159. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  160. if os.environ.get('BORG_LIBLZ4_PREFIX'):
  161. possible_liblz4_prefixes.insert(0, os.environ.get('BORG_LIBLZ4_PREFIX'))
  162. liblz4_prefix = setup_lz4.lz4_system_prefix(possible_liblz4_prefixes)
  163. if prefer_system_liblz4 and liblz4_prefix:
  164. print('Detected and preferring liblz4 over bundled LZ4')
  165. define_macros.append(('BORG_USE_LIBLZ4', 'YES'))
  166. liblz4_system = True
  167. else:
  168. liblz4_system = False
  169. possible_libb2_prefixes = ['/usr', '/usr/local', '/usr/local/opt/libb2', '/usr/local/libb2',
  170. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  171. if os.environ.get('BORG_LIBB2_PREFIX'):
  172. possible_libb2_prefixes.insert(0, os.environ.get('BORG_LIBB2_PREFIX'))
  173. libb2_prefix = setup_b2.b2_system_prefix(possible_libb2_prefixes)
  174. if prefer_system_libb2 and libb2_prefix:
  175. print('Detected and preferring libb2 over bundled BLAKE2')
  176. define_macros.append(('BORG_USE_LIBB2', 'YES'))
  177. libb2_system = True
  178. else:
  179. libb2_system = False
  180. possible_libzstd_prefixes = ['/usr', '/usr/local', '/usr/local/opt/libzstd', '/usr/local/libzstd',
  181. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  182. if os.environ.get('BORG_LIBZSTD_PREFIX'):
  183. possible_libzstd_prefixes.insert(0, os.environ.get('BORG_LIBZSTD_PREFIX'))
  184. libzstd_prefix = setup_zstd.zstd_system_prefix(possible_libzstd_prefixes)
  185. if prefer_system_libzstd and libzstd_prefix:
  186. print('Detected and preferring libzstd over bundled ZSTD')
  187. define_macros.append(('BORG_USE_LIBZSTD', 'YES'))
  188. libzstd_system = True
  189. else:
  190. libzstd_system = False
  191. possible_libxxhash_prefixes = ['/usr', '/usr/local', '/usr/local/opt/libxxhash', '/usr/local/libxxhash',
  192. '/usr/local/borg', '/opt/local', '/opt/pkg', ]
  193. if os.environ.get('BORG_LIBXXHASH_PREFIX'):
  194. possible_libxxhash_prefixes.insert(0, os.environ.get('BORG_LIBXXHASH_PREFIX'))
  195. libxxhash_prefix = setup_xxhash.xxhash_system_prefix(possible_libxxhash_prefixes)
  196. if prefer_system_libxxhash and libxxhash_prefix:
  197. print('Detected and preferring libxxhash over bundled XXHASH')
  198. define_macros.append(('BORG_USE_LIBXXHASH', 'YES'))
  199. define_macros.append(('XXH_PRIVATE_API', 'YES')) # do not use this for bundled zstd or xxh64, breaks the build
  200. libxxhash_system = True
  201. else:
  202. define_macros.append(('XXH_VECTOR', '0')) # avoid compile issues with CPU specific stuff
  203. libxxhash_system = False
  204. with open('README.rst', 'r') as fd:
  205. long_description = fd.read()
  206. # remove header, but have one \n before first headline
  207. start = long_description.find('What is BorgBackup?')
  208. assert start >= 0
  209. long_description = '\n' + long_description[start:]
  210. # remove badges
  211. long_description = re.compile(r'^\.\. start-badges.*^\.\. end-badges', re.M | re.S).sub('', long_description)
  212. # remove unknown directives
  213. long_description = re.compile(r'^\.\. highlight:: \w+$', re.M).sub('', long_description)
  214. def format_metavar(option):
  215. if option.nargs in ('*', '...'):
  216. return '[%s...]' % option.metavar
  217. elif option.nargs == '?':
  218. return '[%s]' % option.metavar
  219. elif option.nargs is None:
  220. return option.metavar
  221. else:
  222. raise ValueError('Can\'t format metavar %s, unknown nargs %s!' % (option.metavar, option.nargs))
  223. class build_usage(Command):
  224. description = "generate usage for each command"
  225. user_options = [
  226. ('output=', 'O', 'output directory'),
  227. ]
  228. def initialize_options(self):
  229. pass
  230. def finalize_options(self):
  231. pass
  232. def run(self):
  233. print('generating usage docs')
  234. import borg
  235. borg.doc_mode = 'build_man'
  236. if not os.path.exists('docs/usage'):
  237. os.mkdir('docs/usage')
  238. # allows us to build docs without the C modules fully loaded during help generation
  239. from borg.archiver import Archiver
  240. parser = Archiver(prog='borg').build_parser()
  241. # borgfs has a separate man page to satisfy debian's "every program from a package
  242. # must have a man page" requirement, but it doesn't need a separate HTML docs page
  243. #borgfs_parser = Archiver(prog='borgfs').build_parser()
  244. self.generate_level("", parser, Archiver)
  245. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  246. is_subcommand = False
  247. choices = {}
  248. for action in parser._actions:
  249. if action.choices is not None and 'SubParsersAction' in str(action.__class__):
  250. is_subcommand = True
  251. for cmd, parser in action.choices.items():
  252. choices[prefix + cmd] = parser
  253. if extra_choices is not None:
  254. choices.update(extra_choices)
  255. if prefix and not choices:
  256. return
  257. print('found commands: %s' % list(choices.keys()))
  258. for command, parser in sorted(choices.items()):
  259. if command.startswith('debug'):
  260. print('skipping', command)
  261. continue
  262. print('generating help for %s' % command)
  263. if self.generate_level(command + " ", parser, Archiver):
  264. continue
  265. with open('docs/usage/%s.rst.inc' % command.replace(" ", "_"), 'w') as doc:
  266. doc.write(".. IMPORTANT: this file is auto-generated from borg's built-in help, do not edit!\n\n")
  267. if command == 'help':
  268. for topic in Archiver.helptext:
  269. params = {"topic": topic,
  270. "underline": '~' * len('borg help ' + topic)}
  271. doc.write(".. _borg_{topic}:\n\n".format(**params))
  272. doc.write("borg help {topic}\n{underline}\n\n".format(**params))
  273. doc.write(Archiver.helptext[topic])
  274. else:
  275. params = {"command": command,
  276. "command_": command.replace(' ', '_'),
  277. "underline": '-' * len('borg ' + command)}
  278. doc.write(".. _borg_{command_}:\n\n".format(**params))
  279. doc.write("borg {command}\n{underline}\n.. code-block:: none\n\n borg [common options] {command}".format(**params))
  280. self.write_usage(parser, doc)
  281. epilog = parser.epilog
  282. parser.epilog = None
  283. self.write_options(parser, doc)
  284. doc.write("\n\nDescription\n~~~~~~~~~~~\n")
  285. doc.write(epilog)
  286. if 'create' in choices:
  287. common_options = [group for group in choices['create']._action_groups if group.title == 'Common options'][0]
  288. with open('docs/usage/common-options.rst.inc', 'w') as doc:
  289. self.write_options_group(common_options, doc, False, base_indent=0)
  290. return is_subcommand
  291. def write_usage(self, parser, fp):
  292. if any(len(o.option_strings) for o in parser._actions):
  293. fp.write(' [options]')
  294. for option in parser._actions:
  295. if option.option_strings:
  296. continue
  297. fp.write(' ' + format_metavar(option))
  298. fp.write('\n\n')
  299. def write_options(self, parser, fp):
  300. def is_positional_group(group):
  301. return any(not o.option_strings for o in group._group_actions)
  302. # HTML output:
  303. # A table using some column-spans
  304. def html_write(s):
  305. for line in s.splitlines():
  306. fp.write(' ' + line + '\n')
  307. rows = []
  308. for group in parser._action_groups:
  309. if group.title == 'Common options':
  310. # (no of columns used, columns, ...)
  311. rows.append((1, '.. class:: borg-common-opt-ref\n\n:ref:`common_options`'))
  312. else:
  313. if not group._group_actions:
  314. continue
  315. group_header = '**%s**' % group.title
  316. if group.description:
  317. group_header += ' — ' + group.description
  318. rows.append((1, group_header))
  319. if is_positional_group(group):
  320. for option in group._group_actions:
  321. rows.append((3, '', '``%s``' % option.metavar, option.help or ''))
  322. else:
  323. for option in group._group_actions:
  324. if option.metavar:
  325. option_fmt = '``%s ' + option.metavar + '``'
  326. else:
  327. option_fmt = '``%s``'
  328. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  329. option_desc = textwrap.dedent((option.help or '') % option.__dict__)
  330. rows.append((3, '', option_str, option_desc))
  331. fp.write('.. only:: html\n\n')
  332. table = io.StringIO()
  333. table.write('.. class:: borg-options-table\n\n')
  334. self.rows_to_table(rows, table.write)
  335. fp.write(textwrap.indent(table.getvalue(), ' ' * 4))
  336. # LaTeX output:
  337. # Regular rST option lists (irregular column widths)
  338. latex_options = io.StringIO()
  339. for group in parser._action_groups:
  340. if group.title == 'Common options':
  341. latex_options.write('\n\n:ref:`common_options`\n')
  342. latex_options.write(' |')
  343. else:
  344. self.write_options_group(group, latex_options)
  345. fp.write('\n.. only:: latex\n\n')
  346. fp.write(textwrap.indent(latex_options.getvalue(), ' ' * 4))
  347. def rows_to_table(self, rows, write):
  348. def write_row_separator():
  349. write('+')
  350. for column_width in column_widths:
  351. write('-' * (column_width + 1))
  352. write('+')
  353. write('\n')
  354. # Find column count and width
  355. column_count = max(columns for columns, *_ in rows)
  356. column_widths = [0] * column_count
  357. for columns, *cells in rows:
  358. for i in range(columns):
  359. # "+ 1" because we want a space between the cell contents and the delimiting "|" in the output
  360. column_widths[i] = max(column_widths[i], len(cells[i]) + 1)
  361. for columns, *original_cells in rows:
  362. write_row_separator()
  363. # If a cell contains newlines, then the row must be split up in individual rows
  364. # where each cell contains no newline.
  365. rowspanning_cells = []
  366. original_cells = list(original_cells)
  367. while any('\n' in cell for cell in original_cells):
  368. cell_bloc = []
  369. for i, cell in enumerate(original_cells):
  370. pre, _, original_cells[i] = cell.partition('\n')
  371. cell_bloc.append(pre)
  372. rowspanning_cells.append(cell_bloc)
  373. rowspanning_cells.append(original_cells)
  374. for cells in rowspanning_cells:
  375. for i, column_width in enumerate(column_widths):
  376. if i < columns:
  377. write('| ')
  378. write(cells[i].ljust(column_width))
  379. else:
  380. write(' ')
  381. write(''.ljust(column_width))
  382. write('|\n')
  383. write_row_separator()
  384. # This bit of JavaScript kills the <colgroup> that is invariably inserted by docutils,
  385. # but does absolutely no good here. It sets bogus column widths which cannot be overridden
  386. # with CSS alone.
  387. # Since this is HTML-only output, it would be possible to just generate a <table> directly,
  388. # but then we'd lose rST formatting.
  389. write(textwrap.dedent("""
  390. .. raw:: html
  391. <script type='text/javascript'>
  392. $(document).ready(function () {
  393. $('.borg-options-table colgroup').remove();
  394. })
  395. </script>
  396. """))
  397. def write_options_group(self, group, fp, with_title=True, base_indent=4):
  398. def is_positional_group(group):
  399. return any(not o.option_strings for o in group._group_actions)
  400. indent = ' ' * base_indent
  401. if is_positional_group(group):
  402. for option in group._group_actions:
  403. fp.write(option.metavar + '\n')
  404. fp.write(textwrap.indent(option.help or '', ' ' * base_indent) + '\n')
  405. return
  406. if not group._group_actions:
  407. return
  408. if with_title:
  409. fp.write('\n\n')
  410. fp.write(group.title + '\n')
  411. opts = OrderedDict()
  412. for option in group._group_actions:
  413. if option.metavar:
  414. option_fmt = '%s ' + option.metavar
  415. else:
  416. option_fmt = '%s'
  417. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  418. option_desc = textwrap.dedent((option.help or '') % option.__dict__)
  419. opts[option_str] = textwrap.indent(option_desc, ' ' * 4)
  420. padding = len(max(opts)) + 1
  421. for option, desc in opts.items():
  422. fp.write(indent + option.ljust(padding) + desc + '\n')
  423. class build_man(Command):
  424. description = 'build man pages'
  425. user_options = []
  426. see_also = {
  427. 'create': ('delete', 'prune', 'check', 'patterns', 'placeholders', 'compression'),
  428. 'recreate': ('patterns', 'placeholders', 'compression'),
  429. 'list': ('info', 'diff', 'prune', 'patterns'),
  430. 'info': ('list', 'diff'),
  431. 'init': ('create', 'delete', 'check', 'list', 'key-import', 'key-export', 'key-change-passphrase'),
  432. 'key-import': ('key-export', ),
  433. 'key-export': ('key-import', ),
  434. 'mount': ('umount', 'extract'), # Would be cooler if these two were on the same page
  435. 'umount': ('mount', ),
  436. 'extract': ('mount', ),
  437. }
  438. rst_prelude = textwrap.dedent("""
  439. .. role:: ref(title)
  440. .. |project_name| replace:: Borg
  441. """)
  442. usage_group = {
  443. 'break-lock': 'lock',
  444. 'with-lock': 'lock',
  445. 'change-passphrase': 'key',
  446. 'key_change-passphrase': 'key',
  447. 'key_export': 'key',
  448. 'key_import': 'key',
  449. 'key_migrate-to-repokey': 'key',
  450. 'export-tar': 'tar',
  451. 'benchmark_crud': 'benchmark',
  452. 'umount': 'mount',
  453. }
  454. def initialize_options(self):
  455. pass
  456. def finalize_options(self):
  457. pass
  458. def run(self):
  459. print('building man pages (in docs/man)', file=sys.stderr)
  460. import borg
  461. borg.doc_mode = 'build_man'
  462. os.makedirs('docs/man', exist_ok=True)
  463. # allows us to build docs without the C modules fully loaded during help generation
  464. from borg.archiver import Archiver
  465. parser = Archiver(prog='borg').build_parser()
  466. borgfs_parser = Archiver(prog='borgfs').build_parser()
  467. self.generate_level('', parser, Archiver, {'borgfs': borgfs_parser})
  468. self.build_topic_pages(Archiver)
  469. self.build_intro_page()
  470. def generate_level(self, prefix, parser, Archiver, extra_choices=None):
  471. is_subcommand = False
  472. choices = {}
  473. for action in parser._actions:
  474. if action.choices is not None and 'SubParsersAction' in str(action.__class__):
  475. is_subcommand = True
  476. for cmd, parser in action.choices.items():
  477. choices[prefix + cmd] = parser
  478. if extra_choices is not None:
  479. choices.update(extra_choices)
  480. if prefix and not choices:
  481. return
  482. for command, parser in sorted(choices.items()):
  483. if command.startswith('debug') or command == 'help':
  484. continue
  485. if command == "borgfs":
  486. man_title = command
  487. else:
  488. man_title = 'borg-' + command.replace(' ', '-')
  489. print('building man page', man_title + '(1)', file=sys.stderr)
  490. is_intermediary = self.generate_level(command + ' ', parser, Archiver)
  491. doc, write = self.new_doc()
  492. self.write_man_header(write, man_title, parser.description)
  493. self.write_heading(write, 'SYNOPSIS')
  494. if is_intermediary:
  495. subparsers = [action for action in parser._actions if 'SubParsersAction' in str(action.__class__)][0]
  496. for subcommand in subparsers.choices:
  497. write('| borg', '[common options]', command, subcommand, '...')
  498. self.see_also.setdefault(command, []).append('%s-%s' % (command, subcommand))
  499. else:
  500. if command == "borgfs":
  501. write(command, end='')
  502. else:
  503. write('borg', '[common options]', command, end='')
  504. self.write_usage(write, parser)
  505. write('\n')
  506. description, _, notes = parser.epilog.partition('\n.. man NOTES')
  507. if description:
  508. self.write_heading(write, 'DESCRIPTION')
  509. write(description)
  510. if not is_intermediary:
  511. self.write_heading(write, 'OPTIONS')
  512. write('See `borg-common(1)` for common options of Borg commands.')
  513. write()
  514. self.write_options(write, parser)
  515. self.write_examples(write, command)
  516. if notes:
  517. self.write_heading(write, 'NOTES')
  518. write(notes)
  519. self.write_see_also(write, man_title)
  520. self.gen_man_page(man_title, doc.getvalue())
  521. # Generate the borg-common(1) man page with the common options.
  522. if 'create' in choices:
  523. doc, write = self.new_doc()
  524. man_title = 'borg-common'
  525. self.write_man_header(write, man_title, 'Common options of Borg commands')
  526. common_options = [group for group in choices['create']._action_groups if group.title == 'Common options'][0]
  527. self.write_heading(write, 'SYNOPSIS')
  528. self.write_options_group(write, common_options)
  529. self.write_see_also(write, man_title)
  530. self.gen_man_page(man_title, doc.getvalue())
  531. return is_subcommand
  532. def build_topic_pages(self, Archiver):
  533. for topic, text in Archiver.helptext.items():
  534. doc, write = self.new_doc()
  535. man_title = 'borg-' + topic
  536. print('building man page', man_title + '(1)', file=sys.stderr)
  537. self.write_man_header(write, man_title, 'Details regarding ' + topic)
  538. self.write_heading(write, 'DESCRIPTION')
  539. write(text)
  540. self.gen_man_page(man_title, doc.getvalue())
  541. def build_intro_page(self):
  542. print('building man page borg(1)', file=sys.stderr)
  543. with open('docs/man_intro.rst') as fd:
  544. man_intro = fd.read()
  545. self.gen_man_page('borg', self.rst_prelude + man_intro)
  546. def new_doc(self):
  547. doc = io.StringIO(self.rst_prelude)
  548. doc.read()
  549. write = self.printer(doc)
  550. return doc, write
  551. def printer(self, fd):
  552. def write(*args, **kwargs):
  553. print(*args, file=fd, **kwargs)
  554. return write
  555. def write_heading(self, write, header, char='-', double_sided=False):
  556. write()
  557. if double_sided:
  558. write(char * len(header))
  559. write(header)
  560. write(char * len(header))
  561. write()
  562. def write_man_header(self, write, title, description):
  563. self.write_heading(write, title, '=', double_sided=True)
  564. self.write_heading(write, description, double_sided=True)
  565. # man page metadata
  566. write(':Author: The Borg Collective')
  567. write(':Date:', datetime.utcnow().date().isoformat())
  568. write(':Manual section: 1')
  569. write(':Manual group: borg backup tool')
  570. write()
  571. def write_examples(self, write, command):
  572. command = command.replace(' ', '_')
  573. with open('docs/usage/%s.rst' % self.usage_group.get(command, command)) as fd:
  574. usage = fd.read()
  575. usage_include = '.. include:: %s.rst.inc' % command
  576. begin = usage.find(usage_include)
  577. end = usage.find('.. include', begin + 1)
  578. # If a command has a dedicated anchor, it will occur before the command's include.
  579. if 0 < usage.find('.. _', begin + 1) < end:
  580. end = usage.find('.. _', begin + 1)
  581. examples = usage[begin:end]
  582. examples = examples.replace(usage_include, '')
  583. examples = examples.replace('Examples\n~~~~~~~~', '')
  584. examples = examples.replace('Miscellaneous Help\n------------------', '')
  585. examples = examples.replace('``docs/misc/prune-example.txt``:', '``docs/misc/prune-example.txt``.')
  586. examples = examples.replace('.. highlight:: none\n', '') # we don't support highlight
  587. examples = re.sub('^(~+)$', lambda matches: '+' * len(matches.group(0)), examples, flags=re.MULTILINE)
  588. examples = examples.strip()
  589. if examples:
  590. self.write_heading(write, 'EXAMPLES', '-')
  591. write(examples)
  592. def write_see_also(self, write, man_title):
  593. see_also = self.see_also.get(man_title.replace('borg-', ''), ())
  594. see_also = ['`borg-%s(1)`' % s for s in see_also]
  595. see_also.insert(0, '`borg-common(1)`')
  596. self.write_heading(write, 'SEE ALSO')
  597. write(', '.join(see_also))
  598. def gen_man_page(self, name, rst):
  599. from docutils.writers import manpage
  600. from docutils.core import publish_string
  601. from docutils.nodes import inline
  602. from docutils.parsers.rst import roles
  603. def issue(name, rawtext, text, lineno, inliner, options={}, content=[]):
  604. return [inline(rawtext, '#' + text)], []
  605. roles.register_local_role('issue', issue)
  606. # We give the source_path so that docutils can find relative includes
  607. # as-if the document where located in the docs/ directory.
  608. man_page = publish_string(source=rst, source_path='docs/%s.rst' % name, writer=manpage.Writer())
  609. with open('docs/man/%s.1' % name, 'wb') as fd:
  610. fd.write(man_page)
  611. def write_usage(self, write, parser):
  612. if any(len(o.option_strings) for o in parser._actions):
  613. write(' [options] ', end='')
  614. for option in parser._actions:
  615. if option.option_strings:
  616. continue
  617. write(format_metavar(option), end=' ')
  618. def write_options(self, write, parser):
  619. for group in parser._action_groups:
  620. if group.title == 'Common options' or not group._group_actions:
  621. continue
  622. title = 'arguments' if group.title == 'positional arguments' else group.title
  623. self.write_heading(write, title, '+')
  624. self.write_options_group(write, group)
  625. def write_options_group(self, write, group):
  626. def is_positional_group(group):
  627. return any(not o.option_strings for o in group._group_actions)
  628. if is_positional_group(group):
  629. for option in group._group_actions:
  630. write(option.metavar)
  631. write(textwrap.indent(option.help or '', ' ' * 4))
  632. return
  633. opts = OrderedDict()
  634. for option in group._group_actions:
  635. if option.metavar:
  636. option_fmt = '%s ' + option.metavar
  637. else:
  638. option_fmt = '%s'
  639. option_str = ', '.join(option_fmt % s for s in option.option_strings)
  640. option_desc = textwrap.dedent((option.help or '') % option.__dict__)
  641. opts[option_str] = textwrap.indent(option_desc, ' ' * 4)
  642. padding = len(max(opts)) + 1
  643. for option, desc in opts.items():
  644. write(option.ljust(padding), desc)
  645. def rm(file):
  646. try:
  647. os.unlink(file)
  648. print('rm', file)
  649. except FileNotFoundError:
  650. pass
  651. class Clean(Command):
  652. user_options = []
  653. def initialize_options(self):
  654. pass
  655. def finalize_options(self):
  656. pass
  657. def run(self):
  658. for source in cython_c_sources:
  659. genc = source.replace('.pyx', '.c')
  660. rm(genc)
  661. for source in cython_cpp_sources:
  662. gencpp = source.replace('.pyx', '.cpp')
  663. rm(gencpp)
  664. for source in cython_c_sources + cython_cpp_sources:
  665. compiled_glob = source.replace('.pyx', '.cpython*')
  666. for compiled in sorted(glob(compiled_glob)):
  667. rm(compiled)
  668. cmdclass = {
  669. 'build_ext': build_ext,
  670. 'build_usage': build_usage,
  671. 'build_man': build_man,
  672. 'sdist': Sdist,
  673. 'clean2': Clean,
  674. }
  675. ext_modules = []
  676. if not on_rtd:
  677. compress_ext_kwargs = dict(sources=[compress_source], include_dirs=include_dirs, library_dirs=library_dirs,
  678. define_macros=define_macros, extra_compile_args=cflags)
  679. compress_ext_kwargs = setup_lz4.lz4_ext_kwargs(bundled_path='src/borg/algorithms/lz4',
  680. system_prefix=liblz4_prefix, system=liblz4_system,
  681. **compress_ext_kwargs)
  682. compress_ext_kwargs = setup_zstd.zstd_ext_kwargs(bundled_path='src/borg/algorithms/zstd',
  683. system_prefix=libzstd_prefix, system=libzstd_system,
  684. multithreaded=False, legacy=False, **compress_ext_kwargs)
  685. crypto_ext_kwargs = dict(sources=[crypto_ll_source], libraries=['crypto'],
  686. include_dirs=include_dirs, library_dirs=library_dirs, define_macros=define_macros,
  687. extra_compile_args=cflags)
  688. crypto_ext_kwargs = setup_b2.b2_ext_kwargs(bundled_path='src/borg/algorithms/blake2',
  689. system_prefix=libb2_prefix, system=libb2_system,
  690. **crypto_ext_kwargs)
  691. checksums_ext_kwargs = dict(sources=[checksums_source], include_dirs=include_dirs, library_dirs=library_dirs,
  692. define_macros=define_macros, extra_compile_args=cflags)
  693. checksums_ext_kwargs = setup_xxhash.xxhash_ext_kwargs(bundled_path='src/borg/algorithms/xxh64',
  694. system_prefix=libxxhash_prefix, system=libxxhash_system,
  695. **checksums_ext_kwargs)
  696. msgpack_macros = [] # setup.py of msgpack 0.5.6 defines __LITTLE_ENDIAN__ / __BIG_ENDIAN__ - which
  697. # leads to troubles when trying cross-platform builds, see borg issue #6105.
  698. # in current msgpack, this was fixed to ONLY define __LITTLE_ENDIAN__ ON WIN32.
  699. # as borg 1.1.x does not support native win32 anyway, we do not have that here.
  700. msgpack_packer_ext_kwargs = dict(
  701. sources=[msgpack_packer_source],
  702. include_dirs=include_dirs,
  703. library_dirs=library_dirs,
  704. define_macros=msgpack_macros,
  705. language='c++',
  706. extra_compile_args=cflags,
  707. )
  708. msgpack_unpacker_ext_kwargs = dict(
  709. sources=[msgpack_unpacker_source],
  710. include_dirs=include_dirs,
  711. library_dirs=library_dirs,
  712. define_macros=msgpack_macros,
  713. language='c++',
  714. extra_compile_args=cflags,
  715. )
  716. ext_modules += [
  717. Extension('borg.algorithms.msgpack._packer', **msgpack_packer_ext_kwargs),
  718. Extension('borg.algorithms.msgpack._unpacker', **msgpack_unpacker_ext_kwargs),
  719. Extension('borg.compress', **compress_ext_kwargs),
  720. Extension('borg.crypto.low_level', **crypto_ext_kwargs),
  721. Extension('borg.hashindex', [hashindex_source], extra_compile_args=cflags),
  722. Extension('borg.item', [item_source], extra_compile_args=cflags),
  723. Extension('borg.chunker', [chunker_source], extra_compile_args=cflags),
  724. Extension('borg.algorithms.checksums', **checksums_ext_kwargs),
  725. ]
  726. if not sys.platform.startswith(('win32', )):
  727. ext_modules.append(Extension('borg.platform.posix', [platform_posix_source], extra_compile_args=cflags))
  728. if sys.platform == 'linux':
  729. ext_modules.append(Extension('borg.platform.linux', [platform_linux_source], libraries=['acl'], extra_compile_args=cflags))
  730. ext_modules.append(Extension('borg.platform.syncfilerange', [platform_syncfilerange_source], extra_compile_args=cflags))
  731. elif sys.platform.startswith('freebsd'):
  732. ext_modules.append(Extension('borg.platform.freebsd', [platform_freebsd_source], extra_compile_args=cflags))
  733. elif sys.platform == 'darwin':
  734. ext_modules.append(Extension('borg.platform.darwin', [platform_darwin_source], extra_compile_args=cflags))
  735. setup(
  736. name='borgbackup',
  737. use_scm_version={
  738. 'write_to': 'src/borg/_version.py',
  739. },
  740. author='The Borg Collective (see AUTHORS file)',
  741. author_email='borgbackup@python.org',
  742. url='https://borgbackup.readthedocs.io/',
  743. description='Deduplicated, encrypted, authenticated and compressed backups',
  744. long_description=long_description,
  745. license='BSD',
  746. platforms=['Linux', 'MacOS X', 'FreeBSD', 'OpenBSD', 'NetBSD', ],
  747. classifiers=[
  748. 'Development Status :: 4 - Beta',
  749. 'Environment :: Console',
  750. 'Intended Audience :: System Administrators',
  751. 'License :: OSI Approved :: BSD License',
  752. 'Operating System :: POSIX :: BSD :: FreeBSD',
  753. 'Operating System :: POSIX :: BSD :: OpenBSD',
  754. 'Operating System :: POSIX :: BSD :: NetBSD',
  755. 'Operating System :: MacOS :: MacOS X',
  756. 'Operating System :: POSIX :: Linux',
  757. 'Programming Language :: Python',
  758. 'Programming Language :: Python :: 3',
  759. 'Programming Language :: Python :: 3.5',
  760. 'Programming Language :: Python :: 3.6',
  761. 'Programming Language :: Python :: 3.7',
  762. 'Programming Language :: Python :: 3.8',
  763. 'Programming Language :: Python :: 3.9',
  764. 'Programming Language :: Python :: 3.10',
  765. 'Topic :: Security :: Cryptography',
  766. 'Topic :: System :: Archiving :: Backup',
  767. ],
  768. packages=find_packages('src'),
  769. package_dir={'': 'src'},
  770. zip_safe=False,
  771. entry_points={
  772. 'console_scripts': [
  773. 'borg = borg.archiver:main',
  774. 'borgfs = borg.archiver:main',
  775. ]
  776. },
  777. # See also the MANIFEST.in file.
  778. # We want to install all the files in the package directories...
  779. include_package_data=True,
  780. # ...except the source files which have been compiled (C extensions):
  781. exclude_package_data={
  782. '': ['*.c', '*.h', '*.pyx', ],
  783. },
  784. cmdclass=cmdclass,
  785. ext_modules=ext_modules,
  786. setup_requires=['setuptools_scm>=1.7'],
  787. install_requires=install_requires,
  788. extras_require=extras_require,
  789. )