gclient_utils.py 47 KB

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