setup.py 35 KB

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