PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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, not

Large files files are truncated, but you can click here to view the full file