setup.py 34 KB

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