gclient_utils.py 48 KB

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