gclient_utils.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Generic utils."""
  5. from __future__ import print_function
  6. import codecs
  7. import collections
  8. import contextlib
  9. import datetime
  10. import errno
  11. import functools
  12. import io
  13. import logging
  14. import operator
  15. import os
  16. import pipes
  17. import platform
  18. import re
  19. import stat
  20. import subprocess
  21. import sys
  22. import tempfile
  23. import threading
  24. import time
  25. import subprocess2
  26. if sys.version_info.major == 2:
  27. from cStringIO import StringIO
  28. import collections as collections_abc
  29. import Queue as queue
  30. import urlparse
  31. else:
  32. from collections import abc as collections_abc
  33. from io import StringIO
  34. import queue
  35. import urllib.parse as urlparse
  36. # Git wrapper retries on a transient error, and some callees do retries too,
  37. # such as GitWrapper.update (doing clone). One retry attempt should be
  38. # sufficient to help with any transient errors at this level.
  39. RETRY_MAX = 1
  40. RETRY_INITIAL_SLEEP = 2 # in seconds
  41. START = datetime.datetime.now()
  42. _WARNINGS = []
  43. # These repos are known to cause OOM errors on 32-bit platforms, due the the
  44. # very large objects they contain. It is not safe to use threaded index-pack
  45. # when cloning/fetching them.
  46. THREADED_INDEX_PACK_BLOCKLIST = [
  47. 'https://chromium.googlesource.com/chromium/reference_builds/chrome_win.git'
  48. ]
  49. """To support rethrowing exceptions with tracebacks on both Py2 and 3."""
  50. if sys.version_info.major == 2:
  51. # We have to use exec to avoid a SyntaxError in Python 3.
  52. exec("def reraise(typ, value, tb=None):\n raise typ, value, tb\n")
  53. else:
  54. def reraise(typ, value, tb=None):
  55. if value is None:
  56. value = typ()
  57. if value.__traceback__ is not tb:
  58. raise value.with_traceback(tb)
  59. raise value
  60. class Error(Exception):
  61. """gclient exception class."""
  62. def __init__(self, msg, *args, **kwargs):
  63. index = getattr(threading.currentThread(), 'index', 0)
  64. if index:
  65. msg = '\n'.join('%d> %s' % (index, l) for l in msg.splitlines())
  66. super(Error, self).__init__(msg, *args, **kwargs)
  67. def Elapsed(until=None):
  68. if until is None:
  69. until = datetime.datetime.now()
  70. return str(until - START).partition('.')[0]
  71. def PrintWarnings():
  72. """Prints any accumulated warnings."""
  73. if _WARNINGS:
  74. print('\n\nWarnings:', file=sys.stderr)
  75. for warning in _WARNINGS:
  76. print(warning, file=sys.stderr)
  77. def AddWarning(msg):
  78. """Adds the given warning message to the list of accumulated warnings."""
  79. _WARNINGS.append(msg)
  80. def FuzzyMatchRepo(repo, candidates):
  81. # type: (str, Union[Collection[str], Mapping[str, Any]]) -> Optional[str]
  82. """Attempts to find a representation of repo in the candidates.
  83. Args:
  84. repo: a string representation of a repo in the form of a url or the
  85. name and path of the solution it represents.
  86. candidates: The candidates to look through which may contain `repo` in
  87. in any of the forms mentioned above.
  88. Returns:
  89. The matching string, if any, which may be in a different form from `repo`.
  90. """
  91. if repo in candidates:
  92. return repo
  93. if repo.endswith('.git') and repo[:-len('.git')] in candidates:
  94. return repo[:-len('.git')]
  95. if repo + '.git' in candidates:
  96. return repo + '.git'
  97. return None
  98. def SplitUrlRevision(url):
  99. """Splits url and returns a two-tuple: url, rev"""
  100. if url.startswith('ssh:'):
  101. # Make sure ssh://user-name@example.com/~/test.git@stable works
  102. regex = r'(ssh://(?:[-.\w]+@)?[-\w:\.]+/[-~\w\./]+)(?:@(.+))?'
  103. components = re.search(regex, url).groups()
  104. else:
  105. components = url.rsplit('@', 1)
  106. if re.match(r'^\w+\@', url) and '@' not in components[0]:
  107. components = [url]
  108. if len(components) == 1:
  109. components += [None]
  110. return tuple(components)
  111. def ExtractRefName(remote, full_refs_str):
  112. """Returns the ref name if full_refs_str is a valid ref."""
  113. result = re.compile(r'^refs(\/.+)?\/((%s)|(heads)|(tags))\/(?P<ref_name>.+)' %
  114. remote).match(full_refs_str)
  115. if result:
  116. return result.group('ref_name')
  117. return None
  118. def IsGitSha(revision):
  119. """Returns true if the given string is a valid hex-encoded sha"""
  120. return re.match('^[a-fA-F0-9]{6,40}$', revision) is not None
  121. def IsFullGitSha(revision):
  122. """Returns true if the given string is a valid hex-encoded full sha"""
  123. return re.match('^[a-fA-F0-9]{40}$', revision) is not None
  124. def IsDateRevision(revision):
  125. """Returns true if the given revision is of the form "{ ... }"."""
  126. return bool(revision and re.match(r'^\{.+\}$', str(revision)))
  127. def MakeDateRevision(date):
  128. """Returns a revision representing the latest revision before the given
  129. date."""
  130. return "{" + date + "}"
  131. def SyntaxErrorToError(filename, e):
  132. """Raises a gclient_utils.Error exception with the human readable message"""
  133. try:
  134. # Try to construct a human readable error message
  135. if filename:
  136. error_message = 'There is a syntax error in %s\n' % filename
  137. else:
  138. error_message = 'There is a syntax error\n'
  139. error_message += 'Line #%s, character %s: "%s"' % (
  140. e.lineno, e.offset, re.sub(r'[\r\n]*$', '', e.text))
  141. except:
  142. # Something went wrong, re-raise the original exception
  143. raise e
  144. else:
  145. raise Error(error_message)
  146. class PrintableObject(object):
  147. def __str__(self):
  148. output = ''
  149. for i in dir(self):
  150. if i.startswith('__'):
  151. continue
  152. output += '%s = %s\n' % (i, str(getattr(self, i, '')))
  153. return output
  154. def AskForData(message):
  155. # Try to load the readline module, so that "elaborate line editing" features
  156. # such as backspace work for `raw_input` / `input`.
  157. try:
  158. import readline
  159. except ImportError:
  160. # The readline module does not exist in all Python distributions, e.g. on
  161. # Windows. Fall back to simple input handling.
  162. pass
  163. # Use this so that it can be mocked in tests on Python 2 and 3.
  164. try:
  165. if sys.version_info.major == 2:
  166. return raw_input(message)
  167. return input(message)
  168. except KeyboardInterrupt:
  169. # Hide the exception.
  170. sys.exit(1)
  171. def FileRead(filename, mode='rbU'):
  172. # mode is ignored now; we always return unicode strings.
  173. with open(filename, mode='rb') as f:
  174. s = f.read()
  175. try:
  176. return s.decode('utf-8', 'replace')
  177. except (UnicodeDecodeError, AttributeError):
  178. return s
  179. def FileWrite(filename, content, mode='w', encoding='utf-8'):
  180. with codecs.open(filename, mode=mode, encoding=encoding) as f:
  181. f.write(content)
  182. @contextlib.contextmanager
  183. def temporary_directory(**kwargs):
  184. tdir = tempfile.mkdtemp(**kwargs)
  185. try:
  186. yield tdir
  187. finally:
  188. if tdir:
  189. rmtree(tdir)
  190. @contextlib.contextmanager
  191. def temporary_file():
  192. """Creates a temporary file.
  193. On Windows, a file must be closed before it can be opened again. This function
  194. allows to write something like:
  195. with gclient_utils.temporary_file() as tmp:
  196. gclient_utils.FileWrite(tmp, foo)
  197. useful_stuff(tmp)
  198. Instead of something like:
  199. with tempfile.NamedTemporaryFile(delete=False) as tmp:
  200. tmp.write(foo)
  201. tmp.close()
  202. try:
  203. useful_stuff(tmp)
  204. finally:
  205. os.remove(tmp.name)
  206. """
  207. handle, name = tempfile.mkstemp()
  208. os.close(handle)
  209. try:
  210. yield name
  211. finally:
  212. os.remove(name)
  213. def safe_rename(old, new):
  214. """Renames a file reliably.
  215. Sometimes os.rename does not work because a dying git process keeps a handle
  216. on it for a few seconds. An exception is then thrown, which make the program
  217. give up what it was doing and remove what was deleted.
  218. The only solution is to catch the exception and try again until it works.
  219. """
  220. # roughly 10s
  221. retries = 100
  222. for i in range(retries):
  223. try:
  224. os.rename(old, new)
  225. break
  226. except OSError:
  227. if i == (retries - 1):
  228. # Give up.
  229. raise
  230. # retry
  231. logging.debug("Renaming failed from %s to %s. Retrying ..." % (old, new))
  232. time.sleep(0.1)
  233. def rm_file_or_tree(path):
  234. if os.path.isfile(path) or os.path.islink(path):
  235. os.remove(path)
  236. else:
  237. rmtree(path)
  238. def rmtree(path):
  239. """shutil.rmtree() on steroids.
  240. Recursively removes a directory, even if it's marked read-only.
  241. shutil.rmtree() doesn't work on Windows if any of the files or directories
  242. are read-only. We need to be able to force the files to be writable (i.e.,
  243. deletable) as we traverse the tree.
  244. Even with all this, Windows still sometimes fails to delete a file, citing
  245. a permission error (maybe something to do with antivirus scans or disk
  246. indexing). The best suggestion any of the user forums had was to wait a
  247. bit and try again, so we do that too. It's hand-waving, but sometimes it
  248. works. :/
  249. On POSIX systems, things are a little bit simpler. The modes of the files
  250. to be deleted doesn't matter, only the modes of the directories containing
  251. them are significant. As the directory tree is traversed, each directory
  252. has its mode set appropriately before descending into it. This should
  253. result in the entire tree being removed, with the possible exception of
  254. *path itself, because nothing attempts to change the mode of its parent.
  255. Doing so would be hazardous, as it's not a directory slated for removal.
  256. In the ordinary case, this is not a problem: for our purposes, the user
  257. will never lack write permission on *path's parent.
  258. """
  259. if not os.path.exists(path):
  260. return
  261. if os.path.islink(path) or not os.path.isdir(path):
  262. raise Error('Called rmtree(%s) in non-directory' % path)
  263. if sys.platform == 'win32':
  264. # Give up and use cmd.exe's rd command.
  265. path = os.path.normcase(path)
  266. for _ in range(3):
  267. exitcode = subprocess.call(['cmd.exe', '/c', 'rd', '/q', '/s', path])
  268. if exitcode == 0:
  269. return
  270. print('rd exited with code %d' % exitcode, file=sys.stderr)
  271. time.sleep(3)
  272. raise Exception('Failed to remove path %s' % path)
  273. # On POSIX systems, we need the x-bit set on the directory to access it,
  274. # the r-bit to see its contents, and the w-bit to remove files from it.
  275. # The actual modes of the files within the directory is irrelevant.
  276. os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
  277. def remove(func, subpath):
  278. func(subpath)
  279. for fn in os.listdir(path):
  280. # If fullpath is a symbolic link that points to a directory, isdir will
  281. # be True, but we don't want to descend into that as a directory, we just
  282. # want to remove the link. Check islink and treat links as ordinary files
  283. # would be treated regardless of what they reference.
  284. fullpath = os.path.join(path, fn)
  285. if os.path.islink(fullpath) or not os.path.isdir(fullpath):
  286. remove(os.remove, fullpath)
  287. else:
  288. # Recurse.
  289. rmtree(fullpath)
  290. remove(os.rmdir, path)
  291. def safe_makedirs(tree):
  292. """Creates the directory in a safe manner.
  293. Because multiple threads can create these directories concurrently, trap the
  294. exception and pass on.
  295. """
  296. count = 0
  297. while not os.path.exists(tree):
  298. count += 1
  299. try:
  300. os.makedirs(tree)
  301. except OSError as e:
  302. # 17 POSIX, 183 Windows
  303. if e.errno not in (17, 183):
  304. raise
  305. if count > 40:
  306. # Give up.
  307. raise
  308. def CommandToStr(args):
  309. """Converts an arg list into a shell escaped string."""
  310. return ' '.join(pipes.quote(arg) for arg in args)
  311. class Wrapper(object):
  312. """Wraps an object, acting as a transparent proxy for all properties by
  313. default.
  314. """
  315. def __init__(self, wrapped):
  316. self._wrapped = wrapped
  317. def __getattr__(self, name):
  318. return getattr(self._wrapped, name)
  319. class AutoFlush(Wrapper):
  320. """Creates a file object clone to automatically flush after N seconds."""
  321. def __init__(self, wrapped, delay):
  322. super(AutoFlush, self).__init__(wrapped)
  323. if not hasattr(self, 'lock'):
  324. self.lock = threading.Lock()
  325. self.__last_flushed_at = time.time()
  326. self.delay = delay
  327. @property
  328. def autoflush(self):
  329. return self
  330. def write(self, out, *args, **kwargs):
  331. self._wrapped.write(out, *args, **kwargs)
  332. should_flush = False
  333. self.lock.acquire()
  334. try:
  335. if self.delay and (time.time() - self.__last_flushed_at) > self.delay:
  336. should_flush = True
  337. self.__last_flushed_at = time.time()
  338. finally:
  339. self.lock.release()
  340. if should_flush:
  341. self.flush()
  342. class Annotated(Wrapper):
  343. """Creates a file object clone to automatically prepends every line in worker
  344. threads with a NN> prefix.
  345. """
  346. def __init__(self, wrapped, include_zero=False):
  347. super(Annotated, self).__init__(wrapped)
  348. if not hasattr(self, 'lock'):
  349. self.lock = threading.Lock()
  350. self.__output_buffers = {}
  351. self.__include_zero = include_zero
  352. self._wrapped_write = getattr(self._wrapped, 'buffer', self._wrapped).write
  353. @property
  354. def annotated(self):
  355. return self
  356. def write(self, out):
  357. # Store as bytes to ensure Unicode characters get output correctly.
  358. if not isinstance(out, bytes):
  359. out = out.encode('utf-8')
  360. index = getattr(threading.currentThread(), 'index', 0)
  361. if not index and not self.__include_zero:
  362. # Unindexed threads aren't buffered.
  363. return self._wrapped_write(out)
  364. self.lock.acquire()
  365. try:
  366. # Use a dummy array to hold the string so the code can be lockless.
  367. # Strings are immutable, requiring to keep a lock for the whole dictionary
  368. # otherwise. Using an array is faster than using a dummy object.
  369. if not index in self.__output_buffers:
  370. obj = self.__output_buffers[index] = [b'']
  371. else:
  372. obj = self.__output_buffers[index]
  373. finally:
  374. self.lock.release()
  375. # Continue lockless.
  376. obj[0] += out
  377. while True:
  378. cr_loc = obj[0].find(b'\r')
  379. lf_loc = obj[0].find(b'\n')
  380. if cr_loc == lf_loc == -1:
  381. break
  382. if cr_loc == -1 or (0 <= lf_loc < cr_loc):
  383. line, remaining = obj[0].split(b'\n', 1)
  384. if line:
  385. self._wrapped_write(b'%d>%s\n' % (index, line))
  386. elif lf_loc == -1 or (0 <= cr_loc < lf_loc):
  387. line, remaining = obj[0].split(b'\r', 1)
  388. if line:
  389. self._wrapped_write(b'%d>%s\r' % (index, line))
  390. obj[0] = remaining
  391. def flush(self):
  392. """Flush buffered output."""
  393. orphans = []
  394. self.lock.acquire()
  395. try:
  396. # Detect threads no longer existing.
  397. indexes = (getattr(t, 'index', None) for t in threading.enumerate())
  398. indexes = filter(None, indexes)
  399. for index in self.__output_buffers:
  400. if not index in indexes:
  401. orphans.append((index, self.__output_buffers[index][0]))
  402. for orphan in orphans:
  403. del self.__output_buffers[orphan[0]]
  404. finally:
  405. self.lock.release()
  406. # Don't keep the lock while writing. Will append \n when it shouldn't.
  407. for orphan in orphans:
  408. if orphan[1]:
  409. self._wrapped_write(b'%d>%s\n' % (orphan[0], orphan[1]))
  410. return self._wrapped.flush()
  411. def MakeFileAutoFlush(fileobj, delay=10):
  412. autoflush = getattr(fileobj, 'autoflush', None)
  413. if autoflush:
  414. autoflush.delay = delay
  415. return fileobj
  416. return AutoFlush(fileobj, delay)
  417. def MakeFileAnnotated(fileobj, include_zero=False):
  418. if getattr(fileobj, 'annotated', None):
  419. return fileobj
  420. return Annotated(fileobj, include_zero)
  421. GCLIENT_CHILDREN = []
  422. GCLIENT_CHILDREN_LOCK = threading.Lock()
  423. class GClientChildren(object):
  424. @staticmethod
  425. def add(popen_obj):
  426. with GCLIENT_CHILDREN_LOCK:
  427. GCLIENT_CHILDREN.append(popen_obj)
  428. @staticmethod
  429. def remove(popen_obj):
  430. with GCLIENT_CHILDREN_LOCK:
  431. GCLIENT_CHILDREN.remove(popen_obj)
  432. @staticmethod
  433. def _attemptToKillChildren():
  434. global GCLIENT_CHILDREN
  435. with GCLIENT_CHILDREN_LOCK:
  436. zombies = [c for c in GCLIENT_CHILDREN if c.poll() is None]
  437. for zombie in zombies:
  438. try:
  439. zombie.kill()
  440. except OSError:
  441. pass
  442. with GCLIENT_CHILDREN_LOCK:
  443. GCLIENT_CHILDREN = [k for k in GCLIENT_CHILDREN if k.poll() is not None]
  444. @staticmethod
  445. def _areZombies():
  446. with GCLIENT_CHILDREN_LOCK:
  447. return bool(GCLIENT_CHILDREN)
  448. @staticmethod
  449. def KillAllRemainingChildren():
  450. GClientChildren._attemptToKillChildren()
  451. if GClientChildren._areZombies():
  452. time.sleep(0.5)
  453. GClientChildren._attemptToKillChildren()
  454. with GCLIENT_CHILDREN_LOCK:
  455. if GCLIENT_CHILDREN:
  456. print('Could not kill the following subprocesses:', file=sys.stderr)
  457. for zombie in GCLIENT_CHILDREN:
  458. print(' ', zombie.pid, file=sys.stderr)
  459. def CheckCallAndFilter(args, print_stdout=False, filter_fn=None,
  460. show_header=False, always_show_header=False, retry=False,
  461. **kwargs):
  462. """Runs a command and calls back a filter function if needed.
  463. Accepts all subprocess2.Popen() parameters plus:
  464. print_stdout: If True, the command's stdout is forwarded to stdout.
  465. filter_fn: A function taking a single string argument called with each line
  466. of the subprocess2's output. Each line has the trailing newline
  467. character trimmed.
  468. show_header: Whether to display a header before the command output.
  469. always_show_header: Show header even when the command produced no output.
  470. retry: If the process exits non-zero, sleep for a brief interval and try
  471. again, up to RETRY_MAX times.
  472. stderr is always redirected to stdout.
  473. Returns the output of the command as a binary string.
  474. """
  475. def show_header_if_necessary(needs_header, attempt):
  476. """Show the header at most once."""
  477. if not needs_header[0]:
  478. return
  479. needs_header[0] = False
  480. # Automatically generated header. We only prepend a newline if
  481. # always_show_header is false, since it usually indicates there's an
  482. # external progress display, and it's better not to clobber it in that case.
  483. header = '' if always_show_header else '\n'
  484. header += '________ running \'%s\' in \'%s\'' % (
  485. ' '.join(args), kwargs.get('cwd', '.'))
  486. if attempt:
  487. header += ' attempt %s / %s' % (attempt + 1, RETRY_MAX + 1)
  488. header += '\n'
  489. if print_stdout:
  490. stdout_write = getattr(sys.stdout, 'buffer', sys.stdout).write
  491. stdout_write(header.encode())
  492. if filter_fn:
  493. filter_fn(header)
  494. def filter_line(command_output, line_start):
  495. """Extract the last line from command output and filter it."""
  496. if not filter_fn or line_start is None:
  497. return
  498. command_output.seek(line_start)
  499. filter_fn(command_output.read().decode('utf-8'))
  500. # Initialize stdout writer if needed. On Python 3, sys.stdout does not accept
  501. # byte inputs and sys.stdout.buffer must be used instead.
  502. if print_stdout:
  503. sys.stdout.flush()
  504. stdout_write = getattr(sys.stdout, 'buffer', sys.stdout).write
  505. else:
  506. stdout_write = lambda _: None
  507. sleep_interval = RETRY_INITIAL_SLEEP
  508. run_cwd = kwargs.get('cwd', os.getcwd())
  509. # Store the output of the command regardless of the value of print_stdout or
  510. # filter_fn.
  511. command_output = io.BytesIO()
  512. for attempt in range(RETRY_MAX + 1):
  513. # If our stdout is a terminal, then pass in a psuedo-tty pipe to our
  514. # subprocess when filtering its output. This makes the subproc believe
  515. # it was launched from a terminal, which will preserve ANSI color codes.
  516. os_type = GetOperatingSystem()
  517. if sys.stdout.isatty() and os_type != 'win' and os_type != 'aix':
  518. pipe_reader, pipe_writer = os.openpty()
  519. else:
  520. pipe_reader, pipe_writer = os.pipe()
  521. kid = subprocess2.Popen(
  522. args, bufsize=0, stdout=pipe_writer, stderr=subprocess2.STDOUT,
  523. **kwargs)
  524. # Close the write end of the pipe once we hand it off to the child proc.
  525. os.close(pipe_writer)
  526. GClientChildren.add(kid)
  527. # Passed as a list for "by ref" semantics.
  528. needs_header = [show_header]
  529. if always_show_header:
  530. show_header_if_necessary(needs_header, attempt)
  531. # Also, we need to forward stdout to prevent weird re-ordering of output.
  532. # This has to be done on a per byte basis to make sure it is not buffered:
  533. # normally buffering is done for each line, but if the process requests
  534. # input, no end-of-line character is output after the prompt and it would
  535. # not show up.
  536. try:
  537. line_start = None
  538. while True:
  539. try:
  540. in_byte = os.read(pipe_reader, 1)
  541. except (IOError, OSError) as e:
  542. if e.errno == errno.EIO:
  543. # An errno.EIO means EOF?
  544. in_byte = None
  545. else:
  546. raise e
  547. is_newline = in_byte in (b'\n', b'\r')
  548. if not in_byte:
  549. break
  550. show_header_if_necessary(needs_header, attempt)
  551. if is_newline:
  552. filter_line(command_output, line_start)
  553. line_start = None
  554. elif line_start is None:
  555. line_start = command_output.tell()
  556. stdout_write(in_byte)
  557. command_output.write(in_byte)
  558. # Flush the rest of buffered output.
  559. sys.stdout.flush()
  560. if line_start is not None:
  561. filter_line(command_output, line_start)
  562. os.close(pipe_reader)
  563. rv = kid.wait()
  564. # Don't put this in a 'finally,' since the child may still run if we get
  565. # an exception.
  566. GClientChildren.remove(kid)
  567. except KeyboardInterrupt:
  568. print('Failed while running "%s"' % ' '.join(args), file=sys.stderr)
  569. raise
  570. if rv == 0:
  571. return command_output.getvalue()
  572. if not retry:
  573. break
  574. print("WARNING: subprocess '%s' in %s failed; will retry after a short "
  575. 'nap...' % (' '.join('"%s"' % x for x in args), run_cwd))
  576. command_output = io.BytesIO()
  577. time.sleep(sleep_interval)
  578. sleep_interval *= 2
  579. raise subprocess2.CalledProcessError(
  580. rv, args, kwargs.get('cwd', None), command_output.getvalue(), None)
  581. class GitFilter(object):
  582. """A filter_fn implementation for quieting down git output messages.
  583. Allows a custom function to skip certain lines (predicate), and will throttle
  584. the output of percentage completed lines to only output every X seconds.
  585. """
  586. PERCENT_RE = re.compile('(.*) ([0-9]{1,3})% .*')
  587. def __init__(self, time_throttle=0, predicate=None, out_fh=None):
  588. """
  589. Args:
  590. time_throttle (int): GitFilter will throttle 'noisy' output (such as the
  591. XX% complete messages) to only be printed at least |time_throttle|
  592. seconds apart.
  593. predicate (f(line)): An optional function which is invoked for every line.
  594. The line will be skipped if predicate(line) returns False.
  595. out_fh: File handle to write output to.
  596. """
  597. self.first_line = True
  598. self.last_time = 0
  599. self.time_throttle = time_throttle
  600. self.predicate = predicate
  601. self.out_fh = out_fh or sys.stdout
  602. self.progress_prefix = None
  603. def __call__(self, line):
  604. # git uses an escape sequence to clear the line; elide it.
  605. esc = line.find(chr(0o33))
  606. if esc > -1:
  607. line = line[:esc]
  608. if self.predicate and not self.predicate(line):
  609. return
  610. now = time.time()
  611. match = self.PERCENT_RE.match(line)
  612. if match:
  613. if match.group(1) != self.progress_prefix:
  614. self.progress_prefix = match.group(1)
  615. elif now - self.last_time < self.time_throttle:
  616. return
  617. self.last_time = now
  618. if not self.first_line:
  619. self.out_fh.write('[%s] ' % Elapsed())
  620. self.first_line = False
  621. print(line, file=self.out_fh)
  622. def FindFileUpwards(filename, path=None):
  623. """Search upwards from the a directory (default: current) to find a file.
  624. Returns nearest upper-level directory with the passed in file.
  625. """
  626. if not path:
  627. path = os.getcwd()
  628. path = os.path.realpath(path)
  629. while True:
  630. file_path = os.path.join(path, filename)
  631. if os.path.exists(file_path):
  632. return path
  633. (new_path, _) = os.path.split(path)
  634. if new_path == path:
  635. return None
  636. path = new_path
  637. def GetOperatingSystem():
  638. """Returns 'mac', 'win', 'linux', or the name of the current platform."""
  639. if sys.platform.startswith(('cygwin', 'win')):
  640. return 'win'
  641. if sys.platform.startswith('linux'):
  642. return 'linux'
  643. if sys.platform == 'darwin':
  644. return 'mac'
  645. if sys.platform.startswith('aix'):
  646. return 'aix'
  647. try:
  648. return os.uname().sysname.lower()
  649. except AttributeError:
  650. return sys.platform
  651. def GetGClientRootAndEntries(path=None):
  652. """Returns the gclient root and the dict of entries."""
  653. config_file = '.gclient_entries'
  654. root = FindFileUpwards(config_file, path)
  655. if not root:
  656. print("Can't find %s" % config_file)
  657. return None
  658. config_path = os.path.join(root, config_file)
  659. env = {}
  660. with open(config_path) as config:
  661. exec(config.read(), env)
  662. config_dir = os.path.dirname(config_path)
  663. return config_dir, env['entries']
  664. def lockedmethod(method):
  665. """Method decorator that holds self.lock for the duration of the call."""
  666. def inner(self, *args, **kwargs):
  667. try:
  668. try:
  669. self.lock.acquire()
  670. except KeyboardInterrupt:
  671. print('Was deadlocked', file=sys.stderr)
  672. raise
  673. return method(self, *args, **kwargs)
  674. finally:
  675. self.lock.release()
  676. return inner
  677. class WorkItem(object):
  678. """One work item."""
  679. # On cygwin, creating a lock throwing randomly when nearing ~100 locks.
  680. # As a workaround, use a single lock. Yep you read it right. Single lock for
  681. # all the 100 objects.
  682. lock = threading.Lock()
  683. def __init__(self, name):
  684. # A unique string representing this work item.
  685. self._name = name
  686. self.outbuf = StringIO()
  687. self.start = self.finish = None
  688. self.resources = [] # List of resources this work item requires.
  689. def run(self, work_queue):
  690. """work_queue is passed as keyword argument so it should be
  691. the last parameters of the function when you override it."""
  692. @property
  693. def name(self):
  694. return self._name
  695. class ExecutionQueue(object):
  696. """Runs a set of WorkItem that have interdependencies and were WorkItem are
  697. added as they are processed.
  698. This class manages that all the required dependencies are run
  699. before running each one.
  700. Methods of this class are thread safe.
  701. """
  702. def __init__(self, jobs, progress, ignore_requirements, verbose=False):
  703. """jobs specifies the number of concurrent tasks to allow. progress is a
  704. Progress instance."""
  705. # Set when a thread is done or a new item is enqueued.
  706. self.ready_cond = threading.Condition()
  707. # Maximum number of concurrent tasks.
  708. self.jobs = jobs
  709. # List of WorkItem, for gclient, these are Dependency instances.
  710. self.queued = []
  711. # List of strings representing each Dependency.name that was run.
  712. self.ran = []
  713. # List of items currently running.
  714. self.running = []
  715. # Exceptions thrown if any.
  716. self.exceptions = queue.Queue()
  717. # Progress status
  718. self.progress = progress
  719. if self.progress:
  720. self.progress.update(0)
  721. self.ignore_requirements = ignore_requirements
  722. self.verbose = verbose
  723. self.last_join = None
  724. self.last_subproc_output = None
  725. def enqueue(self, d):
  726. """Enqueue one Dependency to be executed later once its requirements are
  727. satisfied.
  728. """
  729. assert isinstance(d, WorkItem)
  730. self.ready_cond.acquire()
  731. try:
  732. self.queued.append(d)
  733. total = len(self.queued) + len(self.ran) + len(self.running)
  734. if self.jobs == 1:
  735. total += 1
  736. logging.debug('enqueued(%s)' % d.name)
  737. if self.progress:
  738. self.progress._total = total
  739. self.progress.update(0)
  740. self.ready_cond.notifyAll()
  741. finally:
  742. self.ready_cond.release()
  743. def out_cb(self, _):
  744. self.last_subproc_output = datetime.datetime.now()
  745. return True
  746. @staticmethod
  747. def format_task_output(task, comment=''):
  748. if comment:
  749. comment = ' (%s)' % comment
  750. if task.start and task.finish:
  751. elapsed = ' (Elapsed: %s)' % (
  752. str(task.finish - task.start).partition('.')[0])
  753. else:
  754. elapsed = ''
  755. return """
  756. %s%s%s
  757. ----------------------------------------
  758. %s
  759. ----------------------------------------""" % (
  760. task.name, comment, elapsed, task.outbuf.getvalue().strip())
  761. def _is_conflict(self, job):
  762. """Checks to see if a job will conflict with another running job."""
  763. for running_job in self.running:
  764. for used_resource in running_job.item.resources:
  765. logging.debug('Checking resource %s' % used_resource)
  766. if used_resource in job.resources:
  767. return True
  768. return False
  769. def flush(self, *args, **kwargs):
  770. """Runs all enqueued items until all are executed."""
  771. kwargs['work_queue'] = self
  772. self.last_subproc_output = self.last_join = datetime.datetime.now()
  773. self.ready_cond.acquire()
  774. try:
  775. while True:
  776. # Check for task to run first, then wait.
  777. while True:
  778. if not self.exceptions.empty():
  779. # Systematically flush the queue when an exception logged.
  780. self.queued = []
  781. self._flush_terminated_threads()
  782. if (not self.queued and not self.running or
  783. self.jobs == len(self.running)):
  784. logging.debug('No more worker threads or can\'t queue anything.')
  785. break
  786. # Check for new tasks to start.
  787. for i in range(len(self.queued)):
  788. # Verify its requirements.
  789. if (self.ignore_requirements or
  790. not (set(self.queued[i].requirements) - set(self.ran))):
  791. if not self._is_conflict(self.queued[i]):
  792. # Start one work item: all its requirements are satisfied.
  793. self._run_one_task(self.queued.pop(i), args, kwargs)
  794. break
  795. else:
  796. # Couldn't find an item that could run. Break out the outher loop.
  797. break
  798. if not self.queued and not self.running:
  799. # We're done.
  800. break
  801. # We need to poll here otherwise Ctrl-C isn't processed.
  802. try:
  803. self.ready_cond.wait(10)
  804. # If we haven't printed to terminal for a while, but we have received
  805. # spew from a suprocess, let the user know we're still progressing.
  806. now = datetime.datetime.now()
  807. if (now - self.last_join > datetime.timedelta(seconds=60) and
  808. self.last_subproc_output > self.last_join):
  809. if self.progress:
  810. print('')
  811. sys.stdout.flush()
  812. elapsed = Elapsed()
  813. print('[%s] Still working on:' % elapsed)
  814. sys.stdout.flush()
  815. for task in self.running:
  816. print('[%s] %s' % (elapsed, task.item.name))
  817. sys.stdout.flush()
  818. except KeyboardInterrupt:
  819. # Help debugging by printing some information:
  820. print(
  821. ('\nAllowed parallel jobs: %d\n# queued: %d\nRan: %s\n'
  822. 'Running: %d') % (self.jobs, len(self.queued), ', '.join(
  823. self.ran), len(self.running)),
  824. file=sys.stderr)
  825. for i in self.queued:
  826. print(
  827. '%s (not started): %s' % (i.name, ', '.join(i.requirements)),
  828. file=sys.stderr)
  829. for i in self.running:
  830. print(
  831. self.format_task_output(i.item, 'interrupted'), file=sys.stderr)
  832. raise
  833. # Something happened: self.enqueue() or a thread terminated. Loop again.
  834. finally:
  835. self.ready_cond.release()
  836. assert not self.running, 'Now guaranteed to be single-threaded'
  837. if not self.exceptions.empty():
  838. if self.progress:
  839. print('')
  840. # To get back the stack location correctly, the raise a, b, c form must be
  841. # used, passing a tuple as the first argument doesn't work.
  842. e, task = self.exceptions.get()
  843. print(self.format_task_output(task.item, 'ERROR'), file=sys.stderr)
  844. reraise(e[0], e[1], e[2])
  845. elif self.progress:
  846. self.progress.end()
  847. def _flush_terminated_threads(self):
  848. """Flush threads that have terminated."""
  849. running = self.running
  850. self.running = []
  851. for t in running:
  852. if t.is_alive():
  853. self.running.append(t)
  854. else:
  855. t.join()
  856. self.last_join = datetime.datetime.now()
  857. sys.stdout.flush()
  858. if self.verbose:
  859. print(self.format_task_output(t.item))
  860. if self.progress:
  861. self.progress.update(1, t.item.name)
  862. if t.item.name in self.ran:
  863. raise Error(
  864. 'gclient is confused, "%s" is already in "%s"' % (
  865. t.item.name, ', '.join(self.ran)))
  866. if not t.item.name in self.ran:
  867. self.ran.append(t.item.name)
  868. def _run_one_task(self, task_item, args, kwargs):
  869. if self.jobs > 1:
  870. # Start the thread.
  871. index = len(self.ran) + len(self.running) + 1
  872. new_thread = self._Worker(task_item, index, args, kwargs)
  873. self.running.append(new_thread)
  874. new_thread.start()
  875. else:
  876. # Run the 'thread' inside the main thread. Don't try to catch any
  877. # exception.
  878. try:
  879. task_item.start = datetime.datetime.now()
  880. print('[%s] Started.' % Elapsed(task_item.start), file=task_item.outbuf)
  881. task_item.run(*args, **kwargs)
  882. task_item.finish = datetime.datetime.now()
  883. print(
  884. '[%s] Finished.' % Elapsed(task_item.finish), file=task_item.outbuf)
  885. self.ran.append(task_item.name)
  886. if self.verbose:
  887. if self.progress:
  888. print('')
  889. print(self.format_task_output(task_item))
  890. if self.progress:
  891. self.progress.update(1, ', '.join(t.item.name for t in self.running))
  892. except KeyboardInterrupt:
  893. print(
  894. self.format_task_output(task_item, 'interrupted'), file=sys.stderr)
  895. raise
  896. except Exception:
  897. print(self.format_task_output(task_item, 'ERROR'), file=sys.stderr)
  898. raise
  899. class _Worker(threading.Thread):
  900. """One thread to execute one WorkItem."""
  901. def __init__(self, item, index, args, kwargs):
  902. threading.Thread.__init__(self, name=item.name or 'Worker')
  903. logging.info('_Worker(%s) reqs:%s' % (item.name, item.requirements))
  904. self.item = item
  905. self.index = index
  906. self.args = args
  907. self.kwargs = kwargs
  908. self.daemon = True
  909. def run(self):
  910. """Runs in its own thread."""
  911. logging.debug('_Worker.run(%s)' % self.item.name)
  912. work_queue = self.kwargs['work_queue']
  913. try:
  914. self.item.start = datetime.datetime.now()
  915. print('[%s] Started.' % Elapsed(self.item.start), file=self.item.outbuf)
  916. self.item.run(*self.args, **self.kwargs)
  917. self.item.finish = datetime.datetime.now()
  918. print(
  919. '[%s] Finished.' % Elapsed(self.item.finish), file=self.item.outbuf)
  920. except KeyboardInterrupt:
  921. logging.info('Caught KeyboardInterrupt in thread %s', self.item.name)
  922. logging.info(str(sys.exc_info()))
  923. work_queue.exceptions.put((sys.exc_info(), self))
  924. raise
  925. except Exception:
  926. # Catch exception location.
  927. logging.info('Caught exception in thread %s', self.item.name)
  928. logging.info(str(sys.exc_info()))
  929. work_queue.exceptions.put((sys.exc_info(), self))
  930. finally:
  931. logging.info('_Worker.run(%s) done', self.item.name)
  932. work_queue.ready_cond.acquire()
  933. try:
  934. work_queue.ready_cond.notifyAll()
  935. finally:
  936. work_queue.ready_cond.release()
  937. def GetEditor(git_editor=None):
  938. """Returns the most plausible editor to use.
  939. In order of preference:
  940. - GIT_EDITOR environment variable
  941. - core.editor git configuration variable (if supplied by git-cl)
  942. - VISUAL environment variable
  943. - EDITOR environment variable
  944. - vi (non-Windows) or notepad (Windows)
  945. In the case of git-cl, this matches git's behaviour, except that it does not
  946. include dumb terminal detection.
  947. """
  948. editor = os.environ.get('GIT_EDITOR') or git_editor
  949. if not editor:
  950. editor = os.environ.get('VISUAL')
  951. if not editor:
  952. editor = os.environ.get('EDITOR')
  953. if not editor:
  954. if sys.platform.startswith('win'):
  955. editor = 'notepad'
  956. else:
  957. editor = 'vi'
  958. return editor
  959. def RunEditor(content, git, git_editor=None):
  960. """Opens up the default editor in the system to get the CL description."""
  961. file_handle, filename = tempfile.mkstemp(text=True, prefix='cl_description')
  962. # Make sure CRLF is handled properly by requiring none.
  963. if '\r' in content:
  964. print(
  965. '!! Please remove \\r from your change description !!', file=sys.stderr)
  966. fileobj = os.fdopen(file_handle, 'wb')
  967. # Still remove \r if present.
  968. content = re.sub('\r?\n', '\n', content)
  969. # Some editors complain when the file doesn't end in \n.
  970. if not content.endswith('\n'):
  971. content += '\n'
  972. fileobj.write(content.encode('utf-8'))
  973. fileobj.close()
  974. try:
  975. editor = GetEditor(git_editor=git_editor)
  976. if not editor:
  977. return None
  978. cmd = '%s %s' % (editor, filename)
  979. if sys.platform == 'win32' and os.environ.get('TERM') == 'msys':
  980. # Msysgit requires the usage of 'env' to be present.
  981. cmd = 'env ' + cmd
  982. try:
  983. # shell=True to allow the shell to handle all forms of quotes in
  984. # $EDITOR.
  985. subprocess2.check_call(cmd, shell=True)
  986. except subprocess2.CalledProcessError:
  987. return None
  988. return FileRead(filename)
  989. finally:
  990. os.remove(filename)
  991. def UpgradeToHttps(url):
  992. """Upgrades random urls to https://.
  993. Do not touch unknown urls like ssh:// or git://.
  994. Do not touch http:// urls with a port number,
  995. Fixes invalid GAE url.
  996. """
  997. if not url:
  998. return url
  999. if not re.match(r'[a-z\-]+\://.*', url):
  1000. # Make sure it is a valid uri. Otherwise, urlparse() will consider it a
  1001. # relative url and will use http:///foo. Note that it defaults to http://
  1002. # for compatibility with naked url like "localhost:8080".
  1003. url = 'http://%s' % url
  1004. parsed = list(urlparse.urlparse(url))
  1005. # Do not automatically upgrade http to https if a port number is provided.
  1006. if parsed[0] == 'http' and not re.match(r'^.+?\:\d+$', parsed[1]):
  1007. parsed[0] = 'https'
  1008. return urlparse.urlunparse(parsed)
  1009. def ParseCodereviewSettingsContent(content):
  1010. """Process a codereview.settings file properly."""
  1011. lines = (l for l in content.splitlines() if not l.strip().startswith("#"))
  1012. try:
  1013. keyvals = dict([x.strip() for x in l.split(':', 1)] for l in lines if l)
  1014. except ValueError:
  1015. raise Error(
  1016. 'Failed to process settings, please fix. Content:\n\n%s' % content)
  1017. def fix_url(key):
  1018. if keyvals.get(key):
  1019. keyvals[key] = UpgradeToHttps(keyvals[key])
  1020. fix_url('CODE_REVIEW_SERVER')
  1021. fix_url('VIEW_VC')
  1022. return keyvals
  1023. def NumLocalCpus():
  1024. """Returns the number of processors.
  1025. multiprocessing.cpu_count() is permitted to raise NotImplementedError, and
  1026. is known to do this on some Windows systems and OSX 10.6. If we can't get the
  1027. CPU count, we will fall back to '1'.
  1028. """
  1029. # Surround the entire thing in try/except; no failure here should stop gclient
  1030. # from working.
  1031. try:
  1032. # Use multiprocessing to get CPU count. This may raise
  1033. # NotImplementedError.
  1034. try:
  1035. import multiprocessing
  1036. return multiprocessing.cpu_count()
  1037. except NotImplementedError: # pylint: disable=bare-except
  1038. # (UNIX) Query 'os.sysconf'.
  1039. # pylint: disable=no-member
  1040. if hasattr(os, 'sysconf') and 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
  1041. return int(os.sysconf('SC_NPROCESSORS_ONLN'))
  1042. # (Windows) Query 'NUMBER_OF_PROCESSORS' environment variable.
  1043. if 'NUMBER_OF_PROCESSORS' in os.environ:
  1044. return int(os.environ['NUMBER_OF_PROCESSORS'])
  1045. except Exception as e:
  1046. logging.exception("Exception raised while probing CPU count: %s", e)
  1047. logging.debug('Failed to get CPU count. Defaulting to 1.')
  1048. return 1
  1049. def DefaultDeltaBaseCacheLimit():
  1050. """Return a reasonable default for the git config core.deltaBaseCacheLimit.
  1051. The primary constraint is the address space of virtual memory. The cache
  1052. size limit is per-thread, and 32-bit systems can hit OOM errors if this
  1053. parameter is set too high.
  1054. """
  1055. if platform.architecture()[0].startswith('64'):
  1056. return '2g'
  1057. return '512m'
  1058. def DefaultIndexPackConfig(url=''):
  1059. """Return reasonable default values for configuring git-index-pack.
  1060. Experiments suggest that higher values for pack.threads don't improve
  1061. performance."""
  1062. cache_limit = DefaultDeltaBaseCacheLimit()
  1063. result = ['-c', 'core.deltaBaseCacheLimit=%s' % cache_limit]
  1064. if url in THREADED_INDEX_PACK_BLOCKLIST:
  1065. result.extend(['-c', 'pack.threads=1'])
  1066. return result
  1067. def FindExecutable(executable):
  1068. """This mimics the "which" utility."""
  1069. path_folders = os.environ.get('PATH').split(os.pathsep)
  1070. for path_folder in path_folders:
  1071. target = os.path.join(path_folder, executable)
  1072. # Just in case we have some ~/blah paths.
  1073. target = os.path.abspath(os.path.expanduser(target))
  1074. if os.path.isfile(target) and os.access(target, os.X_OK):
  1075. return target
  1076. if sys.platform.startswith('win'):
  1077. for suffix in ('.bat', '.cmd', '.exe'):
  1078. alt_target = target + suffix
  1079. if os.path.isfile(alt_target) and os.access(alt_target, os.X_OK):
  1080. return alt_target
  1081. return None
  1082. def freeze(obj):
  1083. """Takes a generic object ``obj``, and returns an immutable version of it.
  1084. Supported types:
  1085. * dict / OrderedDict -> FrozenDict
  1086. * list -> tuple
  1087. * set -> frozenset
  1088. * any object with a working __hash__ implementation (assumes that hashable
  1089. means immutable)
  1090. Will raise TypeError if you pass an object which is not hashable.
  1091. """
  1092. if isinstance(obj, collections_abc.Mapping):
  1093. return FrozenDict((freeze(k), freeze(v)) for k, v in obj.items())
  1094. if isinstance(obj, (list, tuple)):
  1095. return tuple(freeze(i) for i in obj)
  1096. if isinstance(obj, set):
  1097. return frozenset(freeze(i) for i in obj)
  1098. hash(obj)
  1099. return obj
  1100. class FrozenDict(collections_abc.Mapping):
  1101. """An immutable OrderedDict.
  1102. Modified From: http://stackoverflow.com/a/2704866
  1103. """
  1104. def __init__(self, *args, **kwargs):
  1105. self._d = collections.OrderedDict(*args, **kwargs)
  1106. # Calculate the hash immediately so that we know all the items are
  1107. # hashable too.
  1108. self._hash = functools.reduce(
  1109. operator.xor, (hash(i) for i in enumerate(self._d.items())), 0)
  1110. def __eq__(self, other):
  1111. if not isinstance(other, collections_abc.Mapping):
  1112. return NotImplemented
  1113. if self is other:
  1114. return True
  1115. if len(self) != len(other):
  1116. return False
  1117. for k, v in self.items():
  1118. if k not in other or other[k] != v:
  1119. return False
  1120. return True
  1121. def __iter__(self):
  1122. return iter(self._d)
  1123. def __len__(self):
  1124. return len(self._d)
  1125. def __getitem__(self, key):
  1126. return self._d[key]
  1127. def __hash__(self):
  1128. return self._hash
  1129. def __repr__(self):
  1130. return 'FrozenDict(%r)' % (self._d.items(),)