setup.py 31 KB

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