forall.py 11 KB

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