setup.py 33 KB

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