gclient_utils.py 49 KB

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