PageRenderTime 78ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/mercurial/util.py

https://bitbucket.org/timeless/mercurial-crew
Python | 3556 lines | 3342 code | 84 blank | 130 comment | 95 complexity | 647fc82108eaf3870e819e29536c6de8 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause
  1. # util.py - Mercurial utility functions and platform specific implementations
  2. #
  3. # Copyright 2005 K. Thananchayan <thananck@yahoo.com>
  4. # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
  5. # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
  6. #
  7. # This software may be used and distributed according to the terms of the
  8. # GNU General Public License version 2 or any later version.
  9. """Mercurial utility functions and platform specific implementations.
  10. This contains helper routines that are independent of the SCM core and
  11. hide platform-specific details from the core.
  12. """
  13. from __future__ import absolute_import
  14. import bz2
  15. import calendar
  16. import collections
  17. import datetime
  18. import errno
  19. import gc
  20. import hashlib
  21. import imp
  22. import os
  23. import platform as pyplatform
  24. import re as remod
  25. import shutil
  26. import signal
  27. import socket
  28. import stat
  29. import string
  30. import subprocess
  31. import sys
  32. import tempfile
  33. import textwrap
  34. import time
  35. import traceback
  36. import zlib
  37. from . import (
  38. encoding,
  39. error,
  40. i18n,
  41. osutil,
  42. parsers,
  43. pycompat,
  44. )
  45. empty = pycompat.empty
  46. httplib = pycompat.httplib
  47. httpserver = pycompat.httpserver
  48. pickle = pycompat.pickle
  49. queue = pycompat.queue
  50. socketserver = pycompat.socketserver
  51. stderr = pycompat.stderr
  52. stdin = pycompat.stdin
  53. stdout = pycompat.stdout
  54. stringio = pycompat.stringio
  55. urlerr = pycompat.urlerr
  56. urlparse = pycompat.urlparse
  57. urlreq = pycompat.urlreq
  58. xmlrpclib = pycompat.xmlrpclib
  59. def isatty(fp):
  60. try:
  61. return fp.isatty()
  62. except AttributeError:
  63. return False
  64. # glibc determines buffering on first write to stdout - if we replace a TTY
  65. # destined stdout with a pipe destined stdout (e.g. pager), we want line
  66. # buffering
  67. if isatty(stdout):
  68. stdout = os.fdopen(stdout.fileno(), pycompat.sysstr('wb'), 1)
  69. if pycompat.osname == 'nt':
  70. from . import windows as platform
  71. stdout = platform.winstdout(stdout)
  72. else:
  73. from . import posix as platform
  74. _ = i18n._
  75. bindunixsocket = platform.bindunixsocket
  76. cachestat = platform.cachestat
  77. checkexec = platform.checkexec
  78. checklink = platform.checklink
  79. copymode = platform.copymode
  80. executablepath = platform.executablepath
  81. expandglobs = platform.expandglobs
  82. explainexit = platform.explainexit
  83. findexe = platform.findexe
  84. gethgcmd = platform.gethgcmd
  85. getuser = platform.getuser
  86. getpid = os.getpid
  87. groupmembers = platform.groupmembers
  88. groupname = platform.groupname
  89. hidewindow = platform.hidewindow
  90. isexec = platform.isexec
  91. isowner = platform.isowner
  92. localpath = platform.localpath
  93. lookupreg = platform.lookupreg
  94. makedir = platform.makedir
  95. nlinks = platform.nlinks
  96. normpath = platform.normpath
  97. normcase = platform.normcase
  98. normcasespec = platform.normcasespec
  99. normcasefallback = platform.normcasefallback
  100. openhardlinks = platform.openhardlinks
  101. oslink = platform.oslink
  102. parsepatchoutput = platform.parsepatchoutput
  103. pconvert = platform.pconvert
  104. poll = platform.poll
  105. popen = platform.popen
  106. posixfile = platform.posixfile
  107. quotecommand = platform.quotecommand
  108. readpipe = platform.readpipe
  109. rename = platform.rename
  110. removedirs = platform.removedirs
  111. samedevice = platform.samedevice
  112. samefile = platform.samefile
  113. samestat = platform.samestat
  114. setbinary = platform.setbinary
  115. setflags = platform.setflags
  116. setsignalhandler = platform.setsignalhandler
  117. shellquote = platform.shellquote
  118. spawndetached = platform.spawndetached
  119. split = platform.split
  120. sshargs = platform.sshargs
  121. statfiles = getattr(osutil, 'statfiles', platform.statfiles)
  122. statisexec = platform.statisexec
  123. statislink = platform.statislink
  124. testpid = platform.testpid
  125. umask = platform.umask
  126. unlink = platform.unlink
  127. unlinkpath = platform.unlinkpath
  128. username = platform.username
  129. # Python compatibility
  130. _notset = object()
  131. # disable Python's problematic floating point timestamps (issue4836)
  132. # (Python hypocritically says you shouldn't change this behavior in
  133. # libraries, and sure enough Mercurial is not a library.)
  134. os.stat_float_times(False)
  135. def safehasattr(thing, attr):
  136. return getattr(thing, attr, _notset) is not _notset
  137. def bitsfrom(container):
  138. bits = 0
  139. for bit in container:
  140. bits |= bit
  141. return bits
  142. DIGESTS = {
  143. 'md5': hashlib.md5,
  144. 'sha1': hashlib.sha1,
  145. 'sha512': hashlib.sha512,
  146. }
  147. # List of digest types from strongest to weakest
  148. DIGESTS_BY_STRENGTH = ['sha512', 'sha1', 'md5']
  149. for k in DIGESTS_BY_STRENGTH:
  150. assert k in DIGESTS
  151. class digester(object):
  152. """helper to compute digests.
  153. This helper can be used to compute one or more digests given their name.
  154. >>> d = digester(['md5', 'sha1'])
  155. >>> d.update('foo')
  156. >>> [k for k in sorted(d)]
  157. ['md5', 'sha1']
  158. >>> d['md5']
  159. 'acbd18db4cc2f85cedef654fccc4a4d8'
  160. >>> d['sha1']
  161. '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'
  162. >>> digester.preferred(['md5', 'sha1'])
  163. 'sha1'
  164. """
  165. def __init__(self, digests, s=''):
  166. self._hashes = {}
  167. for k in digests:
  168. if k not in DIGESTS:
  169. raise Abort(_('unknown digest type: %s') % k)
  170. self._hashes[k] = DIGESTS[k]()
  171. if s:
  172. self.update(s)
  173. def update(self, data):
  174. for h in self._hashes.values():
  175. h.update(data)
  176. def __getitem__(self, key):
  177. if key not in DIGESTS:
  178. raise Abort(_('unknown digest type: %s') % k)
  179. return self._hashes[key].hexdigest()
  180. def __iter__(self):
  181. return iter(self._hashes)
  182. @staticmethod
  183. def preferred(supported):
  184. """returns the strongest digest type in both supported and DIGESTS."""
  185. for k in DIGESTS_BY_STRENGTH:
  186. if k in supported:
  187. return k
  188. return None
  189. class digestchecker(object):
  190. """file handle wrapper that additionally checks content against a given
  191. size and digests.
  192. d = digestchecker(fh, size, {'md5': '...'})
  193. When multiple digests are given, all of them are validated.
  194. """
  195. def __init__(self, fh, size, digests):
  196. self._fh = fh
  197. self._size = size
  198. self._got = 0
  199. self._digests = dict(digests)
  200. self._digester = digester(self._digests.keys())
  201. def read(self, length=-1):
  202. content = self._fh.read(length)
  203. self._digester.update(content)
  204. self._got += len(content)
  205. return content
  206. def validate(self):
  207. if self._size != self._got:
  208. raise Abort(_('size mismatch: expected %d, got %d') %
  209. (self._size, self._got))
  210. for k, v in self._digests.items():
  211. if v != self._digester[k]:
  212. # i18n: first parameter is a digest name
  213. raise Abort(_('%s mismatch: expected %s, got %s') %
  214. (k, v, self._digester[k]))
  215. try:
  216. buffer = buffer
  217. except NameError:
  218. if not pycompat.ispy3:
  219. def buffer(sliceable, offset=0, length=None):
  220. if length is not None:
  221. return sliceable[offset:offset + length]
  222. return sliceable[offset:]
  223. else:
  224. def buffer(sliceable, offset=0, length=None):
  225. if length is not None:
  226. return memoryview(sliceable)[offset:offset + length]
  227. return memoryview(sliceable)[offset:]
  228. closefds = pycompat.osname == 'posix'
  229. _chunksize = 4096
  230. class bufferedinputpipe(object):
  231. """a manually buffered input pipe
  232. Python will not let us use buffered IO and lazy reading with 'polling' at
  233. the same time. We cannot probe the buffer state and select will not detect
  234. that data are ready to read if they are already buffered.
  235. This class let us work around that by implementing its own buffering
  236. (allowing efficient readline) while offering a way to know if the buffer is
  237. empty from the output (allowing collaboration of the buffer with polling).
  238. This class lives in the 'util' module because it makes use of the 'os'
  239. module from the python stdlib.
  240. """
  241. def __init__(self, input):
  242. self._input = input
  243. self._buffer = []
  244. self._eof = False
  245. self._lenbuf = 0
  246. @property
  247. def hasbuffer(self):
  248. """True is any data is currently buffered
  249. This will be used externally a pre-step for polling IO. If there is
  250. already data then no polling should be set in place."""
  251. return bool(self._buffer)
  252. @property
  253. def closed(self):
  254. return self._input.closed
  255. def fileno(self):
  256. return self._input.fileno()
  257. def close(self):
  258. return self._input.close()
  259. def read(self, size):
  260. while (not self._eof) and (self._lenbuf < size):
  261. self._fillbuffer()
  262. return self._frombuffer(size)
  263. def readline(self, *args, **kwargs):
  264. if 1 < len(self._buffer):
  265. # this should not happen because both read and readline end with a
  266. # _frombuffer call that collapse it.
  267. self._buffer = [''.join(self._buffer)]
  268. self._lenbuf = len(self._buffer[0])
  269. lfi = -1
  270. if self._buffer:
  271. lfi = self._buffer[-1].find('\n')
  272. while (not self._eof) and lfi < 0:
  273. self._fillbuffer()
  274. if self._buffer:
  275. lfi = self._buffer[-1].find('\n')
  276. size = lfi + 1
  277. if lfi < 0: # end of file
  278. size = self._lenbuf
  279. elif 1 < len(self._buffer):
  280. # we need to take previous chunks into account
  281. size += self._lenbuf - len(self._buffer[-1])
  282. return self._frombuffer(size)
  283. def _frombuffer(self, size):
  284. """return at most 'size' data from the buffer
  285. The data are removed from the buffer."""
  286. if size == 0 or not self._buffer:
  287. return ''
  288. buf = self._buffer[0]
  289. if 1 < len(self._buffer):
  290. buf = ''.join(self._buffer)
  291. data = buf[:size]
  292. buf = buf[len(data):]
  293. if buf:
  294. self._buffer = [buf]
  295. self._lenbuf = len(buf)
  296. else:
  297. self._buffer = []
  298. self._lenbuf = 0
  299. return data
  300. def _fillbuffer(self):
  301. """read data to the buffer"""
  302. data = os.read(self._input.fileno(), _chunksize)
  303. if not data:
  304. self._eof = True
  305. else:
  306. self._lenbuf += len(data)
  307. self._buffer.append(data)
  308. def popen2(cmd, env=None, newlines=False):
  309. # Setting bufsize to -1 lets the system decide the buffer size.
  310. # The default for bufsize is 0, meaning unbuffered. This leads to
  311. # poor performance on Mac OS X: http://bugs.python.org/issue4194
  312. p = subprocess.Popen(cmd, shell=True, bufsize=-1,
  313. close_fds=closefds,
  314. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  315. universal_newlines=newlines,
  316. env=env)
  317. return p.stdin, p.stdout
  318. def popen3(cmd, env=None, newlines=False):
  319. stdin, stdout, stderr, p = popen4(cmd, env, newlines)
  320. return stdin, stdout, stderr
  321. def popen4(cmd, env=None, newlines=False, bufsize=-1):
  322. p = subprocess.Popen(cmd, shell=True, bufsize=bufsize,
  323. close_fds=closefds,
  324. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  325. stderr=subprocess.PIPE,
  326. universal_newlines=newlines,
  327. env=env)
  328. return p.stdin, p.stdout, p.stderr, p
  329. def version():
  330. """Return version information if available."""
  331. try:
  332. from . import __version__
  333. return __version__.version
  334. except ImportError:
  335. return 'unknown'
  336. def versiontuple(v=None, n=4):
  337. """Parses a Mercurial version string into an N-tuple.
  338. The version string to be parsed is specified with the ``v`` argument.
  339. If it isn't defined, the current Mercurial version string will be parsed.
  340. ``n`` can be 2, 3, or 4. Here is how some version strings map to
  341. returned values:
  342. >>> v = '3.6.1+190-df9b73d2d444'
  343. >>> versiontuple(v, 2)
  344. (3, 6)
  345. >>> versiontuple(v, 3)
  346. (3, 6, 1)
  347. >>> versiontuple(v, 4)
  348. (3, 6, 1, '190-df9b73d2d444')
  349. >>> versiontuple('3.6.1+190-df9b73d2d444+20151118')
  350. (3, 6, 1, '190-df9b73d2d444+20151118')
  351. >>> v = '3.6'
  352. >>> versiontuple(v, 2)
  353. (3, 6)
  354. >>> versiontuple(v, 3)
  355. (3, 6, None)
  356. >>> versiontuple(v, 4)
  357. (3, 6, None, None)
  358. >>> v = '3.9-rc'
  359. >>> versiontuple(v, 2)
  360. (3, 9)
  361. >>> versiontuple(v, 3)
  362. (3, 9, None)
  363. >>> versiontuple(v, 4)
  364. (3, 9, None, 'rc')
  365. >>> v = '3.9-rc+2-02a8fea4289b'
  366. >>> versiontuple(v, 2)
  367. (3, 9)
  368. >>> versiontuple(v, 3)
  369. (3, 9, None)
  370. >>> versiontuple(v, 4)
  371. (3, 9, None, 'rc+2-02a8fea4289b')
  372. """
  373. if not v:
  374. v = version()
  375. parts = remod.split('[\+-]', v, 1)
  376. if len(parts) == 1:
  377. vparts, extra = parts[0], None
  378. else:
  379. vparts, extra = parts
  380. vints = []
  381. for i in vparts.split('.'):
  382. try:
  383. vints.append(int(i))
  384. except ValueError:
  385. break
  386. # (3, 6) -> (3, 6, None)
  387. while len(vints) < 3:
  388. vints.append(None)
  389. if n == 2:
  390. return (vints[0], vints[1])
  391. if n == 3:
  392. return (vints[0], vints[1], vints[2])
  393. if n == 4:
  394. return (vints[0], vints[1], vints[2], extra)
  395. # used by parsedate
  396. defaultdateformats = (
  397. '%Y-%m-%dT%H:%M:%S', # the 'real' ISO8601
  398. '%Y-%m-%dT%H:%M', # without seconds
  399. '%Y-%m-%dT%H%M%S', # another awful but legal variant without :
  400. '%Y-%m-%dT%H%M', # without seconds
  401. '%Y-%m-%d %H:%M:%S', # our common legal variant
  402. '%Y-%m-%d %H:%M', # without seconds
  403. '%Y-%m-%d %H%M%S', # without :
  404. '%Y-%m-%d %H%M', # without seconds
  405. '%Y-%m-%d %I:%M:%S%p',
  406. '%Y-%m-%d %H:%M',
  407. '%Y-%m-%d %I:%M%p',
  408. '%Y-%m-%d',
  409. '%m-%d',
  410. '%m/%d',
  411. '%m/%d/%y',
  412. '%m/%d/%Y',
  413. '%a %b %d %H:%M:%S %Y',
  414. '%a %b %d %I:%M:%S%p %Y',
  415. '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
  416. '%b %d %H:%M:%S %Y',
  417. '%b %d %I:%M:%S%p %Y',
  418. '%b %d %H:%M:%S',
  419. '%b %d %I:%M:%S%p',
  420. '%b %d %H:%M',
  421. '%b %d %I:%M%p',
  422. '%b %d %Y',
  423. '%b %d',
  424. '%H:%M:%S',
  425. '%I:%M:%S%p',
  426. '%H:%M',
  427. '%I:%M%p',
  428. )
  429. extendeddateformats = defaultdateformats + (
  430. "%Y",
  431. "%Y-%m",
  432. "%b",
  433. "%b %Y",
  434. )
  435. def cachefunc(func):
  436. '''cache the result of function calls'''
  437. # XXX doesn't handle keywords args
  438. if func.__code__.co_argcount == 0:
  439. cache = []
  440. def f():
  441. if len(cache) == 0:
  442. cache.append(func())
  443. return cache[0]
  444. return f
  445. cache = {}
  446. if func.__code__.co_argcount == 1:
  447. # we gain a small amount of time because
  448. # we don't need to pack/unpack the list
  449. def f(arg):
  450. if arg not in cache:
  451. cache[arg] = func(arg)
  452. return cache[arg]
  453. else:
  454. def f(*args):
  455. if args not in cache:
  456. cache[args] = func(*args)
  457. return cache[args]
  458. return f
  459. class sortdict(dict):
  460. '''a simple sorted dictionary'''
  461. def __init__(self, data=None):
  462. self._list = []
  463. if data:
  464. self.update(data)
  465. def copy(self):
  466. return sortdict(self)
  467. def __setitem__(self, key, val):
  468. if key in self:
  469. self._list.remove(key)
  470. self._list.append(key)
  471. dict.__setitem__(self, key, val)
  472. def __iter__(self):
  473. return self._list.__iter__()
  474. def update(self, src):
  475. if isinstance(src, dict):
  476. src = src.iteritems()
  477. for k, v in src:
  478. self[k] = v
  479. def clear(self):
  480. dict.clear(self)
  481. self._list = []
  482. def items(self):
  483. return [(k, self[k]) for k in self._list]
  484. def __delitem__(self, key):
  485. dict.__delitem__(self, key)
  486. self._list.remove(key)
  487. def pop(self, key, *args, **kwargs):
  488. dict.pop(self, key, *args, **kwargs)
  489. try:
  490. self._list.remove(key)
  491. except ValueError:
  492. pass
  493. def keys(self):
  494. return self._list[:]
  495. def iterkeys(self):
  496. return self._list.__iter__()
  497. def iteritems(self):
  498. for k in self._list:
  499. yield k, self[k]
  500. def insert(self, index, key, val):
  501. self._list.insert(index, key)
  502. dict.__setitem__(self, key, val)
  503. def __repr__(self):
  504. if not self:
  505. return '%s()' % self.__class__.__name__
  506. return '%s(%r)' % (self.__class__.__name__, self.items())
  507. class _lrucachenode(object):
  508. """A node in a doubly linked list.
  509. Holds a reference to nodes on either side as well as a key-value
  510. pair for the dictionary entry.
  511. """
  512. __slots__ = (u'next', u'prev', u'key', u'value')
  513. def __init__(self):
  514. self.next = None
  515. self.prev = None
  516. self.key = _notset
  517. self.value = None
  518. def markempty(self):
  519. """Mark the node as emptied."""
  520. self.key = _notset
  521. class lrucachedict(object):
  522. """Dict that caches most recent accesses and sets.
  523. The dict consists of an actual backing dict - indexed by original
  524. key - and a doubly linked circular list defining the order of entries in
  525. the cache.
  526. The head node is the newest entry in the cache. If the cache is full,
  527. we recycle head.prev and make it the new head. Cache accesses result in
  528. the node being moved to before the existing head and being marked as the
  529. new head node.
  530. """
  531. def __init__(self, max):
  532. self._cache = {}
  533. self._head = head = _lrucachenode()
  534. head.prev = head
  535. head.next = head
  536. self._size = 1
  537. self._capacity = max
  538. def __len__(self):
  539. return len(self._cache)
  540. def __contains__(self, k):
  541. return k in self._cache
  542. def __iter__(self):
  543. # We don't have to iterate in cache order, but why not.
  544. n = self._head
  545. for i in range(len(self._cache)):
  546. yield n.key
  547. n = n.next
  548. def __getitem__(self, k):
  549. node = self._cache[k]
  550. self._movetohead(node)
  551. return node.value
  552. def __setitem__(self, k, v):
  553. node = self._cache.get(k)
  554. # Replace existing value and mark as newest.
  555. if node is not None:
  556. node.value = v
  557. self._movetohead(node)
  558. return
  559. if self._size < self._capacity:
  560. node = self._addcapacity()
  561. else:
  562. # Grab the last/oldest item.
  563. node = self._head.prev
  564. # At capacity. Kill the old entry.
  565. if node.key is not _notset:
  566. del self._cache[node.key]
  567. node.key = k
  568. node.value = v
  569. self._cache[k] = node
  570. # And mark it as newest entry. No need to adjust order since it
  571. # is already self._head.prev.
  572. self._head = node
  573. def __delitem__(self, k):
  574. node = self._cache.pop(k)
  575. node.markempty()
  576. # Temporarily mark as newest item before re-adjusting head to make
  577. # this node the oldest item.
  578. self._movetohead(node)
  579. self._head = node.next
  580. # Additional dict methods.
  581. def get(self, k, default=None):
  582. try:
  583. return self._cache[k].value
  584. except KeyError:
  585. return default
  586. def clear(self):
  587. n = self._head
  588. while n.key is not _notset:
  589. n.markempty()
  590. n = n.next
  591. self._cache.clear()
  592. def copy(self):
  593. result = lrucachedict(self._capacity)
  594. n = self._head.prev
  595. # Iterate in oldest-to-newest order, so the copy has the right ordering
  596. for i in range(len(self._cache)):
  597. result[n.key] = n.value
  598. n = n.prev
  599. return result
  600. def _movetohead(self, node):
  601. """Mark a node as the newest, making it the new head.
  602. When a node is accessed, it becomes the freshest entry in the LRU
  603. list, which is denoted by self._head.
  604. Visually, let's make ``N`` the new head node (* denotes head):
  605. previous/oldest <-> head <-> next/next newest
  606. ----<->--- A* ---<->-----
  607. | |
  608. E <-> D <-> N <-> C <-> B
  609. To:
  610. ----<->--- N* ---<->-----
  611. | |
  612. E <-> D <-> C <-> B <-> A
  613. This requires the following moves:
  614. C.next = D (node.prev.next = node.next)
  615. D.prev = C (node.next.prev = node.prev)
  616. E.next = N (head.prev.next = node)
  617. N.prev = E (node.prev = head.prev)
  618. N.next = A (node.next = head)
  619. A.prev = N (head.prev = node)
  620. """
  621. head = self._head
  622. # C.next = D
  623. node.prev.next = node.next
  624. # D.prev = C
  625. node.next.prev = node.prev
  626. # N.prev = E
  627. node.prev = head.prev
  628. # N.next = A
  629. # It is tempting to do just "head" here, however if node is
  630. # adjacent to head, this will do bad things.
  631. node.next = head.prev.next
  632. # E.next = N
  633. node.next.prev = node
  634. # A.prev = N
  635. node.prev.next = node
  636. self._head = node
  637. def _addcapacity(self):
  638. """Add a node to the circular linked list.
  639. The new node is inserted before the head node.
  640. """
  641. head = self._head
  642. node = _lrucachenode()
  643. head.prev.next = node
  644. node.prev = head.prev
  645. node.next = head
  646. head.prev = node
  647. self._size += 1
  648. return node
  649. def lrucachefunc(func):
  650. '''cache most recent results of function calls'''
  651. cache = {}
  652. order = collections.deque()
  653. if func.__code__.co_argcount == 1:
  654. def f(arg):
  655. if arg not in cache:
  656. if len(cache) > 20:
  657. del cache[order.popleft()]
  658. cache[arg] = func(arg)
  659. else:
  660. order.remove(arg)
  661. order.append(arg)
  662. return cache[arg]
  663. else:
  664. def f(*args):
  665. if args not in cache:
  666. if len(cache) > 20:
  667. del cache[order.popleft()]
  668. cache[args] = func(*args)
  669. else:
  670. order.remove(args)
  671. order.append(args)
  672. return cache[args]
  673. return f
  674. class propertycache(object):
  675. def __init__(self, func):
  676. self.func = func
  677. self.name = func.__name__
  678. def __get__(self, obj, type=None):
  679. result = self.func(obj)
  680. self.cachevalue(obj, result)
  681. return result
  682. def cachevalue(self, obj, value):
  683. # __dict__ assignment required to bypass __setattr__ (eg: repoview)
  684. obj.__dict__[self.name] = value
  685. def pipefilter(s, cmd):
  686. '''filter string S through command CMD, returning its output'''
  687. p = subprocess.Popen(cmd, shell=True, close_fds=closefds,
  688. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  689. pout, perr = p.communicate(s)
  690. return pout
  691. def tempfilter(s, cmd):
  692. '''filter string S through a pair of temporary files with CMD.
  693. CMD is used as a template to create the real command to be run,
  694. with the strings INFILE and OUTFILE replaced by the real names of
  695. the temporary files generated.'''
  696. inname, outname = None, None
  697. try:
  698. infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
  699. fp = os.fdopen(infd, pycompat.sysstr('wb'))
  700. fp.write(s)
  701. fp.close()
  702. outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
  703. os.close(outfd)
  704. cmd = cmd.replace('INFILE', inname)
  705. cmd = cmd.replace('OUTFILE', outname)
  706. code = os.system(cmd)
  707. if pycompat.sysplatform == 'OpenVMS' and code & 1:
  708. code = 0
  709. if code:
  710. raise Abort(_("command '%s' failed: %s") %
  711. (cmd, explainexit(code)))
  712. return readfile(outname)
  713. finally:
  714. try:
  715. if inname:
  716. os.unlink(inname)
  717. except OSError:
  718. pass
  719. try:
  720. if outname:
  721. os.unlink(outname)
  722. except OSError:
  723. pass
  724. filtertable = {
  725. 'tempfile:': tempfilter,
  726. 'pipe:': pipefilter,
  727. }
  728. def filter(s, cmd):
  729. "filter a string through a command that transforms its input to its output"
  730. for name, fn in filtertable.iteritems():
  731. if cmd.startswith(name):
  732. return fn(s, cmd[len(name):].lstrip())
  733. return pipefilter(s, cmd)
  734. def binary(s):
  735. """return true if a string is binary data"""
  736. return bool(s and '\0' in s)
  737. def increasingchunks(source, min=1024, max=65536):
  738. '''return no less than min bytes per chunk while data remains,
  739. doubling min after each chunk until it reaches max'''
  740. def log2(x):
  741. if not x:
  742. return 0
  743. i = 0
  744. while x:
  745. x >>= 1
  746. i += 1
  747. return i - 1
  748. buf = []
  749. blen = 0
  750. for chunk in source:
  751. buf.append(chunk)
  752. blen += len(chunk)
  753. if blen >= min:
  754. if min < max:
  755. min = min << 1
  756. nmin = 1 << log2(blen)
  757. if nmin > min:
  758. min = nmin
  759. if min > max:
  760. min = max
  761. yield ''.join(buf)
  762. blen = 0
  763. buf = []
  764. if buf:
  765. yield ''.join(buf)
  766. Abort = error.Abort
  767. def always(fn):
  768. return True
  769. def never(fn):
  770. return False
  771. def nogc(func):
  772. """disable garbage collector
  773. Python's garbage collector triggers a GC each time a certain number of
  774. container objects (the number being defined by gc.get_threshold()) are
  775. allocated even when marked not to be tracked by the collector. Tracking has
  776. no effect on when GCs are triggered, only on what objects the GC looks
  777. into. As a workaround, disable GC while building complex (huge)
  778. containers.
  779. This garbage collector issue have been fixed in 2.7.
  780. """
  781. if sys.version_info >= (2, 7):
  782. return func
  783. def wrapper(*args, **kwargs):
  784. gcenabled = gc.isenabled()
  785. gc.disable()
  786. try:
  787. return func(*args, **kwargs)
  788. finally:
  789. if gcenabled:
  790. gc.enable()
  791. return wrapper
  792. def pathto(root, n1, n2):
  793. '''return the relative path from one place to another.
  794. root should use os.sep to separate directories
  795. n1 should use os.sep to separate directories
  796. n2 should use "/" to separate directories
  797. returns an os.sep-separated path.
  798. If n1 is a relative path, it's assumed it's
  799. relative to root.
  800. n2 should always be relative to root.
  801. '''
  802. if not n1:
  803. return localpath(n2)
  804. if os.path.isabs(n1):
  805. if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
  806. return os.path.join(root, localpath(n2))
  807. n2 = '/'.join((pconvert(root), n2))
  808. a, b = splitpath(n1), n2.split('/')
  809. a.reverse()
  810. b.reverse()
  811. while a and b and a[-1] == b[-1]:
  812. a.pop()
  813. b.pop()
  814. b.reverse()
  815. return pycompat.ossep.join((['..'] * len(a)) + b) or '.'
  816. def mainfrozen():
  817. """return True if we are a frozen executable.
  818. The code supports py2exe (most common, Windows only) and tools/freeze
  819. (portable, not much used).
  820. """
  821. return (safehasattr(sys, "frozen") or # new py2exe
  822. safehasattr(sys, "importers") or # old py2exe
  823. imp.is_frozen(u"__main__")) # tools/freeze
  824. # the location of data files matching the source code
  825. if mainfrozen() and getattr(sys, 'frozen', None) != 'macosx_app':
  826. # executable version (py2exe) doesn't support __file__
  827. datapath = os.path.dirname(pycompat.sysexecutable)
  828. else:
  829. datapath = os.path.dirname(__file__)
  830. if not isinstance(datapath, bytes):
  831. datapath = pycompat.fsencode(datapath)
  832. i18n.setdatapath(datapath)
  833. _hgexecutable = None
  834. def hgexecutable():
  835. """return location of the 'hg' executable.
  836. Defaults to $HG or 'hg' in the search path.
  837. """
  838. if _hgexecutable is None:
  839. hg = encoding.environ.get('HG')
  840. mainmod = sys.modules['__main__']
  841. if hg:
  842. _sethgexecutable(hg)
  843. elif mainfrozen():
  844. if getattr(sys, 'frozen', None) == 'macosx_app':
  845. # Env variable set by py2app
  846. _sethgexecutable(encoding.environ['EXECUTABLEPATH'])
  847. else:
  848. _sethgexecutable(pycompat.sysexecutable)
  849. elif os.path.basename(getattr(mainmod, '__file__', '')) == 'hg':
  850. _sethgexecutable(mainmod.__file__)
  851. else:
  852. exe = findexe('hg') or os.path.basename(sys.argv[0])
  853. _sethgexecutable(exe)
  854. return _hgexecutable
  855. def _sethgexecutable(path):
  856. """set location of the 'hg' executable"""
  857. global _hgexecutable
  858. _hgexecutable = path
  859. def _isstdout(f):
  860. fileno = getattr(f, 'fileno', None)
  861. return fileno and fileno() == sys.__stdout__.fileno()
  862. def shellenviron(environ=None):
  863. """return environ with optional override, useful for shelling out"""
  864. def py2shell(val):
  865. 'convert python object into string that is useful to shell'
  866. if val is None or val is False:
  867. return '0'
  868. if val is True:
  869. return '1'
  870. return str(val)
  871. env = dict(encoding.environ)
  872. if environ:
  873. env.update((k, py2shell(v)) for k, v in environ.iteritems())
  874. env['HG'] = hgexecutable()
  875. return env
  876. def system(cmd, environ=None, cwd=None, onerr=None, errprefix=None, out=None):
  877. '''enhanced shell command execution.
  878. run with environment maybe modified, maybe in different dir.
  879. if command fails and onerr is None, return status, else raise onerr
  880. object as exception.
  881. if out is specified, it is assumed to be a file-like object that has a
  882. write() method. stdout and stderr will be redirected to out.'''
  883. try:
  884. stdout.flush()
  885. except Exception:
  886. pass
  887. origcmd = cmd
  888. cmd = quotecommand(cmd)
  889. if pycompat.sysplatform == 'plan9' and (sys.version_info[0] == 2
  890. and sys.version_info[1] < 7):
  891. # subprocess kludge to work around issues in half-baked Python
  892. # ports, notably bichued/python:
  893. if not cwd is None:
  894. os.chdir(cwd)
  895. rc = os.system(cmd)
  896. else:
  897. env = shellenviron(environ)
  898. if out is None or _isstdout(out):
  899. rc = subprocess.call(cmd, shell=True, close_fds=closefds,
  900. env=env, cwd=cwd)
  901. else:
  902. proc = subprocess.Popen(cmd, shell=True, close_fds=closefds,
  903. env=env, cwd=cwd, stdout=subprocess.PIPE,
  904. stderr=subprocess.STDOUT)
  905. for line in iter(proc.stdout.readline, ''):
  906. out.write(line)
  907. proc.wait()
  908. rc = proc.returncode
  909. if pycompat.sysplatform == 'OpenVMS' and rc & 1:
  910. rc = 0
  911. if rc and onerr:
  912. errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
  913. explainexit(rc)[0])
  914. if errprefix:
  915. errmsg = '%s: %s' % (errprefix, errmsg)
  916. raise onerr(errmsg)
  917. return rc
  918. def checksignature(func):
  919. '''wrap a function with code to check for calling errors'''
  920. def check(*args, **kwargs):
  921. try:
  922. return func(*args, **kwargs)
  923. except TypeError:
  924. if len(traceback.extract_tb(sys.exc_info()[2])) == 1:
  925. raise error.SignatureError
  926. raise
  927. return check
  928. def copyfile(src, dest, hardlink=False, copystat=False, checkambig=False):
  929. '''copy a file, preserving mode and optionally other stat info like
  930. atime/mtime
  931. checkambig argument is used with filestat, and is useful only if
  932. destination file is guarded by any lock (e.g. repo.lock or
  933. repo.wlock).
  934. copystat and checkambig should be exclusive.
  935. '''
  936. assert not (copystat and checkambig)
  937. oldstat = None
  938. if os.path.lexists(dest):
  939. if checkambig:
  940. oldstat = checkambig and filestat(dest)
  941. unlink(dest)
  942. # hardlinks are problematic on CIFS, quietly ignore this flag
  943. # until we find a way to work around it cleanly (issue4546)
  944. if False and hardlink:
  945. try:
  946. oslink(src, dest)
  947. return
  948. except (IOError, OSError):
  949. pass # fall back to normal copy
  950. if os.path.islink(src):
  951. os.symlink(os.readlink(src), dest)
  952. # copytime is ignored for symlinks, but in general copytime isn't needed
  953. # for them anyway
  954. else:
  955. try:
  956. shutil.copyfile(src, dest)
  957. if copystat:
  958. # copystat also copies mode
  959. shutil.copystat(src, dest)
  960. else:
  961. shutil.copymode(src, dest)
  962. if oldstat and oldstat.stat:
  963. newstat = filestat(dest)
  964. if newstat.isambig(oldstat):
  965. # stat of copied file is ambiguous to original one
  966. advanced = (oldstat.stat.st_mtime + 1) & 0x7fffffff
  967. os.utime(dest, (advanced, advanced))
  968. except shutil.Error as inst:
  969. raise Abort(str(inst))
  970. def copyfiles(src, dst, hardlink=None, progress=lambda t, pos: None):
  971. """Copy a directory tree using hardlinks if possible."""
  972. num = 0
  973. if hardlink is None:
  974. hardlink = (os.stat(src).st_dev ==
  975. os.stat(os.path.dirname(dst)).st_dev)
  976. if hardlink:
  977. topic = _('linking')
  978. else:
  979. topic = _('copying')
  980. if os.path.isdir(src):
  981. os.mkdir(dst)
  982. for name, kind in osutil.listdir(src):
  983. srcname = os.path.join(src, name)
  984. dstname = os.path.join(dst, name)
  985. def nprog(t, pos):
  986. if pos is not None:
  987. return progress(t, pos + num)
  988. hardlink, n = copyfiles(srcname, dstname, hardlink, progress=nprog)
  989. num += n
  990. else:
  991. if hardlink:
  992. try:
  993. oslink(src, dst)
  994. except (IOError, OSError):
  995. hardlink = False
  996. shutil.copy(src, dst)
  997. else:
  998. shutil.copy(src, dst)
  999. num += 1
  1000. progress(topic, num)
  1001. progress(topic, None)
  1002. return hardlink, num
  1003. _winreservednames = '''con prn aux nul
  1004. com1 com2 com3 com4 com5 com6 com7 com8 com9
  1005. lpt1 lpt2 lpt3 lpt4 lpt5 lpt6 lpt7 lpt8 lpt9'''.split()
  1006. _winreservedchars = ':*?"<>|'
  1007. def checkwinfilename(path):
  1008. r'''Check that the base-relative path is a valid filename on Windows.
  1009. Returns None if the path is ok, or a UI string describing the problem.
  1010. >>> checkwinfilename("just/a/normal/path")
  1011. >>> checkwinfilename("foo/bar/con.xml")
  1012. "filename contains 'con', which is reserved on Windows"
  1013. >>> checkwinfilename("foo/con.xml/bar")
  1014. "filename contains 'con', which is reserved on Windows"
  1015. >>> checkwinfilename("foo/bar/xml.con")
  1016. >>> checkwinfilename("foo/bar/AUX/bla.txt")
  1017. "filename contains 'AUX', which is reserved on Windows"
  1018. >>> checkwinfilename("foo/bar/bla:.txt")
  1019. "filename contains ':', which is reserved on Windows"
  1020. >>> checkwinfilename("foo/bar/b\07la.txt")
  1021. "filename contains '\\x07', which is invalid on Windows"
  1022. >>> checkwinfilename("foo/bar/bla ")
  1023. "filename ends with ' ', which is not allowed on Windows"
  1024. >>> checkwinfilename("../bar")
  1025. >>> checkwinfilename("foo\\")
  1026. "filename ends with '\\', which is invalid on Windows"
  1027. >>> checkwinfilename("foo\\/bar")
  1028. "directory name ends with '\\', which is invalid on Windows"
  1029. '''
  1030. if path.endswith('\\'):
  1031. return _("filename ends with '\\', which is invalid on Windows")
  1032. if '\\/' in path:
  1033. return _("directory name ends with '\\', which is invalid on Windows")
  1034. for n in path.replace('\\', '/').split('/'):
  1035. if not n:
  1036. continue
  1037. for c in n:
  1038. if c in _winreservedchars:
  1039. return _("filename contains '%s', which is reserved "
  1040. "on Windows") % c
  1041. if ord(c) <= 31:
  1042. return _("filename contains %r, which is invalid "
  1043. "on Windows") % c
  1044. base = n.split('.')[0]
  1045. if base and base.lower() in _winreservednames:
  1046. return _("filename contains '%s', which is reserved "
  1047. "on Windows") % base
  1048. t = n[-1]
  1049. if t in '. ' and n not in '..':
  1050. return _("filename ends with '%s', which is not allowed "
  1051. "on Windows") % t
  1052. if pycompat.osname == 'nt':
  1053. checkosfilename = checkwinfilename
  1054. timer = time.clock
  1055. else:
  1056. checkosfilename = platform.checkosfilename
  1057. timer = time.time
  1058. if safehasattr(time, "perf_counter"):
  1059. timer = time.perf_counter
  1060. def makelock(info, pathname):
  1061. try:
  1062. return os.symlink(info, pathname)
  1063. except OSError as why:
  1064. if why.errno == errno.EEXIST:
  1065. raise
  1066. except AttributeError: # no symlink in os
  1067. pass
  1068. ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
  1069. os.write(ld, info)
  1070. os.close(ld)
  1071. def readlock(pathname):
  1072. try:
  1073. return os.readlink(pathname)
  1074. except OSError as why:
  1075. if why.errno not in (errno.EINVAL, errno.ENOSYS):
  1076. raise
  1077. except AttributeError: # no symlink in os
  1078. pass
  1079. fp = posixfile(pathname)
  1080. r = fp.read()
  1081. fp.close()
  1082. return r
  1083. def fstat(fp):
  1084. '''stat file object that may not have fileno method.'''
  1085. try:
  1086. return os.fstat(fp.fileno())
  1087. except AttributeError:
  1088. return os.stat(fp.name)
  1089. # File system features
  1090. def fscasesensitive(path):
  1091. """
  1092. Return true if the given path is on a case-sensitive filesystem
  1093. Requires a path (like /foo/.hg) ending with a foldable final
  1094. directory component.
  1095. """
  1096. s1 = os.lstat(path)
  1097. d, b = os.path.split(path)
  1098. b2 = b.upper()
  1099. if b == b2:
  1100. b2 = b.lower()
  1101. if b == b2:
  1102. return True # no evidence against case sensitivity
  1103. p2 = os.path.join(d, b2)
  1104. try:
  1105. s2 = os.lstat(p2)
  1106. if s2 == s1:
  1107. return False
  1108. return True
  1109. except OSError:
  1110. return True
  1111. try:
  1112. import re2
  1113. _re2 = None
  1114. except ImportError:
  1115. _re2 = False
  1116. class _re(object):
  1117. def _checkre2(self):
  1118. global _re2
  1119. try:
  1120. # check if match works, see issue3964
  1121. _re2 = bool(re2.match(r'\[([^\[]+)\]', '[ui]'))
  1122. except ImportError:
  1123. _re2 = False
  1124. def compile(self, pat, flags=0):
  1125. '''Compile a regular expression, using re2 if possible
  1126. For best performance, use only re2-compatible regexp features. The
  1127. only flags from the re module that are re2-compatible are
  1128. IGNORECASE and MULTILINE.'''
  1129. if _re2 is None:
  1130. self._checkre2()
  1131. if _re2 and (flags & ~(remod.IGNORECASE | remod.MULTILINE)) == 0:
  1132. if flags & remod.IGNORECASE:
  1133. pat = '(?i)' + pat
  1134. if flags & remod.MULTILINE:
  1135. pat = '(?m)' + pat
  1136. try:
  1137. return re2.compile(pat)
  1138. except re2.error:
  1139. pass
  1140. return remod.compile(pat, flags)
  1141. @propertycache
  1142. def escape(self):
  1143. '''Return the version of escape corresponding to self.compile.
  1144. This is imperfect because whether re2 or re is used for a particular
  1145. function depends on the flags, etc, but it's the best we can do.
  1146. '''
  1147. global _re2
  1148. if _re2 is None:
  1149. self._checkre2()
  1150. if _re2:
  1151. return re2.escape
  1152. else:
  1153. return remod.escape
  1154. re = _re()
  1155. _fspathcache = {}
  1156. def fspath(name, root):
  1157. '''Get name in the case stored in the filesystem
  1158. The name should be relative to root, and be normcase-ed for efficiency.
  1159. Note that this function is unnecessary, and should not be
  1160. called, for case-sensitive filesystems (simply because it's expensive).
  1161. The root should be normcase-ed, too.
  1162. '''
  1163. def _makefspathcacheentry(dir):
  1164. return dict((normcase(n), n) for n in os.listdir(dir))
  1165. seps = pycompat.ossep
  1166. if pycompat.osaltsep:
  1167. seps = seps + pycompat.osaltsep
  1168. # Protect backslashes. This gets silly very quickly.
  1169. seps.replace('\\','\\\\')
  1170. pattern = remod.compile(r'([^%s]+)|([%s]+)' % (seps, seps))
  1171. dir = os.path.normpath(root)
  1172. result = []
  1173. for part, sep in pattern.findall(name):
  1174. if sep:
  1175. result.append(sep)
  1176. continue
  1177. if dir not in _fspathcache:
  1178. _fspathcache[dir] = _makefspathcacheentry(dir)
  1179. contents = _fspathcache[dir]
  1180. found = contents.get(part)
  1181. if not found:
  1182. # retry "once per directory" per "dirstate.walk" which
  1183. # may take place for each patches of "hg qpush", for example
  1184. _fspathcache[dir] = contents = _makefspathcacheentry(dir)
  1185. found = contents.get(part)
  1186. result.append(found or part)
  1187. dir = os.path.join(dir, part)
  1188. return ''.join(result)
  1189. def checknlink(testfile):
  1190. '''check whether hardlink count reporting works properly'''
  1191. # testfile may be open, so we need a separate file for checking to
  1192. # work around issue2543 (or testfile may get lost on Samba shares)
  1193. f1 = testfile + ".hgtmp1"
  1194. if os.path.lexists(f1):
  1195. return False
  1196. try:
  1197. posixfile(f1, 'w').close()
  1198. except IOError:
  1199. try:
  1200. os.unlink(f1)
  1201. except OSError:
  1202. pass
  1203. return False
  1204. f2 = testfile + ".hgtmp2"
  1205. fd = None
  1206. try:
  1207. oslink(f1, f2)
  1208. # nlinks() may behave differently for files on Windows shares if
  1209. # the file is open.
  1210. fd = posixfile(f2)
  1211. return nlinks(f2) > 1
  1212. except OSError:
  1213. return False
  1214. finally:
  1215. if fd is not None:
  1216. fd.close()
  1217. for f in (f1, f2):
  1218. try:
  1219. os.unlink(f)
  1220. except OSError:
  1221. pass
  1222. def endswithsep(path):
  1223. '''Check path ends with os.sep or os.altsep.'''
  1224. return (path.endswith(pycompat.ossep)
  1225. or pycompat.osaltsep and path.endswith(pycompat.osaltsep))
  1226. def splitpath(path):
  1227. '''Split path by os.sep.
  1228. Note that this function does not use os.altsep because this is
  1229. an alternative of simple "xxx.split(os.sep)".
  1230. It is recommended to use os.path.normpath() before using this
  1231. function if need.'''
  1232. return path.split(pycompat.ossep)
  1233. def gui():
  1234. '''Are we running in a GUI?'''
  1235. if pycompat.sysplatform == 'darwin':
  1236. if 'SSH_CONNECTION' in encoding.environ:
  1237. # handle SSH access to a box where the user is logged in
  1238. return False
  1239. elif getattr(osutil, 'isgui', None):
  1240. # check if a CoreGraphics session is available
  1241. return osutil.isgui()
  1242. else:
  1243. # pure build; use a safe default
  1244. return True
  1245. else:
  1246. return pycompat.osname == "nt" or encoding.environ.get("DISPLAY")
  1247. def mktempcopy(name, emptyok=False, createmode=None):
  1248. """Create a temporary file with the same contents from name
  1249. The permission bits are copied from the original file.
  1250. If the temporary file is going to be truncated immediately, you
  1251. can use emptyok=True as an optimization.
  1252. Returns the name of the temporary file.
  1253. """
  1254. d, fn = os.path.split(name)
  1255. fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
  1256. os.close(fd)
  1257. # Temporary files are created with mode 0600, which is usually not
  1258. # what we want. If the original file already exists, just copy
  1259. # its mode. Otherwise, manually obey umask.
  1260. copymode(name, temp, createmode)
  1261. if emptyok:
  1262. return temp
  1263. try:
  1264. try:
  1265. ifp = posixfile(name, "rb")
  1266. except IOError as inst:
  1267. if inst.errno == errno.ENOENT:
  1268. return temp
  1269. if not getattr(inst, 'filename', None):
  1270. inst.filename = name
  1271. raise
  1272. ofp = posixfile(temp, "wb")
  1273. for chunk in filechunkiter(ifp):
  1274. ofp.write(chunk)
  1275. ifp.close()
  1276. ofp.close()
  1277. except: # re-raises
  1278. try: os.unlink(temp)
  1279. except OSError: pass
  1280. raise
  1281. return temp
  1282. class filestat(object):
  1283. """help to exactly detect change of a file
  1284. 'stat' attribute is result of 'os.stat()' if specified 'path'
  1285. exists. Otherwise, it is None. This can avoid preparative
  1286. 'exists()' examination on client side of this class.
  1287. """
  1288. def __init__(self, path):
  1289. try:
  1290. self.stat = os.stat(path)
  1291. except OSError as err:
  1292. if err.errno != errno.ENOENT:
  1293. raise
  1294. self.stat = None
  1295. __hash__ = object.__hash__
  1296. def __eq__(self, old):
  1297. try:
  1298. # if ambiguity between stat of new and old file is
  1299. # avoided, comparison of size, ctime and mtime is enough
  1300. # to exactly detect change of a file regardless of platform
  1301. return (self.stat.st_size == old.stat.st_size and
  1302. self.stat.st_ctime == old.stat.st_ctime and
  1303. self.stat.st_mtime == old.stat.st_mtime)
  1304. except AttributeError:
  1305. return False
  1306. def isambig(self, old):
  1307. """Examine whether new (= self) stat is ambiguous against old one
  1308. "S[N]" below means stat of a file at N-th change:
  1309. - S[n-1].ctime < S[n].ctime: can detect change of a file
  1310. - S[n-1].ctime == S[n].ctime
  1311. - S[n-1].ctime < S[n].mtime: means natural advancing (*1)
  1312. - S[n-1].ctime == S[n].mtime: is ambiguous (*2)
  1313. - S[n-1].ctime > S[n].mtime: never occurs naturally (don't care)
  1314. - S[n-1].ctime > S[n].ctime: never occurs naturally (don't care)
  1315. Case (*2) above means that a file was changed twice or more at
  1316. same time in sec (= S[n-1].ctime), and comparison of timestamp
  1317. is ambiguous.
  1318. Base idea to avoid such ambiguity is "advance mtime 1 sec, if
  1319. timestamp is ambiguous".
  1320. But advancing mtime only in case (*2) doesn't work as
  1321. expected, because naturally advanced S[n].mtime in case (*1)
  1322. might be equal to manually advanced S[n-1 or earlier].mtime.
  1323. Therefore, all "S[n-1].ctime == S[n].ctime" cases should be
  1324. treated as ambiguous regardless of mtime, to avoid overlooking
  1325. by confliction between such mtime.
  1326. Advancing mtime "if isambig(oldstat)" ensures "S[n-1].mtime !=
  1327. S[n].mtime", even if size of a file isn't changed.
  1328. """
  1329. try:
  1330. return (self.stat.st_ctime == old.stat.st_ctime)
  1331. except AttributeError:
  1332. return False
  1333. def avoidambig(self, path, old):
  1334. """Change file stat of specified path to avoid ambiguity
  1335. 'old' should be previous filestat of 'path'.
  1336. This skips avoiding ambiguity, if a process doesn't have
  1337. appropriate privileges for 'path'.
  1338. """
  1339. advanced = (old.stat.st_mtime + 1) & 0x7fffffff
  1340. try:
  1341. os.utime(path, (advanced, advanced))
  1342. except OSError as inst:
  1343. if inst.errno == errno.EPERM:
  1344. # utime() on the file created by another user causes EPERM,
  1345. # if a process doesn't have appropriate privileges
  1346. return
  1347. raise
  1348. def __ne__(self, other):
  1349. return not self == other
  1350. class atomictempfile(object):
  1351. '''writable file object that atomically updates a file
  1352. All writes will go to a temporary copy of the original file. Call
  1353. close() when you are done writing, and atomictempfile will rename
  1354. the temporary copy to the original name, making the changes
  1355. visible. If the object is destroyed without being closed, all your
  1356. writes are discarded.
  1357. checkambig argument of constructor is used with filestat, and is
  1358. useful only if target file is guarded by any lock (e.g. repo.lock
  1359. or repo.wlock).
  1360. '''
  1361. def __init__(self, name, mode='w+b', createmode=None, checkambig=False):
  1362. self.__name = name # permanent name
  1363. self._tempname = mktempcopy(name, emptyok=('w' in mode),
  1364. createmode=createmode)
  1365. self._fp = posixfile(self._tempname, mode)
  1366. self._checkambig = checkambig
  1367. # delegated methods
  1368. self.read = self._fp.read
  1369. self.write = self._fp.write
  1370. self.seek = self._fp.seek
  1371. self.tell = self._fp.tell
  1372. self.fileno = self._fp.fileno
  1373. def close(self):
  1374. if not self._fp.closed:
  1375. self._fp.close()
  1376. filename = localpath(self.__name)
  1377. oldstat = self._checkambig and filestat(filename)
  1378. if oldstat and oldstat.stat:
  1379. rename(self._tempname, filename)
  1380. newstat = filestat(filename)
  1381. if newstat.isambig(oldstat):
  1382. # stat of changed file is ambiguous to original one
  1383. advanced = (oldstat.stat.st_mtime + 1) & 0x7fffffff
  1384. os.utime(filename, (advanced, advanced))
  1385. else:
  1386. rename(self._tempname, filename)
  1387. def discard(self):
  1388. if not self._fp.closed:
  1389. try:
  1390. os.unlink(self._tempname)
  1391. except OSError:
  1392. pass
  1393. self._fp.close()
  1394. def __del__(self):
  1395. if safehasattr(self, '_fp'): # constructor actually did something
  1396. self.discard()
  1397. def __enter__(self):
  1398. return self
  1399. def __exit__(self, exctype, excvalue, traceback):
  1400. if exctype is not None:
  1401. self.discard()
  1402. else:
  1403. self.close()
  1404. def makedirs(name, mode=None, notindexed=False):
  1405. """recursive directory creation with parent mode inheritance
  1406. Newly created directories are marked as "not to be indexed by
  1407. the content indexing service", if ``notindexed`` is specified
  1408. for "write" mode access.
  1409. """
  1410. try:
  1411. makedir(name, notindexed)
  1412. except OSError as err:
  1413. if err.errno == errno.EEXIST:
  1414. return
  1415. if err.errno != errno.ENOENT or not name:
  1416. raise
  1417. parent = os.path.dirname(os.path.abspath(name))
  1418. if parent == name:
  1419. raise
  1420. makedirs(parent, mode, notindexed)
  1421. try:
  1422. makedir(name, notindexed)
  1423. except OSError as err:
  1424. # Catch EEXIST to handle races
  1425. if err.errno == errno.EEXIST:
  1426. return
  1427. raise
  1428. if mode is not None:
  1429. os.chmod(name, mode)
  1430. def readfile(path):
  1431. with open(path, 'rb') as fp:
  1432. return fp.read()
  1433. def writefile(path, text):
  1434. with open(path, 'wb') as fp:
  1435. fp.write(text)
  1436. def appendfile(path, text):
  1437. with open(path, 'ab') as fp:
  1438. fp.write(text)
  1439. class chunkbuffer(object):
  1440. """Allow arbitrary sized chunks of data to be efficiently read from an
  1441. iterator over chunks of arbitrary size."""
  1442. def __init__(self, in_iter):
  1443. """in_iter is the iterator that's iterating over the input chunks.
  1444. targetsize is how big a buffer to try to maintain."""
  1445. def splitbig(chunks):
  1446. for chunk in chunks:
  1447. if len(chunk) > 2**20:
  1448. pos = 0
  1449. while pos < len(chunk):
  1450. end = pos + 2 ** 18
  1451. yield chunk[pos:end]
  1452. pos = end
  1453. else:
  1454. yield chunk
  1455. self.iter = splitbig(in_iter)
  1456. self._queue = collections.deque()
  1457. self._chunkoffset = 0
  1458. def read(self, l=None):
  1459. """Read L bytes of data from the iterator of chunks of data.
  1460. Returns less than L bytes if the iterator runs dry.
  1461. If size parameter is omitted, read everything"""
  1462. if l is None:
  1463. return ''.join(self.iter)
  1464. left = l
  1465. buf = []
  1466. queue = self._queue
  1467. while left > 0:
  1468. # refill the queue
  1469. if not queue:
  1470. target = 2**18
  1471. for chunk in self.iter:
  1472. queue.append(chunk)
  1473. target -= len(chunk)
  1474. if target <= 0:
  1475. break
  1476. if not queue:
  1477. break
  1478. # The easy way to do this would be to queue.popleft(), modify the
  1479. # chunk (if necessary), then queue.appendleft(). However, for cases
  1480. # where we read partial chunk content, this incurs 2 dequeue
  1481. # mutations and creates a new str for the remaining chunk in the
  1482. # queue. Our code below avoids this overhead.
  1483. chunk = queue[0]
  1484. chunkl = len(chunk)
  1485. offset = self._chunkoffset
  1486. # Use full chunk.
  1487. if offset == 0 and left >= chunkl:
  1488. left -= chunkl
  1489. queue.popleft()
  1490. buf.append(chunk)
  1491. # self._chunkoffset remains at 0.
  1492. continue
  1493. chunkremaining = chunkl - offset
  1494. # Use all of unconsumed part of chunk.
  1495. if left >= chunkremaining:
  1496. left -= chunkremaining
  1497. queue.popleft()
  1498. # offset == 0 is enabled by block above, so this won't merely
  1499. # copy via ``chunk[0:]``.
  1500. buf.append(chunk[offset:])
  1501. self._chunkoffset = 0
  1502. # Partial chunk needed.
  1503. else:
  1504. buf.append(chunk[offset:offset + left])
  1505. self._chunkoffset += left
  1506. left -= chunkremaining
  1507. return ''.join(buf)
  1508. def filechunkiter(f, size=131072, limit=None):
  1509. """Create a generator that produces the data in the file size
  1510. (default 131072) bytes at a time, up to optional limit (default is
  1511. to read all data). Chunks may be less than size bytes if the
  1512. chunk is the last chunk in the file, or the file is a socket or
  1513. some other type of file that sometimes reads less data than is
  1514. requested."""
  1515. assert size >= 0
  1516. assert limit is None or limit >= 0
  1517. while True:
  1518. if limit is None:
  1519. nbytes = size
  1520. else:
  1521. nbytes = min(limit, size)
  1522. s = nbytes and f.read(nbytes)
  1523. if not s:
  1524. break
  1525. if limit:
  1526. limit -= len(s)
  1527. yield s
  1528. def makedate(timestamp=None):
  1529. '''Return a unix timestamp (or the current time) as a (unixtime,
  1530. offset) tuple based off the local timezone.'''
  1531. if timestamp is None:
  1532. timestamp = time.time()
  1533. if timestamp < 0:
  1534. hint = _("check your clock")
  1535. raise Abort(_("negative timestamp: %d") % timestamp, hint=hint)
  1536. delta = (datetime.datetime.utcfromtimestamp(timestamp) -
  1537. datetime.datetime.fromtimestamp(timestamp))
  1538. tz = delta.days * 86400 + delta.seconds
  1539. return timestamp, tz
  1540. def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
  1541. """represent a (unixtime, offset) tuple as a localized time.
  1542. unixtime is seconds since the epoch, and offset is the time zone's
  1543. number of seconds away from UTC.
  1544. >>> datestr((0, 0))
  1545. 'Thu Jan 01 00:00:00 1970 +0000'
  1546. >>> datestr((42, 0))
  1547. 'Thu Jan 01 00:00:42 1970 +0000'
  1548. >>> datestr((-42, 0))
  1549. 'Wed Dec 31 23:59:18 1969 +0000'
  1550. >>> datestr((0x7fffffff, 0))
  1551. 'Tue Jan 19 03:14:07 2038 +0000'
  1552. >>> datestr((-0x80000000, 0))
  1553. 'Fri Dec 13 20:45:52 1901 +0000'
  1554. """
  1555. t, tz = date or makedate()
  1556. if "%1" in format or "%2" in format or "%z" in format:
  1557. sign = (tz > 0) and "-" or "+"
  1558. minutes = abs(tz) // 60
  1559. q, r = divmod(minutes, 60)
  1560. format = format.replace("%z", "%1%2")
  1561. format = format.replace("%1", "%c%02d" % (sign, q))
  1562. format = format.replace("%2", "%02d" % r)
  1563. d = t - tz
  1564. if d > 0x7fffffff:
  1565. d = 0x7fffffff
  1566. elif d < -0x80000000:
  1567. d = -0x80000000
  1568. # Never use time.gmtime() and datetime.datetime.fromtimestamp()
  1569. # because they use the gmtime() system call which is buggy on Windows
  1570. # for negative values.
  1571. t = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=d)
  1572. s = t.strftime(format)
  1573. return s
  1574. def shortdate(date=None):
  1575. """turn (timestamp, tzoff) tuple into iso 8631 date."""
  1576. return datestr(date, format='%Y-%m-%d')
  1577. def parsetimezone(s):
  1578. """find a trailing timezone, if any, in string, and return a
  1579. (offset, remainder) pair"""
  1580. if s.endswith("GMT") or s.endswith("UTC"):
  1581. return 0, s[:-3].rstrip()
  1582. # Unix-style timezones [+-]hhmm
  1583. if len(s) >= 5 and s[-5] in "+-" and s[-4:].isdigit():
  1584. sign = (s[-5] == "+") and 1 or -1
  1585. hours = int(s[-4:-2])
  1586. minutes = int(s[-2:])
  1587. return -sign * (hours * 60 + minutes) * 60, s[:-5].rstrip()
  1588. # ISO8601 trailing Z
  1589. if s.endswith("Z") and s[-2:-1].isdigit():
  1590. return 0, s[:-1]
  1591. # ISO8601-style [+-]hh:mm
  1592. if (len(s) >= 6 and s[-6] in "+-" and s[-3] == ":" and
  1593. s[-5:-3].isdigit() and s[-2:].isdigit()):
  1594. sign = (s[-6] == "+") and 1 or -1
  1595. hours = int(s[-5:-3])
  1596. minutes = int(s[-2:])
  1597. return -sign * (hours * 60 + minutes) * 60, s[:-6]
  1598. return None, s
  1599. def strdate(string, format, defaults=[]):
  1600. """parse a localized time string and return a (unixtime, offset) tuple.
  1601. if the string cannot be parsed, ValueError is raised."""
  1602. # NOTE: unixtime = localunixtime + offset
  1603. offset, date = parsetimezone(string)
  1604. # add missing elements from defaults
  1605. usenow = False # default to using biased defaults
  1606. for part in ("S", "M", "HI", "d", "mb", "yY"): # decreasing specificity
  1607. found = [True for p in part if ("%"+p) in format]
  1608. if not found:
  1609. date += "@" + defaults[part][usenow]
  1610. format += "@%" + part[0]
  1611. else:
  1612. # We've found a specific time element, less specific time
  1613. # elements are relative to today
  1614. usenow = True
  1615. timetuple = time.strptime(date, format)
  1616. localunixtime = int(calendar.timegm(timetuple))
  1617. if offset is None:
  1618. # local timezone
  1619. unixtime = int(time.mktime(timetuple))
  1620. offset = unixtime - localunixtime
  1621. else:
  1622. unixtime = localunixtime + offset
  1623. return unixtime, offset
  1624. def parsedate(date, formats=None, bias=None):
  1625. """parse a localized date/time and return a (unixtime, offset) tuple.
  1626. The date may be a "unixtime offset" string or in one of the specified
  1627. formats. If the date already is a (unixtime, offset) tuple, it is returned.
  1628. >>> parsedate(' today ') == parsedate(\
  1629. datetime.date.today().strftime('%b %d'))
  1630. True
  1631. >>> parsedate( 'yesterday ') == parsedate((datetime.date.today() -\
  1632. datetime.timedelta(days=1)\
  1633. ).strftime('%b %d'))
  1634. True
  1635. >>> now, tz = makedate()
  1636. >>> strnow, strtz = parsedate('now')
  1637. >>> (strnow - now) < 1
  1638. True
  1639. >>> tz == strtz
  1640. True
  1641. """
  1642. if bias is None:
  1643. bias = {}
  1644. if not date:
  1645. return 0, 0
  1646. if isinstance(date, tuple) and len(date) == 2:
  1647. return date
  1648. if not formats:
  1649. formats = defaultdateformats
  1650. date = date.strip()
  1651. if date == 'now' or date == _('now'):
  1652. return makedate()
  1653. if date == 'today' or date == _('today'):
  1654. date = datetime.date.today().strftime('%b %d')
  1655. elif date == 'yesterday' or date == _('yesterday'):
  1656. date = (datetime.date.today() -
  1657. datetime.timedelta(days=1)).strftime('%b %d')
  1658. try:
  1659. when, offset = map(int, date.split(' '))
  1660. except ValueError:
  1661. # fill out defaults
  1662. now = makedate()
  1663. defaults = {}
  1664. for part in ("d", "mb", "yY", "HI", "M", "S"):
  1665. # this piece is for rounding the specific end of unknowns
  1666. b = bias.get(part)
  1667. if b is None:
  1668. if part[0] in "HMS":
  1669. b = "00"
  1670. else:
  1671. b = "0"
  1672. # this piece is for matching the generic end to today's date
  1673. n = datestr(now, "%" + part[0])
  1674. defaults[part] = (b, n)
  1675. for format in formats:
  1676. try:
  1677. when, offset = strdate(date, format, defaults)
  1678. except (ValueError, OverflowError):
  1679. pass
  1680. else:
  1681. break
  1682. else:
  1683. raise Abort(_('invalid date: %r') % date)
  1684. # validate explicit (probably user-specified) date and
  1685. # time zone offset. values must fit in signed 32 bits for
  1686. # current 32-bit linux runtimes. timezones go from UTC-12
  1687. # to UTC+14
  1688. if when < -0x80000000 or when > 0x7fffffff:
  1689. raise Abort(_('date exceeds 32 bits: %d') % when)
  1690. if offset < -50400 or offset > 43200:
  1691. raise Abort(_('impossible time zone offset: %d') % offset)
  1692. return when, offset
  1693. def matchdate(date):
  1694. """Return a function that matches a given date match specifier
  1695. Formats include:
  1696. '{date}' match a given date to the accuracy provided
  1697. '<{date}' on or before a given date
  1698. '>{date}' on or after a given date
  1699. >>> p1 = parsedate("10:29:59")
  1700. >>> p2 = parsedate("10:30:00")
  1701. >>> p3 = parsedate("10:30:59")
  1702. >>> p4 = parsedate("10:31:00")
  1703. >>> p5 = parsedate("Sep 15 10:30:00 1999")
  1704. >>> f = matchdate("10:30")
  1705. >>> f(p1[0])
  1706. False
  1707. >>> f(p2[0])
  1708. True
  1709. >>> f(p3[0])
  1710. True
  1711. >>> f(p4[0])
  1712. False
  1713. >>> f(p5[0])
  1714. False
  1715. """
  1716. def lower(date):
  1717. d = {'mb': "1", 'd': "1"}
  1718. return parsedate(date, extendeddateformats, d)[0]
  1719. def upper(date):
  1720. d = {'mb': "12", 'HI': "23", 'M': "59", 'S': "59"}
  1721. for days in ("31", "30", "29"):
  1722. try:
  1723. d["d"] = days
  1724. return parsedate(date, extendeddateformats, d)[0]
  1725. except Abort:
  1726. pass
  1727. d["d"] = "28"
  1728. return parsedate(date, extendeddateformats, d)[0]
  1729. date = date.strip()
  1730. if not date:
  1731. raise Abort(_("dates cannot consist entirely of whitespace"))
  1732. elif date[0] == "<":
  1733. if not date[1:]:
  1734. raise Abort(_("invalid day spec, use '<DATE'"))
  1735. when = upper(date[1:])
  1736. return lambda x: x <= when
  1737. elif date[0] == ">":
  1738. if not date[1:]:
  1739. raise Abort(_("invalid day spec, use '>DATE'"))
  1740. when = lower(date[1:])
  1741. return lambda x: x >= when
  1742. elif date[0] == "-":
  1743. try:
  1744. days = int(date[1:])
  1745. except ValueError:
  1746. raise Abort(_("invalid day spec: %s") % date[1:])
  1747. if days < 0:
  1748. raise Abort(_("%s must be nonnegative (see 'hg help dates')")
  1749. % date[1:])
  1750. when = makedate()[0] - days * 3600 * 24
  1751. return lambda x: x >= when
  1752. elif " to " in date:
  1753. a, b = date.split(" to ")
  1754. start, stop = lower(a), upper(b)
  1755. return lambda x: x >= start and x <= stop
  1756. else:
  1757. start, stop = lower(date), upper(date)
  1758. return lambda x: x >= start and x <= stop
  1759. def stringmatcher(pattern, casesensitive=True):
  1760. """
  1761. accepts a string, possibly starting with 're:' or 'literal:' prefix.
  1762. returns the matcher name, pattern, and matcher function.
  1763. missing or unknown prefixes are treated as literal matches.
  1764. helper for tests:
  1765. >>> def test(pattern, *tests):
  1766. ... kind, pattern, matcher = stringmatcher(pattern)
  1767. ... return (kind, pattern, [bool(matcher(t)) for t in tests])
  1768. >>> def itest(pattern, *tests):
  1769. ... kind, pattern, matcher = stringmatcher(pattern, casesensitive=False)
  1770. ... return (kind, pattern, [bool(matcher(t)) for t in tests])
  1771. exact matching (no prefix):
  1772. >>> test('abcdefg', 'abc', 'def', 'abcdefg')
  1773. ('literal', 'abcdefg', [False, False, True])
  1774. regex matching ('re:' prefix)
  1775. >>> test('re:a.+b', 'nomatch', 'fooadef', 'fooadefbar')
  1776. ('re', 'a.+b', [False, False, True])
  1777. force exact matches ('literal:' prefix)
  1778. >>> test('literal:re:foobar', 'foobar', 're:foobar')
  1779. ('literal', 're:foobar', [False, True])
  1780. unknown prefixes are ignored and treated as literals
  1781. >>> test('foo:bar', 'foo', 'bar', 'foo:bar')
  1782. ('literal', 'foo:bar', [False, False, True])
  1783. case insensitive regex matches
  1784. >>> itest('re:A.+b', 'nomatch', 'fooadef', 'fooadefBar')
  1785. ('re', 'A.+b', [False, False, True])
  1786. case insensitive literal matches
  1787. >>> itest('ABCDEFG', 'abc', 'def', 'abcdefg')
  1788. ('literal', 'ABCDEFG', [False, False, True])
  1789. """
  1790. if pattern.startswith('re:'):
  1791. pattern = pattern[3:]
  1792. try:
  1793. flags = 0
  1794. if not casesensitive:
  1795. flags = remod.I
  1796. regex = remod.compile(pattern, flags)
  1797. except remod.error as e:
  1798. raise error.ParseError(_('invalid regular expression: %s')
  1799. % e)
  1800. return 're', pattern, regex.search
  1801. elif pattern.startswith('literal:'):
  1802. pattern = pattern[8:]
  1803. match = pattern.__eq__
  1804. if not casesensitive:
  1805. ipat = encoding.lower(pattern)
  1806. match = lambda s: ipat == encoding.lower(s)
  1807. return 'literal', pattern, match
  1808. def shortuser(user):
  1809. """Return a short representation of a user name or email address."""
  1810. f = user.find('@')
  1811. if f >= 0:
  1812. user = user[:f]
  1813. f = user.find('<')
  1814. if f >= 0:
  1815. user = user[f + 1:]
  1816. f = user.find(' ')
  1817. if f >= 0:
  1818. user = user[:f]
  1819. f = user.find('.')
  1820. if f >= 0:
  1821. user = user[:f]
  1822. return user
  1823. def emailuser(user):
  1824. """Return the user portion of an email address."""
  1825. f = user.find('@')
  1826. if f >= 0:
  1827. user = user[:f]
  1828. f = user.find('<')
  1829. if f >= 0:
  1830. user = user[f + 1:]
  1831. return user
  1832. def email(author):
  1833. '''get email of author.'''
  1834. r = author.find('>')
  1835. if r == -1:
  1836. r = None
  1837. return author[author.find('<') + 1:r]
  1838. def ellipsis(text, maxlength=400):
  1839. """Trim string to at most maxlength (default: 400) columns in display."""
  1840. return encoding.trim(text, maxlength, ellipsis='...')
  1841. def unitcountfn(*unittable):
  1842. '''return a function that renders a readable count of some quantity'''
  1843. def go(count):
  1844. for multiplier, divisor, format in unittable:
  1845. if count >= divisor * multiplier:
  1846. return format % (count / float(divisor))
  1847. return unittable[-1][2] % count
  1848. return go
  1849. bytecount = unitcountfn(
  1850. (100, 1 << 30, _('%.0f GB')),
  1851. (10, 1 << 30, _('%.1f GB')),
  1852. (1, 1 << 30, _('%.2f GB')),
  1853. (100, 1 << 20, _('%.0f MB')),
  1854. (10, 1 << 20, _('%.1f MB')),
  1855. (1, 1 << 20, _('%.2f MB')),
  1856. (100, 1 << 10, _('%.0f KB')),
  1857. (10, 1 << 10, _('%.1f KB')),
  1858. (1, 1 << 10, _('%.2f KB')),
  1859. (1, 1, _('%.0f bytes')),
  1860. )
  1861. def uirepr(s):
  1862. # Avoid double backslash in Windows path repr()
  1863. return repr(s).replace('\\\\', '\\')
  1864. # delay import of textwrap
  1865. def MBTextWrapper(**kwargs):
  1866. class tw(textwrap.TextWrapper):
  1867. """
  1868. Extend TextWrapper for width-awareness.
  1869. Neither number of 'bytes' in any encoding nor 'characters' is
  1870. appropriate to calculate terminal columns for specified string.
  1871. Original TextWrapper implementation uses built-in 'len()' directly,
  1872. so overriding is needed to use width information of each characters.
  1873. In addition, characters classified into 'ambiguous' width are
  1874. treated as wide in East Asian area, but as narrow in other.
  1875. This requires use decision to determine width of such characters.
  1876. """
  1877. def _cutdown(self, ucstr, space_left):
  1878. l = 0
  1879. colwidth = encoding.ucolwidth
  1880. for i in xrange(len(ucstr)):
  1881. l += colwidth(ucstr[i])
  1882. if space_left < l:
  1883. return (ucstr[:i], ucstr[i:])
  1884. return ucstr, ''
  1885. # overriding of base class
  1886. def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
  1887. space_left = max(width - cur_len, 1)
  1888. if self.break_long_words:
  1889. cut, res = self._cutdown(reversed_chunks[-1], space_left)
  1890. cur_line.append(cut)
  1891. reversed_chunks[-1] = res
  1892. elif not cur_line:
  1893. cur_line.append(reversed_chunks.pop())
  1894. # this overriding code is imported from TextWrapper of Python 2.6
  1895. # to calculate columns of string by 'encoding.ucolwidth()'
  1896. def _wrap_chunks(self, chunks):
  1897. colwidth = encoding.ucolwidth
  1898. lines = []
  1899. if self.width <= 0:
  1900. raise ValueError("invalid width %r (must be > 0)" % self.width)
  1901. # Arrange in reverse order so items can be efficiently popped
  1902. # from a stack of chucks.
  1903. chunks.reverse()
  1904. while chunks:
  1905. # Start the list of chunks that will make up the current line.
  1906. # cur_len is just the length of all the chunks in cur_line.
  1907. cur_line = []
  1908. cur_len = 0
  1909. # Figure out which static string will prefix this line.
  1910. if lines:
  1911. indent = self.subsequent_indent
  1912. else:
  1913. indent = self.initial_indent
  1914. # Maximum width for this line.
  1915. width = self.width - len(indent)
  1916. # First chunk on line is whitespace -- drop it, unless this
  1917. # is the very beginning of the text (i.e. no lines started yet).
  1918. if self.drop_whitespace and chunks[-1].strip() == '' and lines:
  1919. del chunks[-1]
  1920. while chunks:
  1921. l = colwidth(chunks[-1])
  1922. # Can at least squeeze this chunk onto the current line.
  1923. if cur_len + l <= width:
  1924. cur_line.append(chunks.pop())
  1925. cur_len += l
  1926. # Nope, this line is full.
  1927. else:
  1928. break
  1929. # The current line is full, and the next chunk is too big to
  1930. # fit on *any* line (not just this one).
  1931. if chunks and colwidth(chunks[-1]) > width:
  1932. self._handle_long_word(chunks, cur_line, cur_len, width)
  1933. # If the last chunk on this line is all whitespace, drop it.
  1934. if (self.drop_whitespace and
  1935. cur_line and cur_line[-1].strip() == ''):
  1936. del cur_line[-1]
  1937. # Convert current line back to a string and store it in list
  1938. # of all lines (return value).
  1939. if cur_line:
  1940. lines.append(indent + ''.join(cur_line))
  1941. return lines
  1942. global MBTextWrapper
  1943. MBTextWrapper = tw
  1944. return tw(**kwargs)
  1945. def wrap(line, width, initindent='', hangindent=''):
  1946. maxindent = max(len(hangindent), len(initindent))
  1947. if width <= maxindent:
  1948. # adjust for weird terminal size
  1949. width = max(78, maxindent + 1)
  1950. line = line.decode(encoding.encoding, encoding.encodingmode)
  1951. initindent = initindent.decode(encoding.encoding, encoding.encodingmode)
  1952. hangindent = hangindent.decode(encoding.encoding, encoding.encodingmode)
  1953. wrapper = MBTextWrapper(width=width,
  1954. initial_indent=initindent,
  1955. subsequent_indent=hangindent)
  1956. return wrapper.fill(line).encode(encoding.encoding)
  1957. if (pyplatform.python_implementation() == 'CPython' and
  1958. sys.version_info < (3, 0)):
  1959. # There is an issue in CPython that some IO methods do not handle EINTR
  1960. # correctly. The following table shows what CPython version (and functions)
  1961. # are affected (buggy: has the EINTR bug, okay: otherwise):
  1962. #
  1963. # | < 2.7.4 | 2.7.4 to 2.7.12 | >= 3.0
  1964. # --------------------------------------------------
  1965. # fp.__iter__ | buggy | buggy | okay
  1966. # fp.read* | buggy | okay [1] | okay
  1967. #
  1968. # [1]: fixed by changeset 67dc99a989cd in the cpython hg repo.
  1969. #
  1970. # Here we workaround the EINTR issue for fileobj.__iter__. Other methods
  1971. # like "read*" are ignored for now, as Python < 2.7.4 is a minority.
  1972. #
  1973. # Although we can workaround the EINTR issue for fp.__iter__, it is slower:
  1974. # "for x in fp" is 4x faster than "for x in iter(fp.readline, '')" in
  1975. # CPython 2, because CPython 2 maintains an internal readahead buffer for
  1976. # fp.__iter__ but not other fp.read* methods.
  1977. #
  1978. # On modern systems like Linux, the "read" syscall cannot be interrupted
  1979. # when reading "fast" files like on-disk files. So the EINTR issue only
  1980. # affects things like pipes, sockets, ttys etc. We treat "normal" (S_ISREG)
  1981. # files approximately as "fast" files and use the fast (unsafe) code path,
  1982. # to minimize the performance impact.
  1983. if sys.version_info >= (2, 7, 4):
  1984. # fp.readline deals with EINTR correctly, use it as a workaround.
  1985. def _safeiterfile(fp):
  1986. return iter(fp.readline, '')
  1987. else:
  1988. # fp.read* are broken too, manually deal with EINTR in a stupid way.
  1989. # note: this may block longer than necessary because of bufsize.
  1990. def _safeiterfile(fp, bufsize=4096):
  1991. fd = fp.fileno()
  1992. line = ''
  1993. while True:
  1994. try:
  1995. buf = os.read(fd, bufsize)
  1996. except OSError as ex:
  1997. # os.read only raises EINTR before any data is read
  1998. if ex.errno == errno.EINTR:
  1999. continue
  2000. else:
  2001. raise
  2002. line += buf
  2003. if '\n' in buf:
  2004. splitted = line.splitlines(True)
  2005. line = ''
  2006. for l in splitted:
  2007. if l[-1] == '\n':
  2008. yield l
  2009. else:
  2010. line = l
  2011. if not buf:
  2012. break
  2013. if line:
  2014. yield line
  2015. def iterfile(fp):
  2016. fastpath = True
  2017. if type(fp) is file:
  2018. fastpath = stat.S_ISREG(os.fstat(fp.fileno()).st_mode)
  2019. if fastpath:
  2020. return fp
  2021. else:
  2022. return _safeiterfile(fp)
  2023. else:
  2024. # PyPy and CPython 3 do not have the EINTR issue thus no workaround needed.
  2025. def iterfile(fp):
  2026. return fp
  2027. def iterlines(iterator):
  2028. for chunk in iterator:
  2029. for line in chunk.splitlines():
  2030. yield line
  2031. def expandpath(path):
  2032. return os.path.expanduser(os.path.expandvars(path))
  2033. def hgcmd():
  2034. """Return the command used to execute current hg
  2035. This is different from hgexecutable() because on Windows we want
  2036. to avoid things opening new shell windows like batch files, so we
  2037. get either the python call or current executable.
  2038. """
  2039. if mainfrozen():
  2040. if getattr(sys, 'frozen', None) == 'macosx_app':
  2041. # Env variable set by py2app
  2042. return [encoding.environ['EXECUTABLEPATH']]
  2043. else:
  2044. return [pycompat.sysexecutable]
  2045. return gethgcmd()
  2046. def rundetached(args, condfn):
  2047. """Execute the argument list in a detached process.
  2048. condfn is a callable which is called repeatedly and should return
  2049. True once the child process is known to have started successfully.
  2050. At this point, the child process PID is returned. If the child
  2051. process fails to start or finishes before condfn() evaluates to
  2052. True, return -1.
  2053. """
  2054. # Windows case is easier because the child process is either
  2055. # successfully starting and validating the condition or exiting
  2056. # on failure. We just poll on its PID. On Unix, if the child
  2057. # process fails to start, it will be left in a zombie state until
  2058. # the parent wait on it, which we cannot do since we expect a long
  2059. # running process on success. Instead we listen for SIGCHLD telling
  2060. # us our child process terminated.
  2061. terminated = set()
  2062. def handler(signum, frame):
  2063. terminated.add(os.wait())
  2064. prevhandler = None
  2065. SIGCHLD = getattr(signal, 'SIGCHLD', None)
  2066. if SIGCHLD is not None:
  2067. prevhandler = signal.signal(SIGCHLD, handler)
  2068. try:
  2069. pid = spawndetached(args)
  2070. while not condfn():
  2071. if ((pid in terminated or not testpid(pid))
  2072. and not condfn()):
  2073. return -1
  2074. time.sleep(0.1)
  2075. return pid
  2076. finally:
  2077. if prevhandler is not None:
  2078. signal.signal(signal.SIGCHLD, prevhandler)
  2079. def interpolate(prefix, mapping, s, fn=None, escape_prefix=False):
  2080. """Return the result of interpolating items in the mapping into string s.
  2081. prefix is a single character string, or a two character string with
  2082. a backslash as the first character if the prefix needs to be escaped in
  2083. a regular expression.
  2084. fn is an optional function that will be applied to the replacement text
  2085. just before replacement.
  2086. escape_prefix is an optional flag that allows using doubled prefix for
  2087. its escaping.
  2088. """
  2089. fn = fn or (lambda s: s)
  2090. patterns = '|'.join(mapping.keys())
  2091. if escape_prefix:
  2092. patterns += '|' + prefix
  2093. if len(prefix) > 1:
  2094. prefix_char = prefix[1:]
  2095. else:
  2096. prefix_char = prefix
  2097. mapping[prefix_char] = prefix_char
  2098. r = remod.compile(r'%s(%s)' % (prefix, patterns))
  2099. return r.sub(lambda x: fn(mapping[x.group()[1:]]), s)
  2100. def getport(port):
  2101. """Return the port for a given network service.
  2102. If port is an integer, it's returned as is. If it's a string, it's
  2103. looked up using socket.getservbyname(). If there's no matching
  2104. service, error.Abort is raised.
  2105. """
  2106. try:
  2107. return int(port)
  2108. except ValueError:
  2109. pass
  2110. try:
  2111. return socket.getservbyname(port)
  2112. except socket.error:
  2113. raise Abort(_("no port number associated with service '%s'") % port)
  2114. _booleans = {'1': True, 'yes': True, 'true': True, 'on': True, 'always': True,
  2115. '0': False, 'no': False, 'false': False, 'off': False,
  2116. 'never': False}
  2117. def parsebool(s):
  2118. """Parse s into a boolean.
  2119. If s is not a valid boolean, returns None.
  2120. """
  2121. return _booleans.get(s.lower(), None)
  2122. _hextochr = dict((a + b, chr(int(a + b, 16)))
  2123. for a in string.hexdigits for b in string.hexdigits)
  2124. class url(object):
  2125. r"""Reliable URL parser.
  2126. This parses URLs and provides attributes for the following
  2127. components:
  2128. <scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
  2129. Missing components are set to None. The only exception is
  2130. fragment, which is set to '' if present but empty.
  2131. If parsefragment is False, fragment is included in query. If
  2132. parsequery is False, query is included in path. If both are
  2133. False, both fragment and query are included in path.
  2134. See http://www.ietf.org/rfc/rfc2396.txt for more information.
  2135. Note that for backward compatibility reasons, bundle URLs do not
  2136. take host names. That means 'bundle://../' has a path of '../'.
  2137. Examples:
  2138. >>> url('http://www.ietf.org/rfc/rfc2396.txt')
  2139. <url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
  2140. >>> url('ssh://[::1]:2200//home/joe/repo')
  2141. <url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
  2142. >>> url('file:///home/joe/repo')
  2143. <url scheme: 'file', path: '/home/joe/repo'>
  2144. >>> url('file:///c:/temp/foo/')
  2145. <url scheme: 'file', path: 'c:/temp/foo/'>
  2146. >>> url('bundle:foo')
  2147. <url scheme: 'bundle', path: 'foo'>
  2148. >>> url('bundle://../foo')
  2149. <url scheme: 'bundle', path: '../foo'>
  2150. >>> url(r'c:\foo\bar')
  2151. <url path: 'c:\\foo\\bar'>
  2152. >>> url(r'\\blah\blah\blah')
  2153. <url path: '\\\\blah\\blah\\blah'>
  2154. >>> url(r'\\blah\blah\blah#baz')
  2155. <url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
  2156. >>> url(r'file:///C:\users\me')
  2157. <url scheme: 'file', path: 'C:\\users\\me'>
  2158. Authentication credentials:
  2159. >>> url('ssh://joe:xyz@x/repo')
  2160. <url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
  2161. >>> url('ssh://joe@x/repo')
  2162. <url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
  2163. Query strings and fragments:
  2164. >>> url('http://host/a?b#c')
  2165. <url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
  2166. >>> url('http://host/a?b#c', parsequery=False, parsefragment=False)
  2167. <url scheme: 'http', host: 'host', path: 'a?b#c'>
  2168. Empty path:
  2169. >>> url('')
  2170. <url path: ''>
  2171. >>> url('#a')
  2172. <url path: '', fragment: 'a'>
  2173. >>> url('http://host/')
  2174. <url scheme: 'http', host: 'host', path: ''>
  2175. >>> url('http://host/#a')
  2176. <url scheme: 'http', host: 'host', path: '', fragment: 'a'>
  2177. Only scheme:
  2178. >>> url('http:')
  2179. <url scheme: 'http'>
  2180. """
  2181. _safechars = "!~*'()+"
  2182. _safepchars = "/!~*'()+:\\"
  2183. _matchscheme = remod.compile('^[a-zA-Z0-9+.\\-]+:').match
  2184. def __init__(self, path, parsequery=True, parsefragment=True):
  2185. # We slowly chomp away at path until we have only the path left
  2186. self.scheme = self.user = self.passwd = self.host = None
  2187. self.port = self.path = self.query = self.fragment = None
  2188. self._localpath = True
  2189. self._hostport = ''
  2190. self._origpath = path
  2191. if parsefragment and '#' in path:
  2192. path, self.fragment = path.split('#', 1)
  2193. # special case for Windows drive letters and UNC paths
  2194. if hasdriveletter(path) or path.startswith('\\\\'):
  2195. self.path = path
  2196. return
  2197. # For compatibility reasons, we can't handle bundle paths as
  2198. # normal URLS
  2199. if path.startswith('bundle:'):
  2200. self.scheme = 'bundle'
  2201. path = path[7:]
  2202. if path.startswith('//'):
  2203. path = path[2:]
  2204. self.path = path
  2205. return
  2206. if self._matchscheme(path):
  2207. parts = path.split(':', 1)
  2208. if parts[0]:
  2209. self.scheme, path = parts
  2210. self._localpath = False
  2211. if not path:
  2212. path = None
  2213. if self._localpath:
  2214. self.path = ''
  2215. return
  2216. else:
  2217. if self._localpath:
  2218. self.path = path
  2219. return
  2220. if parsequery and '?' in path:
  2221. path, self.query = path.split('?', 1)
  2222. if not path:
  2223. path = None
  2224. if not self.query:
  2225. self.query = None
  2226. # // is required to specify a host/authority
  2227. if path and path.startswith('//'):
  2228. parts = path[2:].split('/', 1)
  2229. if len(parts) > 1:
  2230. self.host, path = parts
  2231. else:
  2232. self.host = parts[0]
  2233. path = None
  2234. if not self.host:
  2235. self.host = None
  2236. # path of file:///d is /d
  2237. # path of file:///d:/ is d:/, not /d:/
  2238. if path and not hasdriveletter(path):
  2239. path = '/' + path
  2240. if self.host and '@' in self.host:
  2241. self.user, self.host = self.host.rsplit('@', 1)
  2242. if ':' in self.user:
  2243. self.user, self.passwd = self.user.split(':', 1)
  2244. if not self.host:
  2245. self.host = None
  2246. # Don't split on colons in IPv6 addresses without ports
  2247. if (self.host and ':' in self.host and
  2248. not (self.host.startswith('[') and self.host.endswith(']'))):
  2249. self._hostport = self.host
  2250. self.host, self.port = self.host.rsplit(':', 1)
  2251. if not self.host:
  2252. self.host = None
  2253. if (self.host and self.scheme == 'file' and
  2254. self.host not in ('localhost', '127.0.0.1', '[::1]')):
  2255. raise Abort(_('file:// URLs can only refer to localhost'))
  2256. self.path = path
  2257. # leave the query string escaped
  2258. for a in ('user', 'passwd', 'host', 'port',
  2259. 'path', 'fragment'):
  2260. v = getattr(self, a)
  2261. if v is not None:
  2262. setattr(self, a, pycompat.urlunquote(v))
  2263. def __repr__(self):
  2264. attrs = []
  2265. for a in ('scheme', 'user', 'passwd', 'host', 'port', 'path',
  2266. 'query', 'fragment'):
  2267. v = getattr(self, a)
  2268. if v is not None:
  2269. attrs.append('%s: %r' % (a, v))
  2270. return '<url %s>' % ', '.join(attrs)
  2271. def __str__(self):
  2272. r"""Join the URL's components back into a URL string.
  2273. Examples:
  2274. >>> str(url('http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
  2275. 'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
  2276. >>> str(url('http://user:pw@host:80/?foo=bar&baz=42'))
  2277. 'http://user:pw@host:80/?foo=bar&baz=42'
  2278. >>> str(url('http://user:pw@host:80/?foo=bar%3dbaz'))
  2279. 'http://user:pw@host:80/?foo=bar%3dbaz'
  2280. >>> str(url('ssh://user:pw@[::1]:2200//home/joe#'))
  2281. 'ssh://user:pw@[::1]:2200//home/joe#'
  2282. >>> str(url('http://localhost:80//'))
  2283. 'http://localhost:80//'
  2284. >>> str(url('http://localhost:80/'))
  2285. 'http://localhost:80/'
  2286. >>> str(url('http://localhost:80'))
  2287. 'http://localhost:80/'
  2288. >>> str(url('bundle:foo'))
  2289. 'bundle:foo'
  2290. >>> str(url('bundle://../foo'))
  2291. 'bundle:../foo'
  2292. >>> str(url('path'))
  2293. 'path'
  2294. >>> str(url('file:///tmp/foo/bar'))
  2295. 'file:///tmp/foo/bar'
  2296. >>> str(url('file:///c:/tmp/foo/bar'))
  2297. 'file:///c:/tmp/foo/bar'
  2298. >>> print url(r'bundle:foo\bar')
  2299. bundle:foo\bar
  2300. >>> print url(r'file:///D:\data\hg')
  2301. file:///D:\data\hg
  2302. """
  2303. if self._localpath:
  2304. s = self.path
  2305. if self.scheme == 'bundle':
  2306. s = 'bundle:' + s
  2307. if self.fragment:
  2308. s += '#' + self.fragment
  2309. return s
  2310. s = self.scheme + ':'
  2311. if self.user or self.passwd or self.host:
  2312. s += '//'
  2313. elif self.scheme and (not self.path or self.path.startswith('/')
  2314. or hasdriveletter(self.path)):
  2315. s += '//'
  2316. if hasdriveletter(self.path):
  2317. s += '/'
  2318. if self.user:
  2319. s += urlreq.quote(self.user, safe=self._safechars)
  2320. if self.passwd:
  2321. s += ':' + urlreq.quote(self.passwd, safe=self._safechars)
  2322. if self.user or self.passwd:
  2323. s += '@'
  2324. if self.host:
  2325. if not (self.host.startswith('[') and self.host.endswith(']')):
  2326. s += urlreq.quote(self.host)
  2327. else:
  2328. s += self.host
  2329. if self.port:
  2330. s += ':' + urlreq.quote(self.port)
  2331. if self.host:
  2332. s += '/'
  2333. if self.path:
  2334. # TODO: similar to the query string, we should not unescape the
  2335. # path when we store it, the path might contain '%2f' = '/',
  2336. # which we should *not* escape.
  2337. s += urlreq.quote(self.path, safe=self._safepchars)
  2338. if self.query:
  2339. # we store the query in escaped form.
  2340. s += '?' + self.query
  2341. if self.fragment is not None:
  2342. s += '#' + urlreq.quote(self.fragment, safe=self._safepchars)
  2343. return s
  2344. def authinfo(self):
  2345. user, passwd = self.user, self.passwd
  2346. try:
  2347. self.user, self.passwd = None, None
  2348. s = str(self)
  2349. finally:
  2350. self.user, self.passwd = user, passwd
  2351. if not self.user:
  2352. return (s, None)
  2353. # authinfo[1] is passed to urllib2 password manager, and its
  2354. # URIs must not contain credentials. The host is passed in the
  2355. # URIs list because Python < 2.4.3 uses only that to search for
  2356. # a password.
  2357. return (s, (None, (s, self.host),
  2358. self.user, self.passwd or ''))
  2359. def isabs(self):
  2360. if self.scheme and self.scheme != 'file':
  2361. return True # remote URL
  2362. if hasdriveletter(self.path):
  2363. return True # absolute for our purposes - can't be joined()
  2364. if self.path.startswith(r'\\'):
  2365. return True # Windows UNC path
  2366. if self.path.startswith('/'):
  2367. return True # POSIX-style
  2368. return False
  2369. def localpath(self):
  2370. if self.scheme == 'file' or self.scheme == 'bundle':
  2371. path = self.path or '/'
  2372. # For Windows, we need to promote hosts containing drive
  2373. # letters to paths with drive letters.
  2374. if hasdriveletter(self._hostport):
  2375. path = self._hostport + '/' + self.path
  2376. elif (self.host is not None and self.path
  2377. and not hasdriveletter(path)):
  2378. path = '/' + path
  2379. return path
  2380. return self._origpath
  2381. def islocal(self):
  2382. '''whether localpath will return something that posixfile can open'''
  2383. return (not self.scheme or self.scheme == 'file'
  2384. or self.scheme == 'bundle')
  2385. def hasscheme(path):
  2386. return bool(url(path).scheme)
  2387. def hasdriveletter(path):
  2388. return path and path[1:2] == ':' and path[0:1].isalpha()
  2389. def urllocalpath(path):
  2390. return url(path, parsequery=False, parsefragment=False).localpath()
  2391. def hidepassword(u):
  2392. '''hide user credential in a url string'''
  2393. u = url(u)
  2394. if u.passwd:
  2395. u.passwd = '***'
  2396. return str(u)
  2397. def removeauth(u):
  2398. '''remove all authentication information from a url string'''
  2399. u = url(u)
  2400. u.user = u.passwd = None
  2401. return str(u)
  2402. timecount = unitcountfn(
  2403. (1, 1e3, _('%.0f s')),
  2404. (100, 1, _('%.1f s')),
  2405. (10, 1, _('%.2f s')),
  2406. (1, 1, _('%.3f s')),
  2407. (100, 0.001, _('%.1f ms')),
  2408. (10, 0.001, _('%.2f ms')),
  2409. (1, 0.001, _('%.3f ms')),
  2410. (100, 0.000001, _('%.1f us')),
  2411. (10, 0.000001, _('%.2f us')),
  2412. (1, 0.000001, _('%.3f us')),
  2413. (100, 0.000000001, _('%.1f ns')),
  2414. (10, 0.000000001, _('%.2f ns')),
  2415. (1, 0.000000001, _('%.3f ns')),
  2416. )
  2417. _timenesting = [0]
  2418. def timed(func):
  2419. '''Report the execution time of a function call to stderr.
  2420. During development, use as a decorator when you need to measure
  2421. the cost of a function, e.g. as follows:
  2422. @util.timed
  2423. def foo(a, b, c):
  2424. pass
  2425. '''
  2426. def wrapper(*args, **kwargs):
  2427. start = timer()
  2428. indent = 2
  2429. _timenesting[0] += indent
  2430. try:
  2431. return func(*args, **kwargs)
  2432. finally:
  2433. elapsed = timer() - start
  2434. _timenesting[0] -= indent
  2435. stderr.write('%s%s: %s\n' %
  2436. (' ' * _timenesting[0], func.__name__,
  2437. timecount(elapsed)))
  2438. return wrapper
  2439. _sizeunits = (('m', 2**20), ('k', 2**10), ('g', 2**30),
  2440. ('kb', 2**10), ('mb', 2**20), ('gb', 2**30), ('b', 1))
  2441. def sizetoint(s):
  2442. '''Convert a space specifier to a byte count.
  2443. >>> sizetoint('30')
  2444. 30
  2445. >>> sizetoint('2.2kb')
  2446. 2252
  2447. >>> sizetoint('6M')
  2448. 6291456
  2449. '''
  2450. t = s.strip().lower()
  2451. try:
  2452. for k, u in _sizeunits:
  2453. if t.endswith(k):
  2454. return int(float(t[:-len(k)]) * u)
  2455. return int(t)
  2456. except ValueError:
  2457. raise error.ParseError(_("couldn't parse size: %s") % s)
  2458. class hooks(object):
  2459. '''A collection of hook functions that can be used to extend a
  2460. function's behavior. Hooks are called in lexicographic order,
  2461. based on the names of their sources.'''
  2462. def __init__(self):
  2463. self._hooks = []
  2464. def add(self, source, hook):
  2465. self._hooks.append((source, hook))
  2466. def __call__(self, *args):
  2467. self._hooks.sort(key=lambda x: x[0])
  2468. results = []
  2469. for source, hook in self._hooks:
  2470. results.append(hook(*args))
  2471. return results
  2472. def getstackframes(skip=0, line=' %-*s in %s\n', fileline='%s:%s'):
  2473. '''Yields lines for a nicely formatted stacktrace.
  2474. Skips the 'skip' last entries.
  2475. Each file+linenumber is formatted according to fileline.
  2476. Each line is formatted according to line.
  2477. If line is None, it yields:
  2478. length of longest filepath+line number,
  2479. filepath+linenumber,
  2480. function
  2481. Not be used in production code but very convenient while developing.
  2482. '''
  2483. entries = [(fileline % (fn, ln), func)
  2484. for fn, ln, func, _text in traceback.extract_stack()[:-skip - 1]]
  2485. if entries:
  2486. fnmax = max(len(entry[0]) for entry in entries)
  2487. for fnln, func in entries:
  2488. if line is None:
  2489. yield (fnmax, fnln, func)
  2490. else:
  2491. yield line % (fnmax, fnln, func)
  2492. def debugstacktrace(msg='stacktrace', skip=0, f=stderr, otherf=stdout):
  2493. '''Writes a message to f (stderr) with a nicely formatted stacktrace.
  2494. Skips the 'skip' last entries. By default it will flush stdout first.
  2495. It can be used everywhere and intentionally does not require an ui object.
  2496. Not be used in production code but very convenient while developing.
  2497. '''
  2498. if otherf:
  2499. otherf.flush()
  2500. f.write('%s at:\n' % msg)
  2501. for line in getstackframes(skip + 1):
  2502. f.write(line)
  2503. f.flush()
  2504. class dirs(object):
  2505. '''a multiset of directory names from a dirstate or manifest'''
  2506. def __init__(self, map, skip=None):
  2507. self._dirs = {}
  2508. addpath = self.addpath
  2509. if safehasattr(map, 'iteritems') and skip is not None:
  2510. for f, s in map.iteritems():
  2511. if s[0] != skip:
  2512. addpath(f)
  2513. else:
  2514. for f in map:
  2515. addpath(f)
  2516. def addpath(self, path):
  2517. dirs = self._dirs
  2518. for base in finddirs(path):
  2519. if base in dirs:
  2520. dirs[base] += 1
  2521. return
  2522. dirs[base] = 1
  2523. def delpath(self, path):
  2524. dirs = self._dirs
  2525. for base in finddirs(path):
  2526. if dirs[base] > 1:
  2527. dirs[base] -= 1
  2528. return
  2529. del dirs[base]
  2530. def __iter__(self):
  2531. return self._dirs.iterkeys()
  2532. def __contains__(self, d):
  2533. return d in self._dirs
  2534. if safehasattr(parsers, 'dirs'):
  2535. dirs = parsers.dirs
  2536. def finddirs(path):
  2537. pos = path.rfind('/')
  2538. while pos != -1:
  2539. yield path[:pos]
  2540. pos = path.rfind('/', 0, pos)
  2541. class ctxmanager(object):
  2542. '''A context manager for use in 'with' blocks to allow multiple
  2543. contexts to be entered at once. This is both safer and more
  2544. flexible than contextlib.nested.
  2545. Once Mercurial supports Python 2.7+, this will become mostly
  2546. unnecessary.
  2547. '''
  2548. def __init__(self, *args):
  2549. '''Accepts a list of no-argument functions that return context
  2550. managers. These will be invoked at __call__ time.'''
  2551. self._pending = args
  2552. self._atexit = []
  2553. def __enter__(self):
  2554. return self
  2555. def enter(self):
  2556. '''Create and enter context managers in the order in which they were
  2557. passed to the constructor.'''
  2558. values = []
  2559. for func in self._pending:
  2560. obj = func()
  2561. values.append(obj.__enter__())
  2562. self._atexit.append(obj.__exit__)
  2563. del self._pending
  2564. return values
  2565. def atexit(self, func, *args, **kwargs):
  2566. '''Add a function to call when this context manager exits. The
  2567. ordering of multiple atexit calls is unspecified, save that
  2568. they will happen before any __exit__ functions.'''
  2569. def wrapper(exc_type, exc_val, exc_tb):
  2570. func(*args, **kwargs)
  2571. self._atexit.append(wrapper)
  2572. return func
  2573. def __exit__(self, exc_type, exc_val, exc_tb):
  2574. '''Context managers are exited in the reverse order from which
  2575. they were created.'''
  2576. received = exc_type is not None
  2577. suppressed = False
  2578. pending = None
  2579. self._atexit.reverse()
  2580. for exitfunc in self._atexit:
  2581. try:
  2582. if exitfunc(exc_type, exc_val, exc_tb):
  2583. suppressed = True
  2584. exc_type = None
  2585. exc_val = None
  2586. exc_tb = None
  2587. except BaseException:
  2588. pending = sys.exc_info()
  2589. exc_type, exc_val, exc_tb = pending = sys.exc_info()
  2590. del self._atexit
  2591. if pending:
  2592. raise exc_val
  2593. return received and suppressed
  2594. # compression code
  2595. SERVERROLE = 'server'
  2596. CLIENTROLE = 'client'
  2597. compewireprotosupport = collections.namedtuple(u'compenginewireprotosupport',
  2598. (u'name', u'serverpriority',
  2599. u'clientpriority'))
  2600. class compressormanager(object):
  2601. """Holds registrations of various compression engines.
  2602. This class essentially abstracts the differences between compression
  2603. engines to allow new compression formats to be added easily, possibly from
  2604. extensions.
  2605. Compressors are registered against the global instance by calling its
  2606. ``register()`` method.
  2607. """
  2608. def __init__(self):
  2609. self._engines = {}
  2610. # Bundle spec human name to engine name.
  2611. self._bundlenames = {}
  2612. # Internal bundle identifier to engine name.
  2613. self._bundletypes = {}
  2614. # Revlog header to engine name.
  2615. self._revlogheaders = {}
  2616. # Wire proto identifier to engine name.
  2617. self._wiretypes = {}
  2618. def __getitem__(self, key):
  2619. return self._engines[key]
  2620. def __contains__(self, key):
  2621. return key in self._engines
  2622. def __iter__(self):
  2623. return iter(self._engines.keys())
  2624. def register(self, engine):
  2625. """Register a compression engine with the manager.
  2626. The argument must be a ``compressionengine`` instance.
  2627. """
  2628. if not isinstance(engine, compressionengine):
  2629. raise ValueError(_('argument must be a compressionengine'))
  2630. name = engine.name()
  2631. if name in self._engines:
  2632. raise error.Abort(_('compression engine %s already registered') %
  2633. name)
  2634. bundleinfo = engine.bundletype()
  2635. if bundleinfo:
  2636. bundlename, bundletype = bundleinfo
  2637. if bundlename in self._bundlenames:
  2638. raise error.Abort(_('bundle name %s already registered') %
  2639. bundlename)
  2640. if bundletype in self._bundletypes:
  2641. raise error.Abort(_('bundle type %s already registered by %s') %
  2642. (bundletype, self._bundletypes[bundletype]))
  2643. # No external facing name declared.
  2644. if bundlename:
  2645. self._bundlenames[bundlename] = name
  2646. self._bundletypes[bundletype] = name
  2647. wiresupport = engine.wireprotosupport()
  2648. if wiresupport:
  2649. wiretype = wiresupport.name
  2650. if wiretype in self._wiretypes:
  2651. raise error.Abort(_('wire protocol compression %s already '
  2652. 'registered by %s') %
  2653. (wiretype, self._wiretypes[wiretype]))
  2654. self._wiretypes[wiretype] = name
  2655. revlogheader = engine.revlogheader()
  2656. if revlogheader and revlogheader in self._revlogheaders:
  2657. raise error.Abort(_('revlog header %s already registered by %s') %
  2658. (revlogheader, self._revlogheaders[revlogheader]))
  2659. if revlogheader:
  2660. self._revlogheaders[revlogheader] = name
  2661. self._engines[name] = engine
  2662. @property
  2663. def supportedbundlenames(self):
  2664. return set(self._bundlenames.keys())
  2665. @property
  2666. def supportedbundletypes(self):
  2667. return set(self._bundletypes.keys())
  2668. def forbundlename(self, bundlename):
  2669. """Obtain a compression engine registered to a bundle name.
  2670. Will raise KeyError if the bundle type isn't registered.
  2671. Will abort if the engine is known but not available.
  2672. """
  2673. engine = self._engines[self._bundlenames[bundlename]]
  2674. if not engine.available():
  2675. raise error.Abort(_('compression engine %s could not be loaded') %
  2676. engine.name())
  2677. return engine
  2678. def forbundletype(self, bundletype):
  2679. """Obtain a compression engine registered to a bundle type.
  2680. Will raise KeyError if the bundle type isn't registered.
  2681. Will abort if the engine is known but not available.
  2682. """
  2683. engine = self._engines[self._bundletypes[bundletype]]
  2684. if not engine.available():
  2685. raise error.Abort(_('compression engine %s could not be loaded') %
  2686. engine.name())
  2687. return engine
  2688. def supportedwireengines(self, role, onlyavailable=True):
  2689. """Obtain compression engines that support the wire protocol.
  2690. Returns a list of engines in prioritized order, most desired first.
  2691. If ``onlyavailable`` is set, filter out engines that can't be
  2692. loaded.
  2693. """
  2694. assert role in (SERVERROLE, CLIENTROLE)
  2695. attr = 'serverpriority' if role == SERVERROLE else 'clientpriority'
  2696. engines = [self._engines[e] for e in self._wiretypes.values()]
  2697. if onlyavailable:
  2698. engines = [e for e in engines if e.available()]
  2699. def getkey(e):
  2700. # Sort first by priority, highest first. In case of tie, sort
  2701. # alphabetically. This is arbitrary, but ensures output is
  2702. # stable.
  2703. w = e.wireprotosupport()
  2704. return -1 * getattr(w, attr), w.name
  2705. return list(sorted(engines, key=getkey))
  2706. def forwiretype(self, wiretype):
  2707. engine = self._engines[self._wiretypes[wiretype]]
  2708. if not engine.available():
  2709. raise error.Abort(_('compression engine %s could not be loaded') %
  2710. engine.name())
  2711. return engine
  2712. def forrevlogheader(self, header):
  2713. """Obtain a compression engine registered to a revlog header.
  2714. Will raise KeyError if the revlog header value isn't registered.
  2715. """
  2716. return self._engines[self._revlogheaders[header]]
  2717. compengines = compressormanager()
  2718. class compressionengine(object):
  2719. """Base class for compression engines.
  2720. Compression engines must implement the interface defined by this class.
  2721. """
  2722. def name(self):
  2723. """Returns the name of the compression engine.
  2724. This is the key the engine is registered under.
  2725. This method must be implemented.
  2726. """
  2727. raise NotImplementedError()
  2728. def available(self):
  2729. """Whether the compression engine is available.
  2730. The intent of this method is to allow optional compression engines
  2731. that may not be available in all installations (such as engines relying
  2732. on C extensions that may not be present).
  2733. """
  2734. return True
  2735. def bundletype(self):
  2736. """Describes bundle identifiers for this engine.
  2737. If this compression engine isn't supported for bundles, returns None.
  2738. If this engine can be used for bundles, returns a 2-tuple of strings of
  2739. the user-facing "bundle spec" compression name and an internal
  2740. identifier used to denote the compression format within bundles. To
  2741. exclude the name from external usage, set the first element to ``None``.
  2742. If bundle compression is supported, the class must also implement
  2743. ``compressstream`` and `decompressorreader``.
  2744. """
  2745. return None
  2746. def wireprotosupport(self):
  2747. """Declare support for this compression format on the wire protocol.
  2748. If this compression engine isn't supported for compressing wire
  2749. protocol payloads, returns None.
  2750. Otherwise, returns ``compenginewireprotosupport`` with the following
  2751. fields:
  2752. * String format identifier
  2753. * Integer priority for the server
  2754. * Integer priority for the client
  2755. The integer priorities are used to order the advertisement of format
  2756. support by server and client. The highest integer is advertised
  2757. first. Integers with non-positive values aren't advertised.
  2758. The priority values are somewhat arbitrary and only used for default
  2759. ordering. The relative order can be changed via config options.
  2760. If wire protocol compression is supported, the class must also implement
  2761. ``compressstream`` and ``decompressorreader``.
  2762. """
  2763. return None
  2764. def revlogheader(self):
  2765. """Header added to revlog chunks that identifies this engine.
  2766. If this engine can be used to compress revlogs, this method should
  2767. return the bytes used to identify chunks compressed with this engine.
  2768. Else, the method should return ``None`` to indicate it does not
  2769. participate in revlog compression.
  2770. """
  2771. return None
  2772. def compressstream(self, it, opts=None):
  2773. """Compress an iterator of chunks.
  2774. The method receives an iterator (ideally a generator) of chunks of
  2775. bytes to be compressed. It returns an iterator (ideally a generator)
  2776. of bytes of chunks representing the compressed output.
  2777. Optionally accepts an argument defining how to perform compression.
  2778. Each engine treats this argument differently.
  2779. """
  2780. raise NotImplementedError()
  2781. def decompressorreader(self, fh):
  2782. """Perform decompression on a file object.
  2783. Argument is an object with a ``read(size)`` method that returns
  2784. compressed data. Return value is an object with a ``read(size)`` that
  2785. returns uncompressed data.
  2786. """
  2787. raise NotImplementedError()
  2788. def revlogcompressor(self, opts=None):
  2789. """Obtain an object that can be used to compress revlog entries.
  2790. The object has a ``compress(data)`` method that compresses binary
  2791. data. This method returns compressed binary data or ``None`` if
  2792. the data could not be compressed (too small, not compressible, etc).
  2793. The returned data should have a header uniquely identifying this
  2794. compression format so decompression can be routed to this engine.
  2795. This header should be identified by the ``revlogheader()`` return
  2796. value.
  2797. The object has a ``decompress(data)`` method that decompresses
  2798. data. The method will only be called if ``data`` begins with
  2799. ``revlogheader()``. The method should return the raw, uncompressed
  2800. data or raise a ``RevlogError``.
  2801. The object is reusable but is not thread safe.
  2802. """
  2803. raise NotImplementedError()
  2804. class _zlibengine(compressionengine):
  2805. def name(self):
  2806. return 'zlib'
  2807. def bundletype(self):
  2808. return 'gzip', 'GZ'
  2809. def wireprotosupport(self):
  2810. return compewireprotosupport('zlib', 20, 20)
  2811. def revlogheader(self):
  2812. return 'x'
  2813. def compressstream(self, it, opts=None):
  2814. opts = opts or {}
  2815. z = zlib.compressobj(opts.get('level', -1))
  2816. for chunk in it:
  2817. data = z.compress(chunk)
  2818. # Not all calls to compress emit data. It is cheaper to inspect
  2819. # here than to feed empty chunks through generator.
  2820. if data:
  2821. yield data
  2822. yield z.flush()
  2823. def decompressorreader(self, fh):
  2824. def gen():
  2825. d = zlib.decompressobj()
  2826. for chunk in filechunkiter(fh):
  2827. while chunk:
  2828. # Limit output size to limit memory.
  2829. yield d.decompress(chunk, 2 ** 18)
  2830. chunk = d.unconsumed_tail
  2831. return chunkbuffer(gen())
  2832. class zlibrevlogcompressor(object):
  2833. def compress(self, data):
  2834. insize = len(data)
  2835. # Caller handles empty input case.
  2836. assert insize > 0
  2837. if insize < 44:
  2838. return None
  2839. elif insize <= 1000000:
  2840. compressed = zlib.compress(data)
  2841. if len(compressed) < insize:
  2842. return compressed
  2843. return None
  2844. # zlib makes an internal copy of the input buffer, doubling
  2845. # memory usage for large inputs. So do streaming compression
  2846. # on large inputs.
  2847. else:
  2848. z = zlib.compressobj()
  2849. parts = []
  2850. pos = 0
  2851. while pos < insize:
  2852. pos2 = pos + 2**20
  2853. parts.append(z.compress(data[pos:pos2]))
  2854. pos = pos2
  2855. parts.append(z.flush())
  2856. if sum(map(len, parts)) < insize:
  2857. return ''.join(parts)
  2858. return None
  2859. def decompress(self, data):
  2860. try:
  2861. return zlib.decompress(data)
  2862. except zlib.error as e:
  2863. raise error.RevlogError(_('revlog decompress error: %s') %
  2864. str(e))
  2865. def revlogcompressor(self, opts=None):
  2866. return self.zlibrevlogcompressor()
  2867. compengines.register(_zlibengine())
  2868. class _bz2engine(compressionengine):
  2869. def name(self):
  2870. return 'bz2'
  2871. def bundletype(self):
  2872. return 'bzip2', 'BZ'
  2873. # We declare a protocol name but don't advertise by default because
  2874. # it is slow.
  2875. def wireprotosupport(self):
  2876. return compewireprotosupport('bzip2', 0, 0)
  2877. def compressstream(self, it, opts=None):
  2878. opts = opts or {}
  2879. z = bz2.BZ2Compressor(opts.get('level', 9))
  2880. for chunk in it:
  2881. data = z.compress(chunk)
  2882. if data:
  2883. yield data
  2884. yield z.flush()
  2885. def decompressorreader(self, fh):
  2886. def gen():
  2887. d = bz2.BZ2Decompressor()
  2888. for chunk in filechunkiter(fh):
  2889. yield d.decompress(chunk)
  2890. return chunkbuffer(gen())
  2891. compengines.register(_bz2engine())
  2892. class _truncatedbz2engine(compressionengine):
  2893. def name(self):
  2894. return 'bz2truncated'
  2895. def bundletype(self):
  2896. return None, '_truncatedBZ'
  2897. # We don't implement compressstream because it is hackily handled elsewhere.
  2898. def decompressorreader(self, fh):
  2899. def gen():
  2900. # The input stream doesn't have the 'BZ' header. So add it back.
  2901. d = bz2.BZ2Decompressor()
  2902. d.decompress('BZ')
  2903. for chunk in filechunkiter(fh):
  2904. yield d.decompress(chunk)
  2905. return chunkbuffer(gen())
  2906. compengines.register(_truncatedbz2engine())
  2907. class _noopengine(compressionengine):
  2908. def name(self):
  2909. return 'none'
  2910. def bundletype(self):
  2911. return 'none', 'UN'
  2912. # Clients always support uncompressed payloads. Servers don't because
  2913. # unless you are on a fast network, uncompressed payloads can easily
  2914. # saturate your network pipe.
  2915. def wireprotosupport(self):
  2916. return compewireprotosupport('none', 0, 10)
  2917. # We don't implement revlogheader because it is handled specially
  2918. # in the revlog class.
  2919. def compressstream(self, it, opts=None):
  2920. return it
  2921. def decompressorreader(self, fh):
  2922. return fh
  2923. class nooprevlogcompressor(object):
  2924. def compress(self, data):
  2925. return None
  2926. def revlogcompressor(self, opts=None):
  2927. return self.nooprevlogcompressor()
  2928. compengines.register(_noopengine())
  2929. class _zstdengine(compressionengine):
  2930. def name(self):
  2931. return 'zstd'
  2932. @propertycache
  2933. def _module(self):
  2934. # Not all installs have the zstd module available. So defer importing
  2935. # until first access.
  2936. try:
  2937. from . import zstd
  2938. # Force delayed import.
  2939. zstd.__version__
  2940. return zstd
  2941. except ImportError:
  2942. return None
  2943. def available(self):
  2944. return bool(self._module)
  2945. def bundletype(self):
  2946. return 'zstd', 'ZS'
  2947. def wireprotosupport(self):
  2948. return compewireprotosupport('zstd', 50, 50)
  2949. def revlogheader(self):
  2950. return '\x28'
  2951. def compressstream(self, it, opts=None):
  2952. opts = opts or {}
  2953. # zstd level 3 is almost always significantly faster than zlib
  2954. # while providing no worse compression. It strikes a good balance
  2955. # between speed and compression.
  2956. level = opts.get('level', 3)
  2957. zstd = self._module
  2958. z = zstd.ZstdCompressor(level=level).compressobj()
  2959. for chunk in it:
  2960. data = z.compress(chunk)
  2961. if data:
  2962. yield data
  2963. yield z.flush()
  2964. def decompressorreader(self, fh):
  2965. zstd = self._module
  2966. dctx = zstd.ZstdDecompressor()
  2967. return chunkbuffer(dctx.read_from(fh))
  2968. class zstdrevlogcompressor(object):
  2969. def __init__(self, zstd, level=3):
  2970. # Writing the content size adds a few bytes to the output. However,
  2971. # it allows decompression to be more optimal since we can
  2972. # pre-allocate a buffer to hold the result.
  2973. self._cctx = zstd.ZstdCompressor(level=level,
  2974. write_content_size=True)
  2975. self._dctx = zstd.ZstdDecompressor()
  2976. self._compinsize = zstd.COMPRESSION_RECOMMENDED_INPUT_SIZE
  2977. self._decompinsize = zstd.DECOMPRESSION_RECOMMENDED_INPUT_SIZE
  2978. def compress(self, data):
  2979. insize = len(data)
  2980. # Caller handles empty input case.
  2981. assert insize > 0
  2982. if insize < 50:
  2983. return None
  2984. elif insize <= 1000000:
  2985. compressed = self._cctx.compress(data)
  2986. if len(compressed) < insize:
  2987. return compressed
  2988. return None
  2989. else:
  2990. z = self._cctx.compressobj()
  2991. chunks = []
  2992. pos = 0
  2993. while pos < insize:
  2994. pos2 = pos + self._compinsize
  2995. chunk = z.compress(data[pos:pos2])
  2996. if chunk:
  2997. chunks.append(chunk)
  2998. pos = pos2
  2999. chunks.append(z.flush())
  3000. if sum(map(len, chunks)) < insize:
  3001. return ''.join(chunks)
  3002. return None
  3003. def decompress(self, data):
  3004. insize = len(data)
  3005. try:
  3006. # This was measured to be faster than other streaming
  3007. # decompressors.
  3008. dobj = self._dctx.decompressobj()
  3009. chunks = []
  3010. pos = 0
  3011. while pos < insize:
  3012. pos2 = pos + self._decompinsize
  3013. chunk = dobj.decompress(data[pos:pos2])
  3014. if chunk:
  3015. chunks.append(chunk)
  3016. pos = pos2
  3017. # Frame should be exhausted, so no finish() API.
  3018. return ''.join(chunks)
  3019. except Exception as e:
  3020. raise error.RevlogError(_('revlog decompress error: %s') %
  3021. str(e))
  3022. def revlogcompressor(self, opts=None):
  3023. opts = opts or {}
  3024. return self.zstdrevlogcompressor(self._module,
  3025. level=opts.get('level', 3))
  3026. compengines.register(_zstdengine())
  3027. # convenient shortcut
  3028. dst = debugstacktrace