setup.py 36 KB

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