helpers.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. from .support import argparse # see support/__init__.py docstring
  2. # DEPRECATED - remove after requiring py 3.4
  3. import binascii
  4. from collections import namedtuple
  5. from functools import wraps
  6. import grp
  7. import os
  8. import pwd
  9. import re
  10. import sys
  11. import time
  12. import unicodedata
  13. from datetime import datetime, timezone, timedelta
  14. from fnmatch import translate
  15. from operator import attrgetter
  16. import msgpack
  17. from . import hashindex
  18. from . import chunker
  19. from . import crypto
  20. class Error(Exception):
  21. """Error base class"""
  22. exit_code = 1
  23. def get_message(self):
  24. return 'Error: ' + type(self).__doc__.format(*self.args)
  25. class ExtensionModuleError(Error):
  26. """The Borg binary extension modules do not seem to be properly installed"""
  27. def check_extension_modules():
  28. from . import platform
  29. if hashindex.API_VERSION != 2:
  30. raise ExtensionModuleError
  31. if chunker.API_VERSION != 2:
  32. raise ExtensionModuleError
  33. if crypto.API_VERSION != 2:
  34. raise ExtensionModuleError
  35. if platform.API_VERSION != 2:
  36. raise ExtensionModuleError
  37. class Manifest:
  38. MANIFEST_ID = b'\0' * 32
  39. def __init__(self, key, repository):
  40. self.archives = {}
  41. self.config = {}
  42. self.key = key
  43. self.repository = repository
  44. @classmethod
  45. def load(cls, repository, key=None):
  46. from .key import key_factory
  47. cdata = repository.get(cls.MANIFEST_ID)
  48. if not key:
  49. key = key_factory(repository, cdata)
  50. manifest = cls(key, repository)
  51. data = key.decrypt(None, cdata)
  52. manifest.id = key.id_hash(data)
  53. m = msgpack.unpackb(data)
  54. if not m.get(b'version') == 1:
  55. raise ValueError('Invalid manifest version')
  56. manifest.archives = dict((k.decode('utf-8'), v) for k, v in m[b'archives'].items())
  57. manifest.timestamp = m.get(b'timestamp')
  58. if manifest.timestamp:
  59. manifest.timestamp = manifest.timestamp.decode('ascii')
  60. manifest.config = m[b'config']
  61. return manifest, key
  62. def write(self):
  63. self.timestamp = datetime.utcnow().isoformat()
  64. data = msgpack.packb(StableDict({
  65. 'version': 1,
  66. 'archives': self.archives,
  67. 'timestamp': self.timestamp,
  68. 'config': self.config,
  69. }))
  70. self.id = self.key.id_hash(data)
  71. self.repository.put(self.MANIFEST_ID, self.key.encrypt(data))
  72. def list_archive_infos(self, sort_by=None, reverse=False):
  73. # inexpensive Archive.list_archives replacement if we just need .name, .id, .ts
  74. ArchiveInfo = namedtuple('ArchiveInfo', 'name id ts')
  75. archives = []
  76. for name, values in self.archives.items():
  77. ts = parse_timestamp(values[b'time'].decode('utf-8'))
  78. id = values[b'id']
  79. archives.append(ArchiveInfo(name=name, id=id, ts=ts))
  80. if sort_by is not None:
  81. archives = sorted(archives, key=attrgetter(sort_by), reverse=reverse)
  82. return archives
  83. def prune_within(archives, within):
  84. multiplier = {'H': 1, 'd': 24, 'w': 24*7, 'm': 24*31, 'y': 24*365}
  85. try:
  86. hours = int(within[:-1]) * multiplier[within[-1]]
  87. except (KeyError, ValueError):
  88. # I don't like how this displays the original exception too:
  89. raise argparse.ArgumentTypeError('Unable to parse --within option: "%s"' % within)
  90. if hours <= 0:
  91. raise argparse.ArgumentTypeError('Number specified using --within option must be positive')
  92. target = datetime.now(timezone.utc) - timedelta(seconds=hours*60*60)
  93. return [a for a in archives if a.ts > target]
  94. def prune_split(archives, pattern, n, skip=[]):
  95. last = None
  96. keep = []
  97. if n == 0:
  98. return keep
  99. for a in sorted(archives, key=attrgetter('ts'), reverse=True):
  100. period = to_localtime(a.ts).strftime(pattern)
  101. if period != last:
  102. last = period
  103. if a not in skip:
  104. keep.append(a)
  105. if len(keep) == n:
  106. break
  107. return keep
  108. class Statistics:
  109. def __init__(self):
  110. self.osize = self.csize = self.usize = self.nfiles = 0
  111. def update(self, size, csize, unique):
  112. self.osize += size
  113. self.csize += csize
  114. if unique:
  115. self.usize += csize
  116. def print_(self, label, cache):
  117. total_size, total_csize, unique_size, unique_csize, total_unique_chunks, total_chunks = cache.chunks.summarize()
  118. print()
  119. print(' Original size Compressed size Deduplicated size')
  120. print('%-15s %20s %20s %20s' % (label, format_file_size(self.osize), format_file_size(self.csize), format_file_size(self.usize)))
  121. print('All archives: %20s %20s %20s' % (format_file_size(total_size), format_file_size(total_csize), format_file_size(unique_csize)))
  122. print()
  123. print(' Unique chunks Total chunks')
  124. print('Chunk index: %20d %20d' % (total_unique_chunks, total_chunks))
  125. def show_progress(self, item=None, final=False):
  126. if not final:
  127. path = remove_surrogates(item[b'path']) if item else ''
  128. if len(path) > 43:
  129. path = '%s...%s' % (path[:20], path[-20:])
  130. msg = '%9s O %9s C %9s D %-43s' % (
  131. format_file_size(self.osize), format_file_size(self.csize), format_file_size(self.usize), path)
  132. else:
  133. msg = ' ' * 79
  134. print(msg, end='\r')
  135. sys.stdout.flush()
  136. def get_keys_dir():
  137. """Determine where to repository keys and cache"""
  138. return os.environ.get('BORG_KEYS_DIR',
  139. os.path.join(os.path.expanduser('~'), '.borg', 'keys'))
  140. def get_cache_dir():
  141. """Determine where to repository keys and cache"""
  142. xdg_cache = os.environ.get('XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache'))
  143. return os.environ.get('BORG_CACHE_DIR', os.path.join(xdg_cache, 'borg'))
  144. def to_localtime(ts):
  145. """Convert datetime object from UTC to local time zone"""
  146. return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
  147. def parse_timestamp(timestamp):
  148. """Parse a ISO 8601 timestamp string"""
  149. if '.' in timestamp: # microseconds might not be pressent
  150. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
  151. else:
  152. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
  153. def update_excludes(args):
  154. """Merge exclude patterns from files with those on command line.
  155. Empty lines and lines starting with '#' are ignored, but whitespace
  156. is not stripped."""
  157. if hasattr(args, 'exclude_files') and args.exclude_files:
  158. if not hasattr(args, 'excludes') or args.excludes is None:
  159. args.excludes = []
  160. for file in args.exclude_files:
  161. patterns = [line.rstrip('\r\n') for line in file if not line.startswith('#')]
  162. args.excludes += [ExcludePattern(pattern) for pattern in patterns if pattern]
  163. file.close()
  164. def adjust_patterns(paths, excludes):
  165. if paths:
  166. return (excludes or []) + [IncludePattern(path) for path in paths] + [ExcludePattern('*')]
  167. else:
  168. return excludes
  169. def exclude_path(path, patterns):
  170. """Used by create and extract sub-commands to determine
  171. whether or not an item should be processed.
  172. """
  173. for pattern in (patterns or []):
  174. if pattern.match(path):
  175. return isinstance(pattern, ExcludePattern)
  176. return False
  177. # For both IncludePattern and ExcludePattern, we require that
  178. # the pattern either match the whole path or an initial segment
  179. # of the path up to but not including a path separator. To
  180. # unify the two cases, we add a path separator to the end of
  181. # the path before matching.
  182. def normalized(func):
  183. """ Decorator for the Pattern match methods, returning a wrapper that
  184. normalizes OSX paths to match the normalized pattern on OSX, and
  185. returning the original method on other platforms"""
  186. @wraps(func)
  187. def normalize_wrapper(self, path):
  188. return func(self, unicodedata.normalize("NFD", path))
  189. if sys.platform in ('darwin',):
  190. # HFS+ converts paths to a canonical form, so users shouldn't be
  191. # required to enter an exact match
  192. return normalize_wrapper
  193. else:
  194. # Windows and Unix filesystems allow different forms, so users
  195. # always have to enter an exact match
  196. return func
  197. class IncludePattern:
  198. """Literal files or directories listed on the command line
  199. for some operations (e.g. extract, but not create).
  200. If a directory is specified, all paths that start with that
  201. path match as well. A trailing slash makes no difference.
  202. """
  203. def __init__(self, pattern):
  204. self.pattern_orig = pattern
  205. self.match_count = 0
  206. if sys.platform in ('darwin',):
  207. pattern = unicodedata.normalize("NFD", pattern)
  208. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep)+os.path.sep
  209. @normalized
  210. def match(self, path):
  211. matches = (path+os.path.sep).startswith(self.pattern)
  212. if matches:
  213. self.match_count += 1
  214. return matches
  215. def __repr__(self):
  216. return '%s(%s)' % (type(self), self.pattern)
  217. def __str__(self):
  218. return self.pattern_orig
  219. class ExcludePattern(IncludePattern):
  220. """Shell glob patterns to exclude. A trailing slash means to
  221. exclude the contents of a directory, but not the directory itself.
  222. """
  223. def __init__(self, pattern):
  224. self.pattern_orig = pattern
  225. self.match_count = 0
  226. if pattern.endswith(os.path.sep):
  227. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep)+os.path.sep+'*'+os.path.sep
  228. else:
  229. self.pattern = os.path.normpath(pattern)+os.path.sep+'*'
  230. if sys.platform in ('darwin',):
  231. self.pattern = unicodedata.normalize("NFD", self.pattern)
  232. # fnmatch and re.match both cache compiled regular expressions.
  233. # Nevertheless, this is about 10 times faster.
  234. self.regex = re.compile(translate(self.pattern))
  235. @normalized
  236. def match(self, path):
  237. matches = self.regex.match(path+os.path.sep) is not None
  238. if matches:
  239. self.match_count += 1
  240. return matches
  241. def __repr__(self):
  242. return '%s(%s)' % (type(self), self.pattern)
  243. def __str__(self):
  244. return self.pattern_orig
  245. def timestamp(s):
  246. """Convert a --timestamp=s argument to a datetime object"""
  247. try:
  248. # is it pointing to a file / directory?
  249. ts = os.stat(s).st_mtime
  250. return datetime.utcfromtimestamp(ts)
  251. except OSError:
  252. # didn't work, try parsing as timestamp. UTC, no TZ, no microsecs support.
  253. for format in ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S+00:00',
  254. '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S',
  255. '%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M',
  256. '%Y-%m-%d', '%Y-%j',
  257. ):
  258. try:
  259. return datetime.strptime(s, format)
  260. except ValueError:
  261. continue
  262. raise ValueError
  263. def ChunkerParams(s):
  264. chunk_min, chunk_max, chunk_mask, window_size = s.split(',')
  265. if int(chunk_max) > 23:
  266. # do not go beyond 2**23 (8MB) chunk size now,
  267. # COMPR_BUFFER can only cope with up to this size
  268. raise ValueError('max. chunk size exponent must not be more than 23 (2^23 = 8MiB max. chunk size)')
  269. return int(chunk_min), int(chunk_max), int(chunk_mask), int(window_size)
  270. def CompressionSpec(s):
  271. values = s.split(',')
  272. count = len(values)
  273. if count < 1:
  274. raise ValueError
  275. compression = values[0]
  276. try:
  277. compression = int(compression)
  278. if count > 1:
  279. raise ValueError
  280. # DEPRECATED: it is just --compression N
  281. if 0 <= compression <= 9:
  282. return dict(name='zlib', level=compression)
  283. raise ValueError
  284. except ValueError:
  285. # --compression algo[,...]
  286. name = compression
  287. if name in ('none', 'lz4', ):
  288. return dict(name=name)
  289. if name in ('zlib', 'lzma', ):
  290. if count < 2:
  291. level = 6 # default compression level in py stdlib
  292. elif count == 2:
  293. level = int(values[1])
  294. if not 0 <= level <= 9:
  295. raise ValueError
  296. else:
  297. raise ValueError
  298. return dict(name=name, level=level)
  299. raise ValueError
  300. def is_cachedir(path):
  301. """Determines whether the specified path is a cache directory (and
  302. therefore should potentially be excluded from the backup) according to
  303. the CACHEDIR.TAG protocol
  304. (http://www.brynosaurus.com/cachedir/spec.html).
  305. """
  306. tag_contents = b'Signature: 8a477f597d28d172789f06886806bc55'
  307. tag_path = os.path.join(path, 'CACHEDIR.TAG')
  308. try:
  309. if os.path.exists(tag_path):
  310. with open(tag_path, 'rb') as tag_file:
  311. tag_data = tag_file.read(len(tag_contents))
  312. if tag_data == tag_contents:
  313. return True
  314. except OSError:
  315. pass
  316. return False
  317. def format_time(t):
  318. """Format datetime suitable for fixed length list output
  319. """
  320. if abs((datetime.now() - t).days) < 365:
  321. return t.strftime('%b %d %H:%M')
  322. else:
  323. return t.strftime('%b %d %Y')
  324. def format_timedelta(td):
  325. """Format timedelta in a human friendly format
  326. """
  327. # Since td.total_seconds() requires python 2.7
  328. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  329. s = ts % 60
  330. m = int(ts / 60) % 60
  331. h = int(ts / 3600) % 24
  332. txt = '%.2f seconds' % s
  333. if m:
  334. txt = '%d minutes %s' % (m, txt)
  335. if h:
  336. txt = '%d hours %s' % (h, txt)
  337. if td.days:
  338. txt = '%d days %s' % (td.days, txt)
  339. return txt
  340. def format_file_mode(mod):
  341. """Format file mode bits for list output
  342. """
  343. def x(v):
  344. return ''.join(v & m and s or '-'
  345. for m, s in ((4, 'r'), (2, 'w'), (1, 'x')))
  346. return '%s%s%s' % (x(mod // 64), x(mod // 8), x(mod))
  347. def format_file_size(v):
  348. """Format file size into a human friendly format
  349. """
  350. if abs(v) > 10**12:
  351. return '%.2f TB' % (v / 10**12)
  352. elif abs(v) > 10**9:
  353. return '%.2f GB' % (v / 10**9)
  354. elif abs(v) > 10**6:
  355. return '%.2f MB' % (v / 10**6)
  356. elif abs(v) > 10**3:
  357. return '%.2f kB' % (v / 10**3)
  358. else:
  359. return '%d B' % v
  360. def format_archive(archive):
  361. return '%-36s %s' % (archive.name, to_localtime(archive.ts).strftime('%c'))
  362. class IntegrityError(Error):
  363. """Data integrity error"""
  364. def memoize(function):
  365. cache = {}
  366. def decorated_function(*args):
  367. try:
  368. return cache[args]
  369. except KeyError:
  370. val = function(*args)
  371. cache[args] = val
  372. return val
  373. return decorated_function
  374. @memoize
  375. def uid2user(uid, default=None):
  376. try:
  377. return pwd.getpwuid(uid).pw_name
  378. except KeyError:
  379. return default
  380. @memoize
  381. def user2uid(user, default=None):
  382. try:
  383. return user and pwd.getpwnam(user).pw_uid
  384. except KeyError:
  385. return default
  386. @memoize
  387. def gid2group(gid, default=None):
  388. try:
  389. return grp.getgrgid(gid).gr_name
  390. except KeyError:
  391. return default
  392. @memoize
  393. def group2gid(group, default=None):
  394. try:
  395. return group and grp.getgrnam(group).gr_gid
  396. except KeyError:
  397. return default
  398. def posix_acl_use_stored_uid_gid(acl):
  399. """Replace the user/group field with the stored uid/gid
  400. """
  401. entries = []
  402. for entry in acl.decode('ascii').split('\n'):
  403. if entry:
  404. fields = entry.split(':')
  405. if len(fields) == 4:
  406. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  407. else:
  408. entries.append(entry)
  409. return ('\n'.join(entries)).encode('ascii')
  410. class Location:
  411. """Object representing a repository / archive location
  412. """
  413. proto = user = host = port = path = archive = None
  414. # borg mount's FUSE filesystem creates one level of directories from
  415. # the archive names. Thus, we must not accept "/" in archive names.
  416. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  417. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  418. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  419. file_re = re.compile(r'(?P<proto>file)://'
  420. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  421. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  422. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  423. # get the repo from BORG_RE env and the optional archive from param.
  424. # if the syntax requires giving REPOSITORY (see "borg mount"),
  425. # use "::" to let it use the env var.
  426. # if REPOSITORY argument is optional, it'll automatically use the env.
  427. env_re = re.compile(r'(?:::(?P<archive>[^/]+)?)?$')
  428. def __init__(self, text=''):
  429. self.orig = text
  430. if not self.parse(self.orig):
  431. raise ValueError
  432. def parse(self, text):
  433. valid = self._parse(text)
  434. if valid:
  435. return True
  436. m = self.env_re.match(text)
  437. if not m:
  438. return False
  439. repo = os.environ.get('BORG_REPO')
  440. if repo is None:
  441. return False
  442. valid = self._parse(repo)
  443. if not valid:
  444. return False
  445. self.archive = m.group('archive')
  446. return True
  447. def _parse(self, text):
  448. m = self.ssh_re.match(text)
  449. if m:
  450. self.proto = m.group('proto')
  451. self.user = m.group('user')
  452. self.host = m.group('host')
  453. self.port = m.group('port') and int(m.group('port')) or None
  454. self.path = m.group('path')
  455. self.archive = m.group('archive')
  456. return True
  457. m = self.file_re.match(text)
  458. if m:
  459. self.proto = m.group('proto')
  460. self.path = m.group('path')
  461. self.archive = m.group('archive')
  462. return True
  463. m = self.scp_re.match(text)
  464. if m:
  465. self.user = m.group('user')
  466. self.host = m.group('host')
  467. self.path = m.group('path')
  468. self.archive = m.group('archive')
  469. self.proto = self.host and 'ssh' or 'file'
  470. return True
  471. return False
  472. def __str__(self):
  473. items = []
  474. items.append('proto=%r' % self.proto)
  475. items.append('user=%r' % self.user)
  476. items.append('host=%r' % self.host)
  477. items.append('port=%r' % self.port)
  478. items.append('path=%r' % self.path)
  479. items.append('archive=%r' % self.archive)
  480. return ', '.join(items)
  481. def to_key_filename(self):
  482. name = re.sub('[^\w]', '_', self.path).strip('_')
  483. if self.proto != 'file':
  484. name = self.host + '__' + name
  485. return os.path.join(get_keys_dir(), name)
  486. def __repr__(self):
  487. return "Location(%s)" % self
  488. def canonical_path(self):
  489. if self.proto == 'file':
  490. return self.path
  491. else:
  492. if self.path and self.path.startswith('~'):
  493. path = '/' + self.path
  494. elif self.path and not self.path.startswith('/'):
  495. path = '/~/' + self.path
  496. else:
  497. path = self.path
  498. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  499. self.host,
  500. ':{}'.format(self.port) if self.port else '',
  501. path)
  502. def location_validator(archive=None):
  503. def validator(text):
  504. try:
  505. loc = Location(text)
  506. except ValueError:
  507. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  508. if archive is True and not loc.archive:
  509. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  510. elif archive is False and loc.archive:
  511. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  512. return loc
  513. return validator
  514. def read_msgpack(filename):
  515. with open(filename, 'rb') as fd:
  516. return msgpack.unpack(fd)
  517. def write_msgpack(filename, d):
  518. with open(filename + '.tmp', 'wb') as fd:
  519. msgpack.pack(d, fd)
  520. fd.flush()
  521. os.fsync(fd.fileno())
  522. os.rename(filename + '.tmp', filename)
  523. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  524. for key in keys:
  525. if isinstance(d.get(key), bytes):
  526. d[key] = d[key].decode(encoding, errors)
  527. return d
  528. def remove_surrogates(s, errors='replace'):
  529. """Replace surrogates generated by fsdecode with '?'
  530. """
  531. return s.encode('utf-8', errors).decode('utf-8')
  532. _safe_re = re.compile(r'^((\.\.)?/+)+')
  533. def make_path_safe(path):
  534. """Make path safe by making it relative and local
  535. """
  536. return _safe_re.sub('', path) or '.'
  537. def daemonize():
  538. """Detach process from controlling terminal and run in background
  539. """
  540. pid = os.fork()
  541. if pid:
  542. os._exit(0)
  543. os.setsid()
  544. pid = os.fork()
  545. if pid:
  546. os._exit(0)
  547. os.chdir('/')
  548. os.close(0)
  549. os.close(1)
  550. os.close(2)
  551. fd = os.open('/dev/null', os.O_RDWR)
  552. os.dup2(fd, 0)
  553. os.dup2(fd, 1)
  554. os.dup2(fd, 2)
  555. class StableDict(dict):
  556. """A dict subclass with stable items() ordering"""
  557. def items(self):
  558. return sorted(super().items())
  559. if sys.version < '3.3':
  560. # st_mtime_ns attribute only available in 3.3+
  561. def st_mtime_ns(st):
  562. return int(st.st_mtime * 1e9)
  563. # unhexlify in < 3.3 incorrectly only accepts bytes input
  564. def unhexlify(data):
  565. if isinstance(data, str):
  566. data = data.encode('ascii')
  567. return binascii.unhexlify(data)
  568. else:
  569. def st_mtime_ns(st):
  570. return st.st_mtime_ns
  571. unhexlify = binascii.unhexlify
  572. def bigint_to_int(mtime):
  573. """Convert bytearray to int
  574. """
  575. if isinstance(mtime, bytes):
  576. return int.from_bytes(mtime, 'little', signed=True)
  577. return mtime
  578. def int_to_bigint(value):
  579. """Convert integers larger than 64 bits to bytearray
  580. Smaller integers are left alone
  581. """
  582. if value.bit_length() > 63:
  583. return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
  584. return value