helpers.py 22 KB

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