setup.py 32 KB

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