setup.py 36 KB

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