setup.py 34 KB

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