gclient_utils.py 42 KB

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