setup.py 33 KB

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