setup.py 37 KB

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