2
0

setup.py 37 KB

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