PageRenderTime 34ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/mercurial/util.py

https://bitbucket.org/mirror/mercurial/
Python | 2039 lines | 1917 code | 51 blank | 71 comment | 106 complexity | 3007f2ca76ea962255560f64e1d827f8 MD5 | raw file
Possible License(s): GPL-2.0
  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 i18n import _
  14. import error, osutil, encoding
  15. import errno, re, shutil, sys, tempfile, traceback
  16. import os, time, datetime, calendar, textwrap, signal, collections
  17. import imp, socket, urllib
  18. if os.name == 'nt':
  19. import windows as platform
  20. else:
  21. import posix as platform
  22. cachestat = platform.cachestat
  23. checkexec = platform.checkexec
  24. checklink = platform.checklink
  25. copymode = platform.copymode
  26. executablepath = platform.executablepath
  27. expandglobs = platform.expandglobs
  28. explainexit = platform.explainexit
  29. findexe = platform.findexe
  30. gethgcmd = platform.gethgcmd
  31. getuser = platform.getuser
  32. groupmembers = platform.groupmembers
  33. groupname = platform.groupname
  34. hidewindow = platform.hidewindow
  35. isexec = platform.isexec
  36. isowner = platform.isowner
  37. localpath = platform.localpath
  38. lookupreg = platform.lookupreg
  39. makedir = platform.makedir
  40. nlinks = platform.nlinks
  41. normpath = platform.normpath
  42. normcase = platform.normcase
  43. openhardlinks = platform.openhardlinks
  44. oslink = platform.oslink
  45. parsepatchoutput = platform.parsepatchoutput
  46. pconvert = platform.pconvert
  47. popen = platform.popen
  48. posixfile = platform.posixfile
  49. quotecommand = platform.quotecommand
  50. rename = platform.rename
  51. samedevice = platform.samedevice
  52. samefile = platform.samefile
  53. samestat = platform.samestat
  54. setbinary = platform.setbinary
  55. setflags = platform.setflags
  56. setsignalhandler = platform.setsignalhandler
  57. shellquote = platform.shellquote
  58. spawndetached = platform.spawndetached
  59. split = platform.split
  60. sshargs = platform.sshargs
  61. statfiles = getattr(osutil, 'statfiles', platform.statfiles)
  62. statisexec = platform.statisexec
  63. statislink = platform.statislink
  64. termwidth = platform.termwidth
  65. testpid = platform.testpid
  66. umask = platform.umask
  67. unlink = platform.unlink
  68. unlinkpath = platform.unlinkpath
  69. username = platform.username
  70. # Python compatibility
  71. _notset = object()
  72. def safehasattr(thing, attr):
  73. return getattr(thing, attr, _notset) is not _notset
  74. def sha1(s=''):
  75. '''
  76. Low-overhead wrapper around Python's SHA support
  77. >>> f = _fastsha1
  78. >>> a = sha1()
  79. >>> a = f()
  80. >>> a.hexdigest()
  81. 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
  82. '''
  83. return _fastsha1(s)
  84. def _fastsha1(s=''):
  85. # This function will import sha1 from hashlib or sha (whichever is
  86. # available) and overwrite itself with it on the first call.
  87. # Subsequent calls will go directly to the imported function.
  88. if sys.version_info >= (2, 5):
  89. from hashlib import sha1 as _sha1
  90. else:
  91. from sha import sha as _sha1
  92. global _fastsha1, sha1
  93. _fastsha1 = sha1 = _sha1
  94. return _sha1(s)
  95. try:
  96. buffer = buffer
  97. except NameError:
  98. if sys.version_info[0] < 3:
  99. def buffer(sliceable, offset=0):
  100. return sliceable[offset:]
  101. else:
  102. def buffer(sliceable, offset=0):
  103. return memoryview(sliceable)[offset:]
  104. import subprocess
  105. closefds = os.name == 'posix'
  106. def popen2(cmd, env=None, newlines=False):
  107. # Setting bufsize to -1 lets the system decide the buffer size.
  108. # The default for bufsize is 0, meaning unbuffered. This leads to
  109. # poor performance on Mac OS X: http://bugs.python.org/issue4194
  110. p = subprocess.Popen(cmd, shell=True, bufsize=-1,
  111. close_fds=closefds,
  112. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  113. universal_newlines=newlines,
  114. env=env)
  115. return p.stdin, p.stdout
  116. def popen3(cmd, env=None, newlines=False):
  117. stdin, stdout, stderr, p = popen4(cmd, env, newlines)
  118. return stdin, stdout, stderr
  119. def popen4(cmd, env=None, newlines=False):
  120. p = subprocess.Popen(cmd, shell=True, bufsize=-1,
  121. close_fds=closefds,
  122. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  123. stderr=subprocess.PIPE,
  124. universal_newlines=newlines,
  125. env=env)
  126. return p.stdin, p.stdout, p.stderr, p
  127. def version():
  128. """Return version information if available."""
  129. try:
  130. import __version__
  131. return __version__.version
  132. except ImportError:
  133. return 'unknown'
  134. # used by parsedate
  135. defaultdateformats = (
  136. '%Y-%m-%d %H:%M:%S',
  137. '%Y-%m-%d %I:%M:%S%p',
  138. '%Y-%m-%d %H:%M',
  139. '%Y-%m-%d %I:%M%p',
  140. '%Y-%m-%d',
  141. '%m-%d',
  142. '%m/%d',
  143. '%m/%d/%y',
  144. '%m/%d/%Y',
  145. '%a %b %d %H:%M:%S %Y',
  146. '%a %b %d %I:%M:%S%p %Y',
  147. '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
  148. '%b %d %H:%M:%S %Y',
  149. '%b %d %I:%M:%S%p %Y',
  150. '%b %d %H:%M:%S',
  151. '%b %d %I:%M:%S%p',
  152. '%b %d %H:%M',
  153. '%b %d %I:%M%p',
  154. '%b %d %Y',
  155. '%b %d',
  156. '%H:%M:%S',
  157. '%I:%M:%S%p',
  158. '%H:%M',
  159. '%I:%M%p',
  160. )
  161. extendeddateformats = defaultdateformats + (
  162. "%Y",
  163. "%Y-%m",
  164. "%b",
  165. "%b %Y",
  166. )
  167. def cachefunc(func):
  168. '''cache the result of function calls'''
  169. # XXX doesn't handle keywords args
  170. if func.func_code.co_argcount == 0:
  171. cache = []
  172. def f():
  173. if len(cache) == 0:
  174. cache.append(func())
  175. return cache[0]
  176. return f
  177. cache = {}
  178. if func.func_code.co_argcount == 1:
  179. # we gain a small amount of time because
  180. # we don't need to pack/unpack the list
  181. def f(arg):
  182. if arg not in cache:
  183. cache[arg] = func(arg)
  184. return cache[arg]
  185. else:
  186. def f(*args):
  187. if args not in cache:
  188. cache[args] = func(*args)
  189. return cache[args]
  190. return f
  191. try:
  192. collections.deque.remove
  193. deque = collections.deque
  194. except AttributeError:
  195. # python 2.4 lacks deque.remove
  196. class deque(collections.deque):
  197. def remove(self, val):
  198. for i, v in enumerate(self):
  199. if v == val:
  200. del self[i]
  201. break
  202. class sortdict(dict):
  203. '''a simple sorted dictionary'''
  204. def __init__(self, data=None):
  205. self._list = []
  206. if data:
  207. self.update(data)
  208. def copy(self):
  209. return sortdict(self)
  210. def __setitem__(self, key, val):
  211. if key in self:
  212. self._list.remove(key)
  213. self._list.append(key)
  214. dict.__setitem__(self, key, val)
  215. def __iter__(self):
  216. return self._list.__iter__()
  217. def update(self, src):
  218. for k in src:
  219. self[k] = src[k]
  220. def clear(self):
  221. dict.clear(self)
  222. self._list = []
  223. def items(self):
  224. return [(k, self[k]) for k in self._list]
  225. def __delitem__(self, key):
  226. dict.__delitem__(self, key)
  227. self._list.remove(key)
  228. def keys(self):
  229. return self._list
  230. def iterkeys(self):
  231. return self._list.__iter__()
  232. class lrucachedict(object):
  233. '''cache most recent gets from or sets to this dictionary'''
  234. def __init__(self, maxsize):
  235. self._cache = {}
  236. self._maxsize = maxsize
  237. self._order = deque()
  238. def __getitem__(self, key):
  239. value = self._cache[key]
  240. self._order.remove(key)
  241. self._order.append(key)
  242. return value
  243. def __setitem__(self, key, value):
  244. if key not in self._cache:
  245. if len(self._cache) >= self._maxsize:
  246. del self._cache[self._order.popleft()]
  247. else:
  248. self._order.remove(key)
  249. self._cache[key] = value
  250. self._order.append(key)
  251. def __contains__(self, key):
  252. return key in self._cache
  253. def clear(self):
  254. self._cache.clear()
  255. self._order = deque()
  256. def lrucachefunc(func):
  257. '''cache most recent results of function calls'''
  258. cache = {}
  259. order = deque()
  260. if func.func_code.co_argcount == 1:
  261. def f(arg):
  262. if arg not in cache:
  263. if len(cache) > 20:
  264. del cache[order.popleft()]
  265. cache[arg] = func(arg)
  266. else:
  267. order.remove(arg)
  268. order.append(arg)
  269. return cache[arg]
  270. else:
  271. def f(*args):
  272. if args not in cache:
  273. if len(cache) > 20:
  274. del cache[order.popleft()]
  275. cache[args] = func(*args)
  276. else:
  277. order.remove(args)
  278. order.append(args)
  279. return cache[args]
  280. return f
  281. class propertycache(object):
  282. def __init__(self, func):
  283. self.func = func
  284. self.name = func.__name__
  285. def __get__(self, obj, type=None):
  286. result = self.func(obj)
  287. self.cachevalue(obj, result)
  288. return result
  289. def cachevalue(self, obj, value):
  290. # __dict__ assignment required to bypass __setattr__ (eg: repoview)
  291. obj.__dict__[self.name] = value
  292. def pipefilter(s, cmd):
  293. '''filter string S through command CMD, returning its output'''
  294. p = subprocess.Popen(cmd, shell=True, close_fds=closefds,
  295. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  296. pout, perr = p.communicate(s)
  297. return pout
  298. def tempfilter(s, cmd):
  299. '''filter string S through a pair of temporary files with CMD.
  300. CMD is used as a template to create the real command to be run,
  301. with the strings INFILE and OUTFILE replaced by the real names of
  302. the temporary files generated.'''
  303. inname, outname = None, None
  304. try:
  305. infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
  306. fp = os.fdopen(infd, 'wb')
  307. fp.write(s)
  308. fp.close()
  309. outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
  310. os.close(outfd)
  311. cmd = cmd.replace('INFILE', inname)
  312. cmd = cmd.replace('OUTFILE', outname)
  313. code = os.system(cmd)
  314. if sys.platform == 'OpenVMS' and code & 1:
  315. code = 0
  316. if code:
  317. raise Abort(_("command '%s' failed: %s") %
  318. (cmd, explainexit(code)))
  319. fp = open(outname, 'rb')
  320. r = fp.read()
  321. fp.close()
  322. return r
  323. finally:
  324. try:
  325. if inname:
  326. os.unlink(inname)
  327. except OSError:
  328. pass
  329. try:
  330. if outname:
  331. os.unlink(outname)
  332. except OSError:
  333. pass
  334. filtertable = {
  335. 'tempfile:': tempfilter,
  336. 'pipe:': pipefilter,
  337. }
  338. def filter(s, cmd):
  339. "filter a string through a command that transforms its input to its output"
  340. for name, fn in filtertable.iteritems():
  341. if cmd.startswith(name):
  342. return fn(s, cmd[len(name):].lstrip())
  343. return pipefilter(s, cmd)
  344. def binary(s):
  345. """return true if a string is binary data"""
  346. return bool(s and '\0' in s)
  347. def increasingchunks(source, min=1024, max=65536):
  348. '''return no less than min bytes per chunk while data remains,
  349. doubling min after each chunk until it reaches max'''
  350. def log2(x):
  351. if not x:
  352. return 0
  353. i = 0
  354. while x:
  355. x >>= 1
  356. i += 1
  357. return i - 1
  358. buf = []
  359. blen = 0
  360. for chunk in source:
  361. buf.append(chunk)
  362. blen += len(chunk)
  363. if blen >= min:
  364. if min < max:
  365. min = min << 1
  366. nmin = 1 << log2(blen)
  367. if nmin > min:
  368. min = nmin
  369. if min > max:
  370. min = max
  371. yield ''.join(buf)
  372. blen = 0
  373. buf = []
  374. if buf:
  375. yield ''.join(buf)
  376. Abort = error.Abort
  377. def always(fn):
  378. return True
  379. def never(fn):
  380. return False
  381. def pathto(root, n1, n2):
  382. '''return the relative path from one place to another.
  383. root should use os.sep to separate directories
  384. n1 should use os.sep to separate directories
  385. n2 should use "/" to separate directories
  386. returns an os.sep-separated path.
  387. If n1 is a relative path, it's assumed it's
  388. relative to root.
  389. n2 should always be relative to root.
  390. '''
  391. if not n1:
  392. return localpath(n2)
  393. if os.path.isabs(n1):
  394. if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
  395. return os.path.join(root, localpath(n2))
  396. n2 = '/'.join((pconvert(root), n2))
  397. a, b = splitpath(n1), n2.split('/')
  398. a.reverse()
  399. b.reverse()
  400. while a and b and a[-1] == b[-1]:
  401. a.pop()
  402. b.pop()
  403. b.reverse()
  404. return os.sep.join((['..'] * len(a)) + b) or '.'
  405. _hgexecutable = None
  406. def mainfrozen():
  407. """return True if we are a frozen executable.
  408. The code supports py2exe (most common, Windows only) and tools/freeze
  409. (portable, not much used).
  410. """
  411. return (safehasattr(sys, "frozen") or # new py2exe
  412. safehasattr(sys, "importers") or # old py2exe
  413. imp.is_frozen("__main__")) # tools/freeze
  414. def hgexecutable():
  415. """return location of the 'hg' executable.
  416. Defaults to $HG or 'hg' in the search path.
  417. """
  418. if _hgexecutable is None:
  419. hg = os.environ.get('HG')
  420. mainmod = sys.modules['__main__']
  421. if hg:
  422. _sethgexecutable(hg)
  423. elif mainfrozen():
  424. _sethgexecutable(sys.executable)
  425. elif os.path.basename(getattr(mainmod, '__file__', '')) == 'hg':
  426. _sethgexecutable(mainmod.__file__)
  427. else:
  428. exe = findexe('hg') or os.path.basename(sys.argv[0])
  429. _sethgexecutable(exe)
  430. return _hgexecutable
  431. def _sethgexecutable(path):
  432. """set location of the 'hg' executable"""
  433. global _hgexecutable
  434. _hgexecutable = path
  435. def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None, out=None):
  436. '''enhanced shell command execution.
  437. run with environment maybe modified, maybe in different dir.
  438. if command fails and onerr is None, return status. if ui object,
  439. print error message and return status, else raise onerr object as
  440. exception.
  441. if out is specified, it is assumed to be a file-like object that has a
  442. write() method. stdout and stderr will be redirected to out.'''
  443. try:
  444. sys.stdout.flush()
  445. except Exception:
  446. pass
  447. def py2shell(val):
  448. 'convert python object into string that is useful to shell'
  449. if val is None or val is False:
  450. return '0'
  451. if val is True:
  452. return '1'
  453. return str(val)
  454. origcmd = cmd
  455. cmd = quotecommand(cmd)
  456. if sys.platform == 'plan9' and (sys.version_info[0] == 2
  457. and sys.version_info[1] < 7):
  458. # subprocess kludge to work around issues in half-baked Python
  459. # ports, notably bichued/python:
  460. if not cwd is None:
  461. os.chdir(cwd)
  462. rc = os.system(cmd)
  463. else:
  464. env = dict(os.environ)
  465. env.update((k, py2shell(v)) for k, v in environ.iteritems())
  466. env['HG'] = hgexecutable()
  467. if out is None or out == sys.__stdout__:
  468. rc = subprocess.call(cmd, shell=True, close_fds=closefds,
  469. env=env, cwd=cwd)
  470. else:
  471. proc = subprocess.Popen(cmd, shell=True, close_fds=closefds,
  472. env=env, cwd=cwd, stdout=subprocess.PIPE,
  473. stderr=subprocess.STDOUT)
  474. for line in proc.stdout:
  475. out.write(line)
  476. proc.wait()
  477. rc = proc.returncode
  478. if sys.platform == 'OpenVMS' and rc & 1:
  479. rc = 0
  480. if rc and onerr:
  481. errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
  482. explainexit(rc)[0])
  483. if errprefix:
  484. errmsg = '%s: %s' % (errprefix, errmsg)
  485. try:
  486. onerr.warn(errmsg + '\n')
  487. except AttributeError:
  488. raise onerr(errmsg)
  489. return rc
  490. def checksignature(func):
  491. '''wrap a function with code to check for calling errors'''
  492. def check(*args, **kwargs):
  493. try:
  494. return func(*args, **kwargs)
  495. except TypeError:
  496. if len(traceback.extract_tb(sys.exc_info()[2])) == 1:
  497. raise error.SignatureError
  498. raise
  499. return check
  500. def copyfile(src, dest):
  501. "copy a file, preserving mode and atime/mtime"
  502. if os.path.lexists(dest):
  503. unlink(dest)
  504. if os.path.islink(src):
  505. os.symlink(os.readlink(src), dest)
  506. else:
  507. try:
  508. shutil.copyfile(src, dest)
  509. shutil.copymode(src, dest)
  510. except shutil.Error, inst:
  511. raise Abort(str(inst))
  512. def copyfiles(src, dst, hardlink=None):
  513. """Copy a directory tree using hardlinks if possible"""
  514. if hardlink is None:
  515. hardlink = (os.stat(src).st_dev ==
  516. os.stat(os.path.dirname(dst)).st_dev)
  517. num = 0
  518. if os.path.isdir(src):
  519. os.mkdir(dst)
  520. for name, kind in osutil.listdir(src):
  521. srcname = os.path.join(src, name)
  522. dstname = os.path.join(dst, name)
  523. hardlink, n = copyfiles(srcname, dstname, hardlink)
  524. num += n
  525. else:
  526. if hardlink:
  527. try:
  528. oslink(src, dst)
  529. except (IOError, OSError):
  530. hardlink = False
  531. shutil.copy(src, dst)
  532. else:
  533. shutil.copy(src, dst)
  534. num += 1
  535. return hardlink, num
  536. _winreservednames = '''con prn aux nul
  537. com1 com2 com3 com4 com5 com6 com7 com8 com9
  538. lpt1 lpt2 lpt3 lpt4 lpt5 lpt6 lpt7 lpt8 lpt9'''.split()
  539. _winreservedchars = ':*?"<>|'
  540. def checkwinfilename(path):
  541. r'''Check that the base-relative path is a valid filename on Windows.
  542. Returns None if the path is ok, or a UI string describing the problem.
  543. >>> checkwinfilename("just/a/normal/path")
  544. >>> checkwinfilename("foo/bar/con.xml")
  545. "filename contains 'con', which is reserved on Windows"
  546. >>> checkwinfilename("foo/con.xml/bar")
  547. "filename contains 'con', which is reserved on Windows"
  548. >>> checkwinfilename("foo/bar/xml.con")
  549. >>> checkwinfilename("foo/bar/AUX/bla.txt")
  550. "filename contains 'AUX', which is reserved on Windows"
  551. >>> checkwinfilename("foo/bar/bla:.txt")
  552. "filename contains ':', which is reserved on Windows"
  553. >>> checkwinfilename("foo/bar/b\07la.txt")
  554. "filename contains '\\x07', which is invalid on Windows"
  555. >>> checkwinfilename("foo/bar/bla ")
  556. "filename ends with ' ', which is not allowed on Windows"
  557. >>> checkwinfilename("../bar")
  558. >>> checkwinfilename("foo\\")
  559. "filename ends with '\\', which is invalid on Windows"
  560. >>> checkwinfilename("foo\\/bar")
  561. "directory name ends with '\\', which is invalid on Windows"
  562. '''
  563. if path.endswith('\\'):
  564. return _("filename ends with '\\', which is invalid on Windows")
  565. if '\\/' in path:
  566. return _("directory name ends with '\\', which is invalid on Windows")
  567. for n in path.replace('\\', '/').split('/'):
  568. if not n:
  569. continue
  570. for c in n:
  571. if c in _winreservedchars:
  572. return _("filename contains '%s', which is reserved "
  573. "on Windows") % c
  574. if ord(c) <= 31:
  575. return _("filename contains %r, which is invalid "
  576. "on Windows") % c
  577. base = n.split('.')[0]
  578. if base and base.lower() in _winreservednames:
  579. return _("filename contains '%s', which is reserved "
  580. "on Windows") % base
  581. t = n[-1]
  582. if t in '. ' and n not in '..':
  583. return _("filename ends with '%s', which is not allowed "
  584. "on Windows") % t
  585. if os.name == 'nt':
  586. checkosfilename = checkwinfilename
  587. else:
  588. checkosfilename = platform.checkosfilename
  589. def makelock(info, pathname):
  590. try:
  591. return os.symlink(info, pathname)
  592. except OSError, why:
  593. if why.errno == errno.EEXIST:
  594. raise
  595. except AttributeError: # no symlink in os
  596. pass
  597. ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
  598. os.write(ld, info)
  599. os.close(ld)
  600. def readlock(pathname):
  601. try:
  602. return os.readlink(pathname)
  603. except OSError, why:
  604. if why.errno not in (errno.EINVAL, errno.ENOSYS):
  605. raise
  606. except AttributeError: # no symlink in os
  607. pass
  608. fp = posixfile(pathname)
  609. r = fp.read()
  610. fp.close()
  611. return r
  612. def fstat(fp):
  613. '''stat file object that may not have fileno method.'''
  614. try:
  615. return os.fstat(fp.fileno())
  616. except AttributeError:
  617. return os.stat(fp.name)
  618. # File system features
  619. def checkcase(path):
  620. """
  621. Return true if the given path is on a case-sensitive filesystem
  622. Requires a path (like /foo/.hg) ending with a foldable final
  623. directory component.
  624. """
  625. s1 = os.stat(path)
  626. d, b = os.path.split(path)
  627. b2 = b.upper()
  628. if b == b2:
  629. b2 = b.lower()
  630. if b == b2:
  631. return True # no evidence against case sensitivity
  632. p2 = os.path.join(d, b2)
  633. try:
  634. s2 = os.stat(p2)
  635. if s2 == s1:
  636. return False
  637. return True
  638. except OSError:
  639. return True
  640. try:
  641. import re2
  642. _re2 = None
  643. except ImportError:
  644. _re2 = False
  645. def compilere(pat, flags=0):
  646. '''Compile a regular expression, using re2 if possible
  647. For best performance, use only re2-compatible regexp features. The
  648. only flags from the re module that are re2-compatible are
  649. IGNORECASE and MULTILINE.'''
  650. global _re2
  651. if _re2 is None:
  652. try:
  653. # check if match works, see issue3964
  654. _re2 = bool(re2.match(r'\[([^\[]+)\]', '[ui]'))
  655. except ImportError:
  656. _re2 = False
  657. if _re2 and (flags & ~(re.IGNORECASE | re.MULTILINE)) == 0:
  658. if flags & re.IGNORECASE:
  659. pat = '(?i)' + pat
  660. if flags & re.MULTILINE:
  661. pat = '(?m)' + pat
  662. try:
  663. return re2.compile(pat)
  664. except re2.error:
  665. pass
  666. return re.compile(pat, flags)
  667. _fspathcache = {}
  668. def fspath(name, root):
  669. '''Get name in the case stored in the filesystem
  670. The name should be relative to root, and be normcase-ed for efficiency.
  671. Note that this function is unnecessary, and should not be
  672. called, for case-sensitive filesystems (simply because it's expensive).
  673. The root should be normcase-ed, too.
  674. '''
  675. def find(p, contents):
  676. for n in contents:
  677. if normcase(n) == p:
  678. return n
  679. return None
  680. seps = os.sep
  681. if os.altsep:
  682. seps = seps + os.altsep
  683. # Protect backslashes. This gets silly very quickly.
  684. seps.replace('\\','\\\\')
  685. pattern = re.compile(r'([^%s]+)|([%s]+)' % (seps, seps))
  686. dir = os.path.normpath(root)
  687. result = []
  688. for part, sep in pattern.findall(name):
  689. if sep:
  690. result.append(sep)
  691. continue
  692. if dir not in _fspathcache:
  693. _fspathcache[dir] = os.listdir(dir)
  694. contents = _fspathcache[dir]
  695. found = find(part, contents)
  696. if not found:
  697. # retry "once per directory" per "dirstate.walk" which
  698. # may take place for each patches of "hg qpush", for example
  699. contents = os.listdir(dir)
  700. _fspathcache[dir] = contents
  701. found = find(part, contents)
  702. result.append(found or part)
  703. dir = os.path.join(dir, part)
  704. return ''.join(result)
  705. def checknlink(testfile):
  706. '''check whether hardlink count reporting works properly'''
  707. # testfile may be open, so we need a separate file for checking to
  708. # work around issue2543 (or testfile may get lost on Samba shares)
  709. f1 = testfile + ".hgtmp1"
  710. if os.path.lexists(f1):
  711. return False
  712. try:
  713. posixfile(f1, 'w').close()
  714. except IOError:
  715. return False
  716. f2 = testfile + ".hgtmp2"
  717. fd = None
  718. try:
  719. try:
  720. oslink(f1, f2)
  721. except OSError:
  722. return False
  723. # nlinks() may behave differently for files on Windows shares if
  724. # the file is open.
  725. fd = posixfile(f2)
  726. return nlinks(f2) > 1
  727. finally:
  728. if fd is not None:
  729. fd.close()
  730. for f in (f1, f2):
  731. try:
  732. os.unlink(f)
  733. except OSError:
  734. pass
  735. def endswithsep(path):
  736. '''Check path ends with os.sep or os.altsep.'''
  737. return path.endswith(os.sep) or os.altsep and path.endswith(os.altsep)
  738. def splitpath(path):
  739. '''Split path by os.sep.
  740. Note that this function does not use os.altsep because this is
  741. an alternative of simple "xxx.split(os.sep)".
  742. It is recommended to use os.path.normpath() before using this
  743. function if need.'''
  744. return path.split(os.sep)
  745. def gui():
  746. '''Are we running in a GUI?'''
  747. if sys.platform == 'darwin':
  748. if 'SSH_CONNECTION' in os.environ:
  749. # handle SSH access to a box where the user is logged in
  750. return False
  751. elif getattr(osutil, 'isgui', None):
  752. # check if a CoreGraphics session is available
  753. return osutil.isgui()
  754. else:
  755. # pure build; use a safe default
  756. return True
  757. else:
  758. return os.name == "nt" or os.environ.get("DISPLAY")
  759. def mktempcopy(name, emptyok=False, createmode=None):
  760. """Create a temporary file with the same contents from name
  761. The permission bits are copied from the original file.
  762. If the temporary file is going to be truncated immediately, you
  763. can use emptyok=True as an optimization.
  764. Returns the name of the temporary file.
  765. """
  766. d, fn = os.path.split(name)
  767. fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
  768. os.close(fd)
  769. # Temporary files are created with mode 0600, which is usually not
  770. # what we want. If the original file already exists, just copy
  771. # its mode. Otherwise, manually obey umask.
  772. copymode(name, temp, createmode)
  773. if emptyok:
  774. return temp
  775. try:
  776. try:
  777. ifp = posixfile(name, "rb")
  778. except IOError, inst:
  779. if inst.errno == errno.ENOENT:
  780. return temp
  781. if not getattr(inst, 'filename', None):
  782. inst.filename = name
  783. raise
  784. ofp = posixfile(temp, "wb")
  785. for chunk in filechunkiter(ifp):
  786. ofp.write(chunk)
  787. ifp.close()
  788. ofp.close()
  789. except: # re-raises
  790. try: os.unlink(temp)
  791. except OSError: pass
  792. raise
  793. return temp
  794. class atomictempfile(object):
  795. '''writable file object that atomically updates a file
  796. All writes will go to a temporary copy of the original file. Call
  797. close() when you are done writing, and atomictempfile will rename
  798. the temporary copy to the original name, making the changes
  799. visible. If the object is destroyed without being closed, all your
  800. writes are discarded.
  801. '''
  802. def __init__(self, name, mode='w+b', createmode=None):
  803. self.__name = name # permanent name
  804. self._tempname = mktempcopy(name, emptyok=('w' in mode),
  805. createmode=createmode)
  806. self._fp = posixfile(self._tempname, mode)
  807. # delegated methods
  808. self.write = self._fp.write
  809. self.seek = self._fp.seek
  810. self.tell = self._fp.tell
  811. self.fileno = self._fp.fileno
  812. def close(self):
  813. if not self._fp.closed:
  814. self._fp.close()
  815. rename(self._tempname, localpath(self.__name))
  816. def discard(self):
  817. if not self._fp.closed:
  818. try:
  819. os.unlink(self._tempname)
  820. except OSError:
  821. pass
  822. self._fp.close()
  823. def __del__(self):
  824. if safehasattr(self, '_fp'): # constructor actually did something
  825. self.discard()
  826. def makedirs(name, mode=None, notindexed=False):
  827. """recursive directory creation with parent mode inheritance"""
  828. try:
  829. makedir(name, notindexed)
  830. except OSError, err:
  831. if err.errno == errno.EEXIST:
  832. return
  833. if err.errno != errno.ENOENT or not name:
  834. raise
  835. parent = os.path.dirname(os.path.abspath(name))
  836. if parent == name:
  837. raise
  838. makedirs(parent, mode, notindexed)
  839. makedir(name, notindexed)
  840. if mode is not None:
  841. os.chmod(name, mode)
  842. def ensuredirs(name, mode=None):
  843. """race-safe recursive directory creation"""
  844. if os.path.isdir(name):
  845. return
  846. parent = os.path.dirname(os.path.abspath(name))
  847. if parent != name:
  848. ensuredirs(parent, mode)
  849. try:
  850. os.mkdir(name)
  851. except OSError, err:
  852. if err.errno == errno.EEXIST and os.path.isdir(name):
  853. # someone else seems to have won a directory creation race
  854. return
  855. raise
  856. if mode is not None:
  857. os.chmod(name, mode)
  858. def readfile(path):
  859. fp = open(path, 'rb')
  860. try:
  861. return fp.read()
  862. finally:
  863. fp.close()
  864. def writefile(path, text):
  865. fp = open(path, 'wb')
  866. try:
  867. fp.write(text)
  868. finally:
  869. fp.close()
  870. def appendfile(path, text):
  871. fp = open(path, 'ab')
  872. try:
  873. fp.write(text)
  874. finally:
  875. fp.close()
  876. class chunkbuffer(object):
  877. """Allow arbitrary sized chunks of data to be efficiently read from an
  878. iterator over chunks of arbitrary size."""
  879. def __init__(self, in_iter):
  880. """in_iter is the iterator that's iterating over the input chunks.
  881. targetsize is how big a buffer to try to maintain."""
  882. def splitbig(chunks):
  883. for chunk in chunks:
  884. if len(chunk) > 2**20:
  885. pos = 0
  886. while pos < len(chunk):
  887. end = pos + 2 ** 18
  888. yield chunk[pos:end]
  889. pos = end
  890. else:
  891. yield chunk
  892. self.iter = splitbig(in_iter)
  893. self._queue = deque()
  894. def read(self, l=None):
  895. """Read L bytes of data from the iterator of chunks of data.
  896. Returns less than L bytes if the iterator runs dry.
  897. If size parameter is ommited, read everything"""
  898. left = l
  899. buf = []
  900. queue = self._queue
  901. while left is None or left > 0:
  902. # refill the queue
  903. if not queue:
  904. target = 2**18
  905. for chunk in self.iter:
  906. queue.append(chunk)
  907. target -= len(chunk)
  908. if target <= 0:
  909. break
  910. if not queue:
  911. break
  912. chunk = queue.popleft()
  913. if left is not None:
  914. left -= len(chunk)
  915. if left is not None and left < 0:
  916. queue.appendleft(chunk[left:])
  917. buf.append(chunk[:left])
  918. else:
  919. buf.append(chunk)
  920. return ''.join(buf)
  921. def filechunkiter(f, size=65536, limit=None):
  922. """Create a generator that produces the data in the file size
  923. (default 65536) bytes at a time, up to optional limit (default is
  924. to read all data). Chunks may be less than size bytes if the
  925. chunk is the last chunk in the file, or the file is a socket or
  926. some other type of file that sometimes reads less data than is
  927. requested."""
  928. assert size >= 0
  929. assert limit is None or limit >= 0
  930. while True:
  931. if limit is None:
  932. nbytes = size
  933. else:
  934. nbytes = min(limit, size)
  935. s = nbytes and f.read(nbytes)
  936. if not s:
  937. break
  938. if limit:
  939. limit -= len(s)
  940. yield s
  941. def makedate(timestamp=None):
  942. '''Return a unix timestamp (or the current time) as a (unixtime,
  943. offset) tuple based off the local timezone.'''
  944. if timestamp is None:
  945. timestamp = time.time()
  946. if timestamp < 0:
  947. hint = _("check your clock")
  948. raise Abort(_("negative timestamp: %d") % timestamp, hint=hint)
  949. delta = (datetime.datetime.utcfromtimestamp(timestamp) -
  950. datetime.datetime.fromtimestamp(timestamp))
  951. tz = delta.days * 86400 + delta.seconds
  952. return timestamp, tz
  953. def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
  954. """represent a (unixtime, offset) tuple as a localized time.
  955. unixtime is seconds since the epoch, and offset is the time zone's
  956. number of seconds away from UTC. if timezone is false, do not
  957. append time zone to string."""
  958. t, tz = date or makedate()
  959. if t < 0:
  960. t = 0 # time.gmtime(lt) fails on Windows for lt < -43200
  961. tz = 0
  962. if "%1" in format or "%2" in format or "%z" in format:
  963. sign = (tz > 0) and "-" or "+"
  964. minutes = abs(tz) // 60
  965. format = format.replace("%z", "%1%2")
  966. format = format.replace("%1", "%c%02d" % (sign, minutes // 60))
  967. format = format.replace("%2", "%02d" % (minutes % 60))
  968. try:
  969. t = time.gmtime(float(t) - tz)
  970. except ValueError:
  971. # time was out of range
  972. t = time.gmtime(sys.maxint)
  973. s = time.strftime(format, t)
  974. return s
  975. def shortdate(date=None):
  976. """turn (timestamp, tzoff) tuple into iso 8631 date."""
  977. return datestr(date, format='%Y-%m-%d')
  978. def strdate(string, format, defaults=[]):
  979. """parse a localized time string and return a (unixtime, offset) tuple.
  980. if the string cannot be parsed, ValueError is raised."""
  981. def timezone(string):
  982. tz = string.split()[-1]
  983. if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
  984. sign = (tz[0] == "+") and 1 or -1
  985. hours = int(tz[1:3])
  986. minutes = int(tz[3:5])
  987. return -sign * (hours * 60 + minutes) * 60
  988. if tz == "GMT" or tz == "UTC":
  989. return 0
  990. return None
  991. # NOTE: unixtime = localunixtime + offset
  992. offset, date = timezone(string), string
  993. if offset is not None:
  994. date = " ".join(string.split()[:-1])
  995. # add missing elements from defaults
  996. usenow = False # default to using biased defaults
  997. for part in ("S", "M", "HI", "d", "mb", "yY"): # decreasing specificity
  998. found = [True for p in part if ("%"+p) in format]
  999. if not found:
  1000. date += "@" + defaults[part][usenow]
  1001. format += "@%" + part[0]
  1002. else:
  1003. # We've found a specific time element, less specific time
  1004. # elements are relative to today
  1005. usenow = True
  1006. timetuple = time.strptime(date, format)
  1007. localunixtime = int(calendar.timegm(timetuple))
  1008. if offset is None:
  1009. # local timezone
  1010. unixtime = int(time.mktime(timetuple))
  1011. offset = unixtime - localunixtime
  1012. else:
  1013. unixtime = localunixtime + offset
  1014. return unixtime, offset
  1015. def parsedate(date, formats=None, bias={}):
  1016. """parse a localized date/time and return a (unixtime, offset) tuple.
  1017. The date may be a "unixtime offset" string or in one of the specified
  1018. formats. If the date already is a (unixtime, offset) tuple, it is returned.
  1019. >>> parsedate(' today ') == parsedate(\
  1020. datetime.date.today().strftime('%b %d'))
  1021. True
  1022. >>> parsedate( 'yesterday ') == parsedate((datetime.date.today() -\
  1023. datetime.timedelta(days=1)\
  1024. ).strftime('%b %d'))
  1025. True
  1026. >>> now, tz = makedate()
  1027. >>> strnow, strtz = parsedate('now')
  1028. >>> (strnow - now) < 1
  1029. True
  1030. >>> tz == strtz
  1031. True
  1032. """
  1033. if not date:
  1034. return 0, 0
  1035. if isinstance(date, tuple) and len(date) == 2:
  1036. return date
  1037. if not formats:
  1038. formats = defaultdateformats
  1039. date = date.strip()
  1040. if date == _('now'):
  1041. return makedate()
  1042. if date == _('today'):
  1043. date = datetime.date.today().strftime('%b %d')
  1044. elif date == _('yesterday'):
  1045. date = (datetime.date.today() -
  1046. datetime.timedelta(days=1)).strftime('%b %d')
  1047. try:
  1048. when, offset = map(int, date.split(' '))
  1049. except ValueError:
  1050. # fill out defaults
  1051. now = makedate()
  1052. defaults = {}
  1053. for part in ("d", "mb", "yY", "HI", "M", "S"):
  1054. # this piece is for rounding the specific end of unknowns
  1055. b = bias.get(part)
  1056. if b is None:
  1057. if part[0] in "HMS":
  1058. b = "00"
  1059. else:
  1060. b = "0"
  1061. # this piece is for matching the generic end to today's date
  1062. n = datestr(now, "%" + part[0])
  1063. defaults[part] = (b, n)
  1064. for format in formats:
  1065. try:
  1066. when, offset = strdate(date, format, defaults)
  1067. except (ValueError, OverflowError):
  1068. pass
  1069. else:
  1070. break
  1071. else:
  1072. raise Abort(_('invalid date: %r') % date)
  1073. # validate explicit (probably user-specified) date and
  1074. # time zone offset. values must fit in signed 32 bits for
  1075. # current 32-bit linux runtimes. timezones go from UTC-12
  1076. # to UTC+14
  1077. if abs(when) > 0x7fffffff:
  1078. raise Abort(_('date exceeds 32 bits: %d') % when)
  1079. if when < 0:
  1080. raise Abort(_('negative date value: %d') % when)
  1081. if offset < -50400 or offset > 43200:
  1082. raise Abort(_('impossible time zone offset: %d') % offset)
  1083. return when, offset
  1084. def matchdate(date):
  1085. """Return a function that matches a given date match specifier
  1086. Formats include:
  1087. '{date}' match a given date to the accuracy provided
  1088. '<{date}' on or before a given date
  1089. '>{date}' on or after a given date
  1090. >>> p1 = parsedate("10:29:59")
  1091. >>> p2 = parsedate("10:30:00")
  1092. >>> p3 = parsedate("10:30:59")
  1093. >>> p4 = parsedate("10:31:00")
  1094. >>> p5 = parsedate("Sep 15 10:30:00 1999")
  1095. >>> f = matchdate("10:30")
  1096. >>> f(p1[0])
  1097. False
  1098. >>> f(p2[0])
  1099. True
  1100. >>> f(p3[0])
  1101. True
  1102. >>> f(p4[0])
  1103. False
  1104. >>> f(p5[0])
  1105. False
  1106. """
  1107. def lower(date):
  1108. d = {'mb': "1", 'd': "1"}
  1109. return parsedate(date, extendeddateformats, d)[0]
  1110. def upper(date):
  1111. d = {'mb': "12", 'HI': "23", 'M': "59", 'S': "59"}
  1112. for days in ("31", "30", "29"):
  1113. try:
  1114. d["d"] = days
  1115. return parsedate(date, extendeddateformats, d)[0]
  1116. except Abort:
  1117. pass
  1118. d["d"] = "28"
  1119. return parsedate(date, extendeddateformats, d)[0]
  1120. date = date.strip()
  1121. if not date:
  1122. raise Abort(_("dates cannot consist entirely of whitespace"))
  1123. elif date[0] == "<":
  1124. if not date[1:]:
  1125. raise Abort(_("invalid day spec, use '<DATE'"))
  1126. when = upper(date[1:])
  1127. return lambda x: x <= when
  1128. elif date[0] == ">":
  1129. if not date[1:]:
  1130. raise Abort(_("invalid day spec, use '>DATE'"))
  1131. when = lower(date[1:])
  1132. return lambda x: x >= when
  1133. elif date[0] == "-":
  1134. try:
  1135. days = int(date[1:])
  1136. except ValueError:
  1137. raise Abort(_("invalid day spec: %s") % date[1:])
  1138. if days < 0:
  1139. raise Abort(_("%s must be nonnegative (see 'hg help dates')")
  1140. % date[1:])
  1141. when = makedate()[0] - days * 3600 * 24
  1142. return lambda x: x >= when
  1143. elif " to " in date:
  1144. a, b = date.split(" to ")
  1145. start, stop = lower(a), upper(b)
  1146. return lambda x: x >= start and x <= stop
  1147. else:
  1148. start, stop = lower(date), upper(date)
  1149. return lambda x: x >= start and x <= stop
  1150. def shortuser(user):
  1151. """Return a short representation of a user name or email address."""
  1152. f = user.find('@')
  1153. if f >= 0:
  1154. user = user[:f]
  1155. f = user.find('<')
  1156. if f >= 0:
  1157. user = user[f + 1:]
  1158. f = user.find(' ')
  1159. if f >= 0:
  1160. user = user[:f]
  1161. f = user.find('.')
  1162. if f >= 0:
  1163. user = user[:f]
  1164. return user
  1165. def emailuser(user):
  1166. """Return the user portion of an email address."""
  1167. f = user.find('@')
  1168. if f >= 0:
  1169. user = user[:f]
  1170. f = user.find('<')
  1171. if f >= 0:
  1172. user = user[f + 1:]
  1173. return user
  1174. def email(author):
  1175. '''get email of author.'''
  1176. r = author.find('>')
  1177. if r == -1:
  1178. r = None
  1179. return author[author.find('<') + 1:r]
  1180. def ellipsis(text, maxlength=400):
  1181. """Trim string to at most maxlength (default: 400) columns in display."""
  1182. return encoding.trim(text, maxlength, ellipsis='...')
  1183. def unitcountfn(*unittable):
  1184. '''return a function that renders a readable count of some quantity'''
  1185. def go(count):
  1186. for multiplier, divisor, format in unittable:
  1187. if count >= divisor * multiplier:
  1188. return format % (count / float(divisor))
  1189. return unittable[-1][2] % count
  1190. return go
  1191. bytecount = unitcountfn(
  1192. (100, 1 << 30, _('%.0f GB')),
  1193. (10, 1 << 30, _('%.1f GB')),
  1194. (1, 1 << 30, _('%.2f GB')),
  1195. (100, 1 << 20, _('%.0f MB')),
  1196. (10, 1 << 20, _('%.1f MB')),
  1197. (1, 1 << 20, _('%.2f MB')),
  1198. (100, 1 << 10, _('%.0f KB')),
  1199. (10, 1 << 10, _('%.1f KB')),
  1200. (1, 1 << 10, _('%.2f KB')),
  1201. (1, 1, _('%.0f bytes')),
  1202. )
  1203. def uirepr(s):
  1204. # Avoid double backslash in Windows path repr()
  1205. return repr(s).replace('\\\\', '\\')
  1206. # delay import of textwrap
  1207. def MBTextWrapper(**kwargs):
  1208. class tw(textwrap.TextWrapper):
  1209. """
  1210. Extend TextWrapper for width-awareness.
  1211. Neither number of 'bytes' in any encoding nor 'characters' is
  1212. appropriate to calculate terminal columns for specified string.
  1213. Original TextWrapper implementation uses built-in 'len()' directly,
  1214. so overriding is needed to use width information of each characters.
  1215. In addition, characters classified into 'ambiguous' width are
  1216. treated as wide in East Asian area, but as narrow in other.
  1217. This requires use decision to determine width of such characters.
  1218. """
  1219. def __init__(self, **kwargs):
  1220. textwrap.TextWrapper.__init__(self, **kwargs)
  1221. # for compatibility between 2.4 and 2.6
  1222. if getattr(self, 'drop_whitespace', None) is None:
  1223. self.drop_whitespace = kwargs.get('drop_whitespace', True)
  1224. def _cutdown(self, ucstr, space_left):
  1225. l = 0
  1226. colwidth = encoding.ucolwidth
  1227. for i in xrange(len(ucstr)):
  1228. l += colwidth(ucstr[i])
  1229. if space_left < l:
  1230. return (ucstr[:i], ucstr[i:])
  1231. return ucstr, ''
  1232. # overriding of base class
  1233. def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
  1234. space_left = max(width - cur_len, 1)
  1235. if self.break_long_words:
  1236. cut, res = self._cutdown(reversed_chunks[-1], space_left)
  1237. cur_line.append(cut)
  1238. reversed_chunks[-1] = res
  1239. elif not cur_line:
  1240. cur_line.append(reversed_chunks.pop())
  1241. # this overriding code is imported from TextWrapper of python 2.6
  1242. # to calculate columns of string by 'encoding.ucolwidth()'
  1243. def _wrap_chunks(self, chunks):
  1244. colwidth = encoding.ucolwidth
  1245. lines = []
  1246. if self.width <= 0:
  1247. raise ValueError("invalid width %r (must be > 0)" % self.width)
  1248. # Arrange in reverse order so items can be efficiently popped
  1249. # from a stack of chucks.
  1250. chunks.reverse()
  1251. while chunks:
  1252. # Start the list of chunks that will make up the current line.
  1253. # cur_len is just the length of all the chunks in cur_line.
  1254. cur_line = []
  1255. cur_len = 0
  1256. # Figure out which static string will prefix this line.
  1257. if lines:
  1258. indent = self.subsequent_indent
  1259. else:
  1260. indent = self.initial_indent
  1261. # Maximum width for this line.
  1262. width = self.width - len(indent)
  1263. # First chunk on line is whitespace -- drop it, unless this
  1264. # is the very beginning of the text (i.e. no lines started yet).
  1265. if self.drop_whitespace and chunks[-1].strip() == '' and lines:
  1266. del chunks[-1]
  1267. while chunks:
  1268. l = colwidth(chunks[-1])
  1269. # Can at least squeeze this chunk onto the current line.
  1270. if cur_len + l <= width:
  1271. cur_line.append(chunks.pop())
  1272. cur_len += l
  1273. # Nope, this line is full.
  1274. else:
  1275. break
  1276. # The current line is full, and the next chunk is too big to
  1277. # fit on *any* line (not just this one).
  1278. if chunks and colwidth(chunks[-1]) > width:
  1279. self._handle_long_word(chunks, cur_line, cur_len, width)
  1280. # If the last chunk on this line is all whitespace, drop it.
  1281. if (self.drop_whitespace and
  1282. cur_line and cur_line[-1].strip() == ''):
  1283. del cur_line[-1]
  1284. # Convert current line back to a string and store it in list
  1285. # of all lines (return value).
  1286. if cur_line:
  1287. lines.append(indent + ''.join(cur_line))
  1288. return lines
  1289. global MBTextWrapper
  1290. MBTextWrapper = tw
  1291. return tw(**kwargs)
  1292. def wrap(line, width, initindent='', hangindent=''):
  1293. maxindent = max(len(hangindent), len(initindent))
  1294. if width <= maxindent:
  1295. # adjust for weird terminal size
  1296. width = max(78, maxindent + 1)
  1297. line = line.decode(encoding.encoding, encoding.encodingmode)
  1298. initindent = initindent.decode(encoding.encoding, encoding.encodingmode)
  1299. hangindent = hangindent.decode(encoding.encoding, encoding.encodingmode)
  1300. wrapper = MBTextWrapper(width=width,
  1301. initial_indent=initindent,
  1302. subsequent_indent=hangindent)
  1303. return wrapper.fill(line).encode(encoding.encoding)
  1304. def iterlines(iterator):
  1305. for chunk in iterator:
  1306. for line in chunk.splitlines():
  1307. yield line
  1308. def expandpath(path):
  1309. return os.path.expanduser(os.path.expandvars(path))
  1310. def hgcmd():
  1311. """Return the command used to execute current hg
  1312. This is different from hgexecutable() because on Windows we want
  1313. to avoid things opening new shell windows like batch files, so we
  1314. get either the python call or current executable.
  1315. """
  1316. if mainfrozen():
  1317. return [sys.executable]
  1318. return gethgcmd()
  1319. def rundetached(args, condfn):
  1320. """Execute the argument list in a detached process.
  1321. condfn is a callable which is called repeatedly and should return
  1322. True once the child process is known to have started successfully.
  1323. At this point, the child process PID is returned. If the child
  1324. process fails to start or finishes before condfn() evaluates to
  1325. True, return -1.
  1326. """
  1327. # Windows case is easier because the child process is either
  1328. # successfully starting and validating the condition or exiting
  1329. # on failure. We just poll on its PID. On Unix, if the child
  1330. # process fails to start, it will be left in a zombie state until
  1331. # the parent wait on it, which we cannot do since we expect a long
  1332. # running process on success. Instead we listen for SIGCHLD telling
  1333. # us our child process terminated.
  1334. terminated = set()
  1335. def handler(signum, frame):
  1336. terminated.add(os.wait())
  1337. prevhandler = None
  1338. SIGCHLD = getattr(signal, 'SIGCHLD', None)
  1339. if SIGCHLD is not None:
  1340. prevhandler = signal.signal(SIGCHLD, handler)
  1341. try:
  1342. pid = spawndetached(args)
  1343. while not condfn():
  1344. if ((pid in terminated or not testpid(pid))
  1345. and not condfn()):
  1346. return -1
  1347. time.sleep(0.1)
  1348. return pid
  1349. finally:
  1350. if prevhandler is not None:
  1351. signal.signal(signal.SIGCHLD, prevhandler)
  1352. try:
  1353. any, all = any, all
  1354. except NameError:
  1355. def any(iterable):
  1356. for i in iterable:
  1357. if i:
  1358. return True
  1359. return False
  1360. def all(iterable):
  1361. for i in iterable:
  1362. if not i:
  1363. return False
  1364. return True
  1365. def interpolate(prefix, mapping, s, fn=None, escape_prefix=False):
  1366. """Return the result of interpolating items in the mapping into string s.
  1367. prefix is a single character string, or a two character string with
  1368. a backslash as the first character if the prefix needs to be escaped in
  1369. a regular expression.
  1370. fn is an optional function that will be applied to the replacement text
  1371. just before replacement.
  1372. escape_prefix is an optional flag that allows using doubled prefix for
  1373. its escaping.
  1374. """
  1375. fn = fn or (lambda s: s)
  1376. patterns = '|'.join(mapping.keys())
  1377. if escape_prefix:
  1378. patterns += '|' + prefix
  1379. if len(prefix) > 1:
  1380. prefix_char = prefix[1:]
  1381. else:
  1382. prefix_char = prefix
  1383. mapping[prefix_char] = prefix_char
  1384. r = re.compile(r'%s(%s)' % (prefix, patterns))
  1385. return r.sub(lambda x: fn(mapping[x.group()[1:]]), s)
  1386. def getport(port):
  1387. """Return the port for a given network service.
  1388. If port is an integer, it's returned as is. If it's a string, it's
  1389. looked up using socket.getservbyname(). If there's no matching
  1390. service, util.Abort is raised.
  1391. """
  1392. try:
  1393. return int(port)
  1394. except ValueError:
  1395. pass
  1396. try:
  1397. return socket.getservbyname(port)
  1398. except socket.error:
  1399. raise Abort(_("no port number associated with service '%s'") % port)
  1400. _booleans = {'1': True, 'yes': True, 'true': True, 'on': True, 'always': True,
  1401. '0': False, 'no': False, 'false': False, 'off': False,
  1402. 'never': False}
  1403. def parsebool(s):
  1404. """Parse s into a boolean.
  1405. If s is not a valid boolean, returns None.
  1406. """
  1407. return _booleans.get(s.lower(), None)
  1408. _hexdig = '0123456789ABCDEFabcdef'
  1409. _hextochr = dict((a + b, chr(int(a + b, 16)))
  1410. for a in _hexdig for b in _hexdig)
  1411. def _urlunquote(s):
  1412. """Decode HTTP/HTML % encoding.
  1413. >>> _urlunquote('abc%20def')
  1414. 'abc def'
  1415. """
  1416. res = s.split('%')
  1417. # fastpath
  1418. if len(res) == 1:
  1419. return s
  1420. s = res[0]
  1421. for item in res[1:]:
  1422. try:
  1423. s += _hextochr[item[:2]] + item[2:]
  1424. except KeyError:
  1425. s += '%' + item
  1426. except UnicodeDecodeError:
  1427. s += unichr(int(item[:2], 16)) + item[2:]
  1428. return s
  1429. class url(object):
  1430. r"""Reliable URL parser.
  1431. This parses URLs and provides attributes for the following
  1432. components:
  1433. <scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
  1434. Missing components are set to None. The only exception is
  1435. fragment, which is set to '' if present but empty.
  1436. If parsefragment is False, fragment is included in query. If
  1437. parsequery is False, query is included in path. If both are
  1438. False, both fragment and query are included in path.
  1439. See http://www.ietf.org/rfc/rfc2396.txt for more information.
  1440. Note that for backward compatibility reasons, bundle URLs do not
  1441. take host names. That means 'bundle://../' has a path of '../'.
  1442. Examples:
  1443. >>> url('http://www.ietf.org/rfc/rfc2396.txt')
  1444. <url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
  1445. >>> url('ssh://[::1]:2200//home/joe/repo')
  1446. <url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
  1447. >>> url('file:///home/joe/repo')
  1448. <url scheme: 'file', path: '/home/joe/repo'>
  1449. >>> url('file:///c:/temp/foo/')
  1450. <url scheme: 'file', path: 'c:/temp/foo/'>
  1451. >>> url('bundle:foo')
  1452. <url scheme: 'bundle', path: 'foo'>
  1453. >>> url('bundle://../foo')
  1454. <url scheme: 'bundle', path: '../foo'>
  1455. >>> url(r'c:\foo\bar')
  1456. <url path: 'c:\\foo\\bar'>
  1457. >>> url(r'\\blah\blah\blah')
  1458. <url path: '\\\\blah\\blah\\blah'>
  1459. >>> url(r'\\blah\blah\blah#baz')
  1460. <url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
  1461. >>> url(r'file:///C:\users\me')
  1462. <url scheme: 'file', path: 'C:\\users\\me'>
  1463. Authentication credentials:
  1464. >>> url('ssh://joe:xyz@x/repo')
  1465. <url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
  1466. >>> url('ssh://joe@x/repo')
  1467. <url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
  1468. Query strings and fragments:
  1469. >>> url('http://host/a?b#c')
  1470. <url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
  1471. >>> url('http://host/a?b#c', parsequery=False, parsefragment=False)
  1472. <url scheme: 'http', host: 'host', path: 'a?b#c'>
  1473. """
  1474. _safechars = "!~*'()+"
  1475. _safepchars = "/!~*'()+:\\"
  1476. _matchscheme = re.compile(r'^[a-zA-Z0-9+.\-]+:').match
  1477. def __init__(self, path, parsequery=True, parsefragment=True):
  1478. # We slowly chomp away at path until we have only the path left
  1479. self.scheme = self.user = self.passwd = self.host = None
  1480. self.port = self.path = self.query = self.fragment = None
  1481. self._localpath = True
  1482. self._hostport = ''
  1483. self._origpath = path
  1484. if parsefragment and '#' in path:
  1485. path, self.fragment = path.split('#', 1)
  1486. if not path:
  1487. path = None
  1488. # special case for Windows drive letters and UNC paths
  1489. if hasdriveletter(path) or path.startswith(r'\\'):
  1490. self.path = path
  1491. return
  1492. # For compatibility reasons, we can't handle bundle paths as
  1493. # normal URLS
  1494. if path.startswith('bundle:'):
  1495. self.scheme = 'bundle'
  1496. path = path[7:]
  1497. if path.startswith('//'):
  1498. path = path[2:]
  1499. self.path = path
  1500. return
  1501. if self._matchscheme(path):
  1502. parts = path.split(':', 1)
  1503. if parts[0]:
  1504. self.scheme, path = parts
  1505. self._localpath = False
  1506. if not path:
  1507. path = None
  1508. if self._localpath:
  1509. self.path = ''
  1510. return
  1511. else:
  1512. if self._localpath:
  1513. self.path = path
  1514. return
  1515. if parsequery and '?' in path:
  1516. path, self.query = path.split('?', 1)
  1517. if not path:
  1518. path = None
  1519. if not self.query:
  1520. self.query = None
  1521. # // is required to specify a host/authority
  1522. if path and path.startswith('//'):
  1523. parts = path[2:].split('/', 1)
  1524. if len(parts) > 1:
  1525. self.host, path = parts
  1526. else:
  1527. self.host = parts[0]
  1528. path = None
  1529. if not self.host:
  1530. self.host = None
  1531. # path of file:///d is /d
  1532. # path of file:///d:/ is d:/, not /d:/
  1533. if path and not hasdriveletter(path):
  1534. path = '/' + path
  1535. if self.host and '@' in self.host:
  1536. self.user, self.host = self.host.rsplit('@', 1)
  1537. if ':' in self.user:
  1538. self.user, self.passwd = self.user.split(':', 1)
  1539. if not self.host:
  1540. self.host = None
  1541. # Don't split on colons in IPv6 addresses without ports
  1542. if (self.host and ':' in self.host and
  1543. not (self.host.startswith('[') and self.host.endswith(']'))):
  1544. self._hostport = self.host
  1545. self.host, self.port = self.host.rsplit(':', 1)
  1546. if not self.host:
  1547. self.host = None
  1548. if (self.host and self.scheme == 'file' and
  1549. self.host not in ('localhost', '127.0.0.1', '[::1]')):
  1550. raise Abort(_('file:// URLs can only refer to localhost'))
  1551. self.path = path
  1552. # leave the query string escaped
  1553. for a in ('user', 'passwd', 'host', 'port',
  1554. 'path', 'fragment'):
  1555. v = getattr(self, a)
  1556. if v is not None:
  1557. setattr(self, a, _urlunquote(v))
  1558. def __repr__(self):
  1559. attrs = []
  1560. for a in ('scheme', 'user', 'passwd', 'host', 'port', 'path',
  1561. 'query', 'fragment'):
  1562. v = getattr(self, a)
  1563. if v is not None:
  1564. attrs.append('%s: %r' % (a, v))
  1565. return '<url %s>' % ', '.join(attrs)
  1566. def __str__(self):
  1567. r"""Join the URL's components back into a URL string.
  1568. Examples:
  1569. >>> str(url('http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
  1570. 'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
  1571. >>> str(url('http://user:pw@host:80/?foo=bar&baz=42'))
  1572. 'http://user:pw@host:80/?foo=bar&baz=42'
  1573. >>> str(url('http://user:pw@host:80/?foo=bar%3dbaz'))
  1574. 'http://user:pw@host:80/?foo=bar%3dbaz'
  1575. >>> str(url('ssh://user:pw@[::1]:2200//home/joe#'))
  1576. 'ssh://user:pw@[::1]:2200//home/joe#'
  1577. >>> str(url('http://localhost:80//'))
  1578. 'http://localhost:80//'
  1579. >>> str(url('http://localhost:80/'))
  1580. 'http://localhost:80/'
  1581. >>> str(url('http://localhost:80'))
  1582. 'http://localhost:80/'
  1583. >>> str(url('bundle:foo'))
  1584. 'bundle:foo'
  1585. >>> str(url('bundle://../foo'))
  1586. 'bundle:../foo'
  1587. >>> str(url('path'))
  1588. 'path'
  1589. >>> str(url('file:///tmp/foo/bar'))
  1590. 'file:///tmp/foo/bar'
  1591. >>> str(url('file:///c:/tmp/foo/bar'))
  1592. 'file:///c:/tmp/foo/bar'
  1593. >>> print url(r'bundle:foo\bar')
  1594. bundle:foo\bar
  1595. >>> print url(r'file:///D:\data\hg')
  1596. file:///D:\data\hg
  1597. """
  1598. if self._localpath:
  1599. s = self.path
  1600. if self.scheme == 'bundle':
  1601. s = 'bundle:' + s
  1602. if self.fragment:
  1603. s += '#' + self.fragment
  1604. return s
  1605. s = self.scheme + ':'
  1606. if self.user or self.passwd or self.host:
  1607. s += '//'
  1608. elif self.scheme and (not self.path or self.path.startswith('/')
  1609. or hasdriveletter(self.path)):
  1610. s += '//'
  1611. if hasdriveletter(self.path):
  1612. s += '/'
  1613. if self.user:
  1614. s += urllib.quote(self.user, safe=self._safechars)
  1615. if self.passwd:
  1616. s += ':' + urllib.quote(self.passwd, safe=self._safechars)
  1617. if self.user or self.passwd:
  1618. s += '@'
  1619. if self.host:
  1620. if not (self.host.startswith('[') and self.host.endswith(']')):
  1621. s += urllib.quote(self.host)
  1622. else:
  1623. s += self.host
  1624. if self.port:
  1625. s += ':' + urllib.quote(self.port)
  1626. if self.host:
  1627. s += '/'
  1628. if self.path:
  1629. # TODO: similar to the query string, we should not unescape the
  1630. # path when we store it, the path might contain '%2f' = '/',
  1631. # which we should *not* escape.
  1632. s += urllib.quote(self.path, safe=self._safepchars)
  1633. if self.query:
  1634. # we store the query in escaped form.
  1635. s += '?' + self.query
  1636. if self.fragment is not None:
  1637. s += '#' + urllib.quote(self.fragment, safe=self._safepchars)
  1638. return s
  1639. def authinfo(self):
  1640. user, passwd = self.user, self.passwd
  1641. try:
  1642. self.user, self.passwd = None, None
  1643. s = str(self)
  1644. finally:
  1645. self.user, self.passwd = user, passwd
  1646. if not self.user:
  1647. return (s, None)
  1648. # authinfo[1] is passed to urllib2 password manager, and its
  1649. # URIs must not contain credentials. The host is passed in the
  1650. # URIs list because Python < 2.4.3 uses only that to search for
  1651. # a password.
  1652. return (s, (None, (s, self.host),
  1653. self.user, self.passwd or ''))
  1654. def isabs(self):
  1655. if self.scheme and self.scheme != 'file':
  1656. return True # remote URL
  1657. if hasdriveletter(self.path):
  1658. return True # absolute for our purposes - can't be joined()
  1659. if self.path.startswith(r'\\'):
  1660. return True # Windows UNC path
  1661. if self.path.startswith('/'):
  1662. return True # POSIX-style
  1663. return False
  1664. def localpath(self):
  1665. if self.scheme == 'file' or self.scheme == 'bundle':
  1666. path = self.path or '/'
  1667. # For Windows, we need to promote hosts containing drive
  1668. # letters to paths with drive letters.
  1669. if hasdriveletter(self._hostport):
  1670. path = self._hostport + '/' + self.path
  1671. elif (self.host is not None and self.path
  1672. and not hasdriveletter(path)):
  1673. path = '/' + path
  1674. return path
  1675. return self._origpath
  1676. def islocal(self):
  1677. '''whether localpath will return something that posixfile can open'''
  1678. return (not self.scheme or self.scheme == 'file'
  1679. or self.scheme == 'bundle')
  1680. def hasscheme(path):
  1681. return bool(url(path).scheme)
  1682. def hasdriveletter(path):
  1683. return path and path[1:2] == ':' and path[0:1].isalpha()
  1684. def urllocalpath(path):
  1685. return url(path, parsequery=False, parsefragment=False).localpath()
  1686. def hidepassword(u):
  1687. '''hide user credential in a url string'''
  1688. u = url(u)
  1689. if u.passwd:
  1690. u.passwd = '***'
  1691. return str(u)
  1692. def removeauth(u):
  1693. '''remove all authentication information from a url string'''
  1694. u = url(u)
  1695. u.user = u.passwd = None
  1696. return str(u)
  1697. def isatty(fd):
  1698. try:
  1699. return fd.isatty()
  1700. except AttributeError:
  1701. return False
  1702. timecount = unitcountfn(
  1703. (1, 1e3, _('%.0f s')),
  1704. (100, 1, _('%.1f s')),
  1705. (10, 1, _('%.2f s')),
  1706. (1, 1, _('%.3f s')),
  1707. (100, 0.001, _('%.1f ms')),
  1708. (10, 0.001, _('%.2f ms')),
  1709. (1, 0.001, _('%.3f ms')),
  1710. (100, 0.000001, _('%.1f us')),
  1711. (10, 0.000001, _('%.2f us')),
  1712. (1, 0.000001, _('%.3f us')),
  1713. (100, 0.000000001, _('%.1f ns')),
  1714. (10, 0.000000001, _('%.2f ns')),
  1715. (1, 0.000000001, _('%.3f ns')),
  1716. )
  1717. _timenesting = [0]
  1718. def timed(func):
  1719. '''Report the execution time of a function call to stderr.
  1720. During development, use as a decorator when you need to measure
  1721. the cost of a function, e.g. as follows:
  1722. @util.timed
  1723. def foo(a, b, c):
  1724. pass
  1725. '''
  1726. def wrapper(*args, **kwargs):
  1727. start = time.time()
  1728. indent = 2
  1729. _timenesting[0] += indent
  1730. try:
  1731. return func(*args, **kwargs)
  1732. finally:
  1733. elapsed = time.time() - start
  1734. _timenesting[0] -= indent
  1735. sys.stderr.write('%s%s: %s\n' %
  1736. (' ' * _timenesting[0], func.__name__,
  1737. timecount(elapsed)))
  1738. return wrapper
  1739. _sizeunits = (('m', 2**20), ('k', 2**10), ('g', 2**30),
  1740. ('kb', 2**10), ('mb', 2**20), ('gb', 2**30), ('b', 1))
  1741. def sizetoint(s):
  1742. '''Convert a space specifier to a byte count.
  1743. >>> sizetoint('30')
  1744. 30
  1745. >>> sizetoint('2.2kb')
  1746. 2252
  1747. >>> sizetoint('6M')
  1748. 6291456
  1749. '''
  1750. t = s.strip().lower()
  1751. try:
  1752. for k, u in _sizeunits:
  1753. if t.endswith(k):
  1754. return int(float(t[:-len(k)]) * u)
  1755. return int(t)
  1756. except ValueError:
  1757. raise error.ParseError(_("couldn't parse size: %s") % s)
  1758. class hooks(object):
  1759. '''A collection of hook functions that can be used to extend a
  1760. function's behaviour. Hooks are called in lexicographic order,
  1761. based on the names of their sources.'''
  1762. def __init__(self):
  1763. self._hooks = []
  1764. def add(self, source, hook):
  1765. self._hooks.append((source, hook))
  1766. def __call__(self, *args):
  1767. self._hooks.sort(key=lambda x: x[0])
  1768. results = []
  1769. for source, hook in self._hooks:
  1770. results.append(hook(*args))
  1771. return results
  1772. def debugstacktrace(msg='stacktrace', skip=0, f=sys.stderr, otherf=sys.stdout):
  1773. '''Writes a message to f (stderr) with a nicely formatted stacktrace.
  1774. Skips the 'skip' last entries. By default it will flush stdout first.
  1775. It can be used everywhere and do intentionally not require an ui object.
  1776. Not be used in production code but very convenient while developing.
  1777. '''
  1778. if otherf:
  1779. otherf.flush()
  1780. f.write('%s at:\n' % msg)
  1781. entries = [('%s:%s' % (fn, ln), func)
  1782. for fn, ln, func, _text in traceback.extract_stack()[:-skip - 1]]
  1783. if entries:
  1784. fnmax = max(len(entry[0]) for entry in entries)
  1785. for fnln, func in entries:
  1786. f.write(' %-*s in %s\n' % (fnmax, fnln, func))
  1787. f.flush()
  1788. # convenient shortcut
  1789. dst = debugstacktrace