2
0

setup.py 33 KB

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