setup.py 31 KB

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