helpers.py 22 KB

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