blob: 3ddc3c3dcae79baca4ae2d170fc4fcda4bd7f327 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#
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
Sarah Owenscecd1d82012-11-01 22:59:27 -070016from __future__ import print_function
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090017import errno
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070018import fcntl
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090019import multiprocessing
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import re
21import os
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070022import select
Colin Cross31a7be52015-05-13 00:04:36 -070023import signal
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024import sys
25import subprocess
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070026
27from color import Coloring
Shawn O. Pearce44469462009-03-03 17:51:01 -080028from command import Command, MirrorSafeCommand
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070030_CAN_COLOR = [
31 'branch',
32 'diff',
33 'grep',
34 'log',
35]
36
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090037
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070038class ForallColoring(Coloring):
39 def __init__(self, config):
40 Coloring.__init__(self, config, 'forall')
41 self.project = self.printer('project', attr='bold')
42
43
Shawn O. Pearce44469462009-03-03 17:51:01 -080044class Forall(Command, MirrorSafeCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070045 common = False
46 helpSummary = "Run a shell command in each project"
47 helpUsage = """
48%prog [<project>...] -c <command> [<arg>...]
Zhiguang Lia8864fb2013-03-15 10:32:10 +080049%prog -r str1 [str2] ... -c <command> [<arg>...]"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070050"""
51 helpDescription = """
52Executes the same shell command in each project.
53
Zhiguang Lia8864fb2013-03-15 10:32:10 +080054The -r option allows running the command only on projects matching
55regex or wildcard expression.
56
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070057Output Formatting
58-----------------
59
60The -p option causes '%prog' to bind pipes to the command's stdin,
61stdout and stderr streams, and pipe all output into a continuous
62stream that is displayed in a single pager session. Project headings
63are inserted before the output of each command is displayed. If the
64command produces no output in a project, no heading is displayed.
65
66The formatting convention used by -p is very suitable for some
67types of searching, e.g. `repo forall -p -c git log -SFoo` will
68print all commits that add or remove references to Foo.
69
70The -v option causes '%prog' to display stderr messages if a
71command produces output only on stderr. Normally the -p option
72causes command output to be suppressed until the command produces
73at least one byte of output on stdout.
74
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070075Environment
76-----------
Shawn O. Pearceff84fea2009-04-13 12:11:59 -070077
Shawn O. Pearce44469462009-03-03 17:51:01 -080078pwd is the project's working directory. If the current client is
79a mirror client, then pwd is the Git repository.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070080
81REPO_PROJECT is set to the unique name of the project.
82
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050083REPO_PATH is the path relative the the root of the client.
84
85REPO_REMOTE is the name of the remote system from the manifest.
86
87REPO_LREV is the name of the revision from the manifest, translated
88to a local tracking branch. If you need to pass the manifest
89revision to a locally executed git command, use REPO_LREV.
90
91REPO_RREV is the name of the revision from the manifest, exactly
92as written in the manifest.
93
Mitchel Humpheryse81bc032014-03-31 11:36:56 -070094REPO_COUNT is the total number of projects being iterated.
95
96REPO_I is the current (1-based) iteration count. Can be used in
97conjunction with REPO_COUNT to add a simple progress indicator to your
98command.
99
James W. Mills24c13082012-04-12 15:04:13 -0500100REPO__* are any extra environment variables, specified by the
101"annotation" element under any project element. This can be useful
102for differentiating trees based on user-specific criteria, or simply
103annotating tree details.
104
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105shell positional arguments ($1, $2, .., $#) are set to any arguments
106following <command>.
107
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700108Unless -p is used, stdin, stdout, stderr are inherited from the
109terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +0200110
111If -e is used, when a command exits unsuccessfully, '%prog' will abort
112without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700113"""
114
115 def _Options(self, p):
116 def cmd(option, opt_str, value, parser):
117 setattr(parser.values, option.dest, list(parser.rargs))
118 while parser.rargs:
119 del parser.rargs[0]
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800120 p.add_option('-r', '--regex',
121 dest='regex', action='store_true',
122 help="Execute the command only on projects matching regex or wildcard expression")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700123 p.add_option('-c', '--command',
124 help='Command (and arguments) to execute',
125 dest='command',
126 action='callback',
127 callback=cmd)
Victor Boivie88b86722011-09-07 09:43:28 +0200128 p.add_option('-e', '--abort-on-errors',
129 dest='abort_on_errors', action='store_true',
130 help='Abort if a command exits unsuccessfully')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700131
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700132 g = p.add_option_group('Output')
133 g.add_option('-p',
134 dest='project_header', action='store_true',
135 help='Show project headers before output')
136 g.add_option('-v', '--verbose',
137 dest='verbose', action='store_true',
138 help='Show command error messages')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900139 g.add_option('-j', '--jobs',
140 dest='jobs', action='store', type='int', default=1,
141 help='number of commands to execute simultaneously')
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700142
143 def WantPager(self, opt):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900144 return opt.project_header and opt.jobs == 1
145
146 def _SerializeProject(self, project):
147 """ Serialize a project._GitGetByExec instance.
148
149 project._GitGetByExec is not pickle-able. Instead of trying to pass it
150 around between processes, make a dict ourselves containing only the
151 attributes that we need.
152
153 """
David Pursehouse30d13ee2015-05-07 15:01:15 +0900154 if not self.manifest.IsMirror:
155 lrev = project.GetRevisionId()
156 else:
157 lrev = None
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900158 return {
159 'name': project.name,
160 'relpath': project.relpath,
161 'remote_name': project.remote.name,
David Pursehouse30d13ee2015-05-07 15:01:15 +0900162 'lrev': lrev,
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900163 'rrev': project.revisionExpr,
164 'annotations': dict((a.name, a.value) for a in project.annotations),
165 'gitdir': project.gitdir,
166 'worktree': project.worktree,
167 }
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700168
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700169 def Execute(self, opt, args):
170 if not opt.command:
171 self.Usage()
172
173 cmd = [opt.command[0]]
174
175 shell = True
176 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
177 shell = False
178
179 if shell:
180 cmd.append(cmd[0])
181 cmd.extend(opt.command[1:])
182
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700183 if opt.project_header \
184 and not shell \
185 and cmd[0] == 'git':
186 # If this is a direct git command that can enable colorized
187 # output and the user prefers coloring, add --color into the
188 # command line because we are going to wrap the command into
189 # a pipe and git won't know coloring should activate.
190 #
191 for cn in cmd[1:]:
192 if not cn.startswith('-'):
193 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900194 else:
195 cn = None
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900196 # pylint: disable=W0631
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900197 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700198 class ColorCmd(Coloring):
199 def __init__(self, config, cmd):
200 Coloring.__init__(self, config, cmd)
201 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
202 cmd.insert(cmd.index(cn) + 1, '--color')
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900203 # pylint: enable=W0631
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700204
Shawn O. Pearce44469462009-03-03 17:51:01 -0800205 mirror = self.manifest.IsMirror
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700206 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700207
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800208 if not opt.regex:
209 projects = self.GetProjects(args)
210 else:
211 projects = self.FindProjects(args)
212
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700213 os.environ['REPO_COUNT'] = str(len(projects))
214
Colin Cross31a7be52015-05-13 00:04:36 -0700215 pool = multiprocessing.Pool(opt.jobs, InitWorker)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900216 try:
217 config = self.manifest.manifestProject.config
218 results_it = pool.imap(
219 DoWorkWrapper,
Colin Cross31a7be52015-05-13 00:04:36 -0700220 self.ProjectArgs(projects, mirror, opt, cmd, shell, config))
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900221 pool.close()
222 for r in results_it:
223 rc = rc or r
224 if r != 0 and opt.abort_on_errors:
225 raise Exception('Aborting due to previous error')
226 except (KeyboardInterrupt, WorkerKeyboardInterrupt):
227 # Catch KeyboardInterrupt raised inside and outside of workers
228 print('Interrupted - terminating the pool')
229 pool.terminate()
230 rc = rc or errno.EINTR
231 except Exception as e:
232 # Catch any other exceptions raised
233 print('Got an error, terminating the pool: %r' % e,
234 file=sys.stderr)
235 pool.terminate()
236 rc = rc or getattr(e, 'errno', 1)
237 finally:
238 pool.join()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700239 if rc != 0:
240 sys.exit(rc)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900241
Colin Cross31a7be52015-05-13 00:04:36 -0700242 def ProjectArgs(self, projects, mirror, opt, cmd, shell, config):
243 for cnt, p in enumerate(projects):
244 try:
245 project = self._SerializeProject(p)
246 except Exception as e:
247 print('Project list error: %r' % e,
248 file=sys.stderr)
249 return
250 except KeyboardInterrupt:
251 print('Project list interrupted',
252 file=sys.stderr)
253 return
254 yield [mirror, opt, cmd, shell, cnt, config, project]
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900255
256class WorkerKeyboardInterrupt(Exception):
257 """ Keyboard interrupt exception for worker processes. """
258 pass
259
260
Colin Cross31a7be52015-05-13 00:04:36 -0700261def InitWorker():
262 signal.signal(signal.SIGINT, signal.SIG_IGN)
263
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900264def DoWorkWrapper(args):
265 """ A wrapper around the DoWork() method.
266
267 Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
268 ``Exception``-based exception to stop it flooding the console with stacktraces
269 and making the parent hang indefinitely.
270
271 """
272 project = args.pop()
273 try:
274 return DoWork(project, *args)
275 except KeyboardInterrupt:
276 print('%s: Worker interrupted' % project['name'])
277 raise WorkerKeyboardInterrupt()
278
279
280def DoWork(project, mirror, opt, cmd, shell, cnt, config):
281 env = os.environ.copy()
282 def setenv(name, val):
283 if val is None:
284 val = ''
Anthony Kingc116f942015-06-03 17:29:29 +0100285 if hasattr(val, 'encode'):
286 val = val.encode()
287 env[name] = val
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900288
289 setenv('REPO_PROJECT', project['name'])
290 setenv('REPO_PATH', project['relpath'])
291 setenv('REPO_REMOTE', project['remote_name'])
292 setenv('REPO_LREV', project['lrev'])
293 setenv('REPO_RREV', project['rrev'])
294 setenv('REPO_I', str(cnt + 1))
295 for name in project['annotations']:
296 setenv("REPO__%s" % (name), project['annotations'][name])
297
298 if mirror:
299 setenv('GIT_DIR', project['gitdir'])
300 cwd = project['gitdir']
301 else:
302 cwd = project['worktree']
303
304 if not os.path.exists(cwd):
305 if (opt.project_header and opt.verbose) \
306 or not opt.project_header:
307 print('skipping %s/' % project['relpath'], file=sys.stderr)
308 return
309
310 if opt.project_header:
311 stdin = subprocess.PIPE
312 stdout = subprocess.PIPE
313 stderr = subprocess.PIPE
314 else:
315 stdin = None
316 stdout = None
317 stderr = None
318
319 p = subprocess.Popen(cmd,
320 cwd=cwd,
321 shell=shell,
322 env=env,
323 stdin=stdin,
324 stdout=stdout,
325 stderr=stderr)
326
327 if opt.project_header:
328 out = ForallColoring(config)
329 out.redirect(sys.stdout)
330 class sfd(object):
331 def __init__(self, fd, dest):
332 self.fd = fd
333 self.dest = dest
334 def fileno(self):
335 return self.fd.fileno()
336
337 empty = True
338 errbuf = ''
339
340 p.stdin.close()
341 s_in = [sfd(p.stdout, sys.stdout),
342 sfd(p.stderr, sys.stderr)]
343
344 for s in s_in:
345 flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
346 fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
347
348 while s_in:
349 in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
350 for s in in_ready:
351 buf = s.fd.read(4096)
352 if not buf:
353 s.fd.close()
354 s_in.remove(s)
355 continue
356
357 if not opt.verbose:
358 if s.fd != p.stdout:
359 errbuf += buf
360 continue
361
362 if empty and out:
363 if not cnt == 0:
364 out.nl()
365
366 if mirror:
367 project_header_path = project['name']
368 else:
369 project_header_path = project['relpath']
370 out.project('project %s/', project_header_path)
371 out.nl()
372 out.flush()
373 if errbuf:
374 sys.stderr.write(errbuf)
375 sys.stderr.flush()
376 errbuf = ''
377 empty = False
378
379 s.dest.write(buf)
380 s.dest.flush()
381
382 r = p.wait()
383 return r