forall.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import print_function
  16. import errno
  17. import fcntl
  18. import multiprocessing
  19. import re
  20. import os
  21. import select
  22. import signal
  23. import sys
  24. import subprocess
  25. from color import Coloring
  26. from command import Command, MirrorSafeCommand
  27. _CAN_COLOR = [
  28. 'branch',
  29. 'diff',
  30. 'grep',
  31. 'log',
  32. ]
  33. class ForallColoring(Coloring):
  34. def __init__(self, config):
  35. Coloring.__init__(self, config, 'forall')
  36. self.project = self.printer('project', attr='bold')
  37. class Forall(Command, MirrorSafeCommand):
  38. common = False
  39. helpSummary = "Run a shell command in each project"
  40. helpUsage = """
  41. %prog [<project>...] -c <command> [<arg>...]
  42. %prog -r str1 [str2] ... -c <command> [<arg>...]"
  43. """
  44. helpDescription = """
  45. Executes the same shell command in each project.
  46. The -r option allows running the command only on projects matching
  47. regex or wildcard expression.
  48. Output Formatting
  49. -----------------
  50. The -p option causes '%prog' to bind pipes to the command's stdin,
  51. stdout and stderr streams, and pipe all output into a continuous
  52. stream that is displayed in a single pager session. Project headings
  53. are inserted before the output of each command is displayed. If the
  54. command produces no output in a project, no heading is displayed.
  55. The formatting convention used by -p is very suitable for some
  56. types of searching, e.g. `repo forall -p -c git log -SFoo` will
  57. print all commits that add or remove references to Foo.
  58. The -v option causes '%prog' to display stderr messages if a
  59. command produces output only on stderr. Normally the -p option
  60. causes command output to be suppressed until the command produces
  61. at least one byte of output on stdout.
  62. Environment
  63. -----------
  64. pwd is the project's working directory. If the current client is
  65. a mirror client, then pwd is the Git repository.
  66. REPO_PROJECT is set to the unique name of the project.
  67. REPO_PATH is the path relative the the root of the client.
  68. REPO_REMOTE is the name of the remote system from the manifest.
  69. REPO_LREV is the name of the revision from the manifest, translated
  70. to a local tracking branch. If you need to pass the manifest
  71. revision to a locally executed git command, use REPO_LREV.
  72. REPO_RREV is the name of the revision from the manifest, exactly
  73. as written in the manifest.
  74. REPO_COUNT is the total number of projects being iterated.
  75. REPO_I is the current (1-based) iteration count. Can be used in
  76. conjunction with REPO_COUNT to add a simple progress indicator to your
  77. command.
  78. REPO__* are any extra environment variables, specified by the
  79. "annotation" element under any project element. This can be useful
  80. for differentiating trees based on user-specific criteria, or simply
  81. annotating tree details.
  82. shell positional arguments ($1, $2, .., $#) are set to any arguments
  83. following <command>.
  84. Unless -p is used, stdin, stdout, stderr are inherited from the
  85. terminal and are not redirected.
  86. If -e is used, when a command exits unsuccessfully, '%prog' will abort
  87. without iterating through the remaining projects.
  88. """
  89. def _Options(self, p):
  90. def cmd(option, opt_str, value, parser):
  91. setattr(parser.values, option.dest, list(parser.rargs))
  92. while parser.rargs:
  93. del parser.rargs[0]
  94. p.add_option('-r', '--regex',
  95. dest='regex', action='store_true',
  96. help="Execute the command only on projects matching regex or wildcard expression")
  97. p.add_option('-c', '--command',
  98. help='Command (and arguments) to execute',
  99. dest='command',
  100. action='callback',
  101. callback=cmd)
  102. p.add_option('-e', '--abort-on-errors',
  103. dest='abort_on_errors', action='store_true',
  104. help='Abort if a command exits unsuccessfully')
  105. g = p.add_option_group('Output')
  106. g.add_option('-p',
  107. dest='project_header', action='store_true',
  108. help='Show project headers before output')
  109. g.add_option('-v', '--verbose',
  110. dest='verbose', action='store_true',
  111. help='Show command error messages')
  112. g.add_option('-j', '--jobs',
  113. dest='jobs', action='store', type='int', default=1,
  114. help='number of commands to execute simultaneously')
  115. def WantPager(self, opt):
  116. return opt.project_header and opt.jobs == 1
  117. def _SerializeProject(self, project):
  118. """ Serialize a project._GitGetByExec instance.
  119. project._GitGetByExec is not pickle-able. Instead of trying to pass it
  120. around between processes, make a dict ourselves containing only the
  121. attributes that we need.
  122. """
  123. return {
  124. 'name': project.name,
  125. 'relpath': project.relpath,
  126. 'remote_name': project.remote.name,
  127. 'lrev': project.GetRevisionId(),
  128. 'rrev': project.revisionExpr,
  129. 'annotations': dict((a.name, a.value) for a in project.annotations),
  130. 'gitdir': project.gitdir,
  131. 'worktree': project.worktree,
  132. }
  133. def Execute(self, opt, args):
  134. if not opt.command:
  135. self.Usage()
  136. cmd = [opt.command[0]]
  137. shell = True
  138. if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
  139. shell = False
  140. if shell:
  141. cmd.append(cmd[0])
  142. cmd.extend(opt.command[1:])
  143. if opt.project_header \
  144. and not shell \
  145. and cmd[0] == 'git':
  146. # If this is a direct git command that can enable colorized
  147. # output and the user prefers coloring, add --color into the
  148. # command line because we are going to wrap the command into
  149. # a pipe and git won't know coloring should activate.
  150. #
  151. for cn in cmd[1:]:
  152. if not cn.startswith('-'):
  153. break
  154. else:
  155. cn = None
  156. # pylint: disable=W0631
  157. if cn and cn in _CAN_COLOR:
  158. class ColorCmd(Coloring):
  159. def __init__(self, config, cmd):
  160. Coloring.__init__(self, config, cmd)
  161. if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
  162. cmd.insert(cmd.index(cn) + 1, '--color')
  163. # pylint: enable=W0631
  164. mirror = self.manifest.IsMirror
  165. rc = 0
  166. if not opt.regex:
  167. projects = self.GetProjects(args)
  168. else:
  169. projects = self.FindProjects(args)
  170. os.environ['REPO_COUNT'] = str(len(projects))
  171. pool = multiprocessing.Pool(opt.jobs, InitWorker)
  172. try:
  173. config = self.manifest.manifestProject.config
  174. results_it = pool.imap(
  175. DoWorkWrapper,
  176. self.ProjectArgs(projects, mirror, opt, cmd, shell, config))
  177. pool.close()
  178. for r in results_it:
  179. rc = rc or r
  180. if r != 0 and opt.abort_on_errors:
  181. raise Exception('Aborting due to previous error')
  182. except (KeyboardInterrupt, WorkerKeyboardInterrupt):
  183. # Catch KeyboardInterrupt raised inside and outside of workers
  184. print('Interrupted - terminating the pool')
  185. pool.terminate()
  186. rc = rc or errno.EINTR
  187. except Exception as e:
  188. # Catch any other exceptions raised
  189. print('Got an error, terminating the pool: %r' % e,
  190. file=sys.stderr)
  191. pool.terminate()
  192. rc = rc or getattr(e, 'errno', 1)
  193. finally:
  194. pool.join()
  195. if rc != 0:
  196. sys.exit(rc)
  197. def ProjectArgs(self, projects, mirror, opt, cmd, shell, config):
  198. for cnt, p in enumerate(projects):
  199. try:
  200. project = self._SerializeProject(p)
  201. except Exception as e:
  202. print('Project list error: %r' % e,
  203. file=sys.stderr)
  204. return
  205. except KeyboardInterrupt:
  206. print('Project list interrupted',
  207. file=sys.stderr)
  208. return
  209. yield [mirror, opt, cmd, shell, cnt, config, project]
  210. class WorkerKeyboardInterrupt(Exception):
  211. """ Keyboard interrupt exception for worker processes. """
  212. pass
  213. def InitWorker():
  214. signal.signal(signal.SIGINT, signal.SIG_IGN)
  215. def DoWorkWrapper(args):
  216. """ A wrapper around the DoWork() method.
  217. Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
  218. ``Exception``-based exception to stop it flooding the console with stacktraces
  219. and making the parent hang indefinitely.
  220. """
  221. project = args.pop()
  222. try:
  223. return DoWork(project, *args)
  224. except KeyboardInterrupt:
  225. print('%s: Worker interrupted' % project['name'])
  226. raise WorkerKeyboardInterrupt()
  227. def DoWork(project, mirror, opt, cmd, shell, cnt, config):
  228. env = os.environ.copy()
  229. def setenv(name, val):
  230. if val is None:
  231. val = ''
  232. if hasattr(val, 'encode'):
  233. val = val.encode()
  234. env[name] = val
  235. setenv('REPO_PROJECT', project['name'])
  236. setenv('REPO_PATH', project['relpath'])
  237. setenv('REPO_REMOTE', project['remote_name'])
  238. setenv('REPO_LREV', project['lrev'])
  239. setenv('REPO_RREV', project['rrev'])
  240. setenv('REPO_I', str(cnt + 1))
  241. for name in project['annotations']:
  242. setenv("REPO__%s" % (name), project['annotations'][name])
  243. if mirror:
  244. setenv('GIT_DIR', project['gitdir'])
  245. cwd = project['gitdir']
  246. else:
  247. cwd = project['worktree']
  248. if not os.path.exists(cwd):
  249. if (opt.project_header and opt.verbose) \
  250. or not opt.project_header:
  251. print('skipping %s/' % project['relpath'], file=sys.stderr)
  252. return
  253. if opt.project_header:
  254. stdin = subprocess.PIPE
  255. stdout = subprocess.PIPE
  256. stderr = subprocess.PIPE
  257. else:
  258. stdin = None
  259. stdout = None
  260. stderr = None
  261. p = subprocess.Popen(cmd,
  262. cwd=cwd,
  263. shell=shell,
  264. env=env,
  265. stdin=stdin,
  266. stdout=stdout,
  267. stderr=stderr)
  268. if opt.project_header:
  269. out = ForallColoring(config)
  270. out.redirect(sys.stdout)
  271. class sfd(object):
  272. def __init__(self, fd, dest):
  273. self.fd = fd
  274. self.dest = dest
  275. def fileno(self):
  276. return self.fd.fileno()
  277. empty = True
  278. errbuf = ''
  279. p.stdin.close()
  280. s_in = [sfd(p.stdout, sys.stdout),
  281. sfd(p.stderr, sys.stderr)]
  282. for s in s_in:
  283. flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
  284. fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  285. while s_in:
  286. in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
  287. for s in in_ready:
  288. buf = s.fd.read(4096)
  289. if not buf:
  290. s.fd.close()
  291. s_in.remove(s)
  292. continue
  293. if not opt.verbose:
  294. if s.fd != p.stdout:
  295. errbuf += buf
  296. continue
  297. if empty and out:
  298. if not cnt == 0:
  299. out.nl()
  300. if mirror:
  301. project_header_path = project['name']
  302. else:
  303. project_header_path = project['relpath']
  304. out.project('project %s/', project_header_path)
  305. out.nl()
  306. out.flush()
  307. if errbuf:
  308. sys.stderr.write(errbuf)
  309. sys.stderr.flush()
  310. errbuf = ''
  311. empty = False
  312. s.dest.write(buf)
  313. s.dest.flush()
  314. r = p.wait()
  315. return r