2
0

setup.py 33 KB

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