setup.py 36 KB

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