setup.py 34 KB

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