setup.py 33 KB

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