blob: 693949e2b46cc01ae1cfe1fc6bbc6815415ecdf1 [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
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090018import multiprocessing
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070019import re
20import os
Colin Cross31a7be52015-05-13 00:04:36 -070021import signal
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070022import sys
23import subprocess
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070024
25from color import Coloring
Shawn O. Pearce44469462009-03-03 17:51:01 -080026from command import Command, MirrorSafeCommand
Renaud Paquay2e702912016-11-01 11:23:38 -070027import platform_utils
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070029_CAN_COLOR = [
30 'branch',
31 'diff',
32 'grep',
33 'log',
34]
35
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090036
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070037class ForallColoring(Coloring):
38 def __init__(self, config):
39 Coloring.__init__(self, config, 'forall')
40 self.project = self.printer('project', attr='bold')
41
42
Shawn O. Pearce44469462009-03-03 17:51:01 -080043class Forall(Command, MirrorSafeCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070044 common = False
45 helpSummary = "Run a shell command in each project"
46 helpUsage = """
47%prog [<project>...] -c <command> [<arg>...]
Zhiguang Lia8864fb2013-03-15 10:32:10 +080048%prog -r str1 [str2] ... -c <command> [<arg>...]"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070049"""
50 helpDescription = """
51Executes the same shell command in each project.
52
Zhiguang Lia8864fb2013-03-15 10:32:10 +080053The -r option allows running the command only on projects matching
54regex or wildcard expression.
55
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070056Output Formatting
57-----------------
58
59The -p option causes '%prog' to bind pipes to the command's stdin,
60stdout and stderr streams, and pipe all output into a continuous
61stream that is displayed in a single pager session. Project headings
62are inserted before the output of each command is displayed. If the
63command produces no output in a project, no heading is displayed.
64
65The formatting convention used by -p is very suitable for some
66types of searching, e.g. `repo forall -p -c git log -SFoo` will
67print all commits that add or remove references to Foo.
68
69The -v option causes '%prog' to display stderr messages if a
70command produces output only on stderr. Normally the -p option
71causes command output to be suppressed until the command produces
72at least one byte of output on stdout.
73
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070074Environment
75-----------
Shawn O. Pearceff84fea2009-04-13 12:11:59 -070076
Shawn O. Pearce44469462009-03-03 17:51:01 -080077pwd is the project's working directory. If the current client is
78a mirror client, then pwd is the Git repository.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070079
80REPO_PROJECT is set to the unique name of the project.
81
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050082REPO_PATH is the path relative the the root of the client.
83
84REPO_REMOTE is the name of the remote system from the manifest.
85
86REPO_LREV is the name of the revision from the manifest, translated
87to a local tracking branch. If you need to pass the manifest
88revision to a locally executed git command, use REPO_LREV.
89
90REPO_RREV is the name of the revision from the manifest, exactly
91as written in the manifest.
92
Mitchel Humpheryse81bc032014-03-31 11:36:56 -070093REPO_COUNT is the total number of projects being iterated.
94
95REPO_I is the current (1-based) iteration count. Can be used in
96conjunction with REPO_COUNT to add a simple progress indicator to your
97command.
98
James W. Mills24c13082012-04-12 15:04:13 -050099REPO__* are any extra environment variables, specified by the
100"annotation" element under any project element. This can be useful
101for differentiating trees based on user-specific criteria, or simply
102annotating tree details.
103
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700104shell positional arguments ($1, $2, .., $#) are set to any arguments
105following <command>.
106
David Pursehousef46902a2017-10-31 12:27:17 +0900107Example: to list projects:
108
109 %prog% forall -c 'echo $REPO_PROJECT'
110
111Notice that $REPO_PROJECT is quoted to ensure it is expanded in
112the context of running <command> instead of in the calling shell.
113
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700114Unless -p is used, stdin, stdout, stderr are inherited from the
115terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +0200116
117If -e is used, when a command exits unsuccessfully, '%prog' will abort
118without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700119"""
120
121 def _Options(self, p):
122 def cmd(option, opt_str, value, parser):
123 setattr(parser.values, option.dest, list(parser.rargs))
124 while parser.rargs:
125 del parser.rargs[0]
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800126 p.add_option('-r', '--regex',
127 dest='regex', action='store_true',
128 help="Execute the command only on projects matching regex or wildcard expression")
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900129 p.add_option('-i', '--inverse-regex',
130 dest='inverse_regex', action='store_true',
131 help="Execute the command only on projects not matching regex or wildcard expression")
Graham Christensen0369a062015-07-29 17:02:54 -0500132 p.add_option('-g', '--groups',
133 dest='groups',
134 help="Execute the command only on projects matching the specified groups")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135 p.add_option('-c', '--command',
136 help='Command (and arguments) to execute',
137 dest='command',
138 action='callback',
139 callback=cmd)
Victor Boivie88b86722011-09-07 09:43:28 +0200140 p.add_option('-e', '--abort-on-errors',
141 dest='abort_on_errors', action='store_true',
142 help='Abort if a command exits unsuccessfully')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700143
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700144 g = p.add_option_group('Output')
145 g.add_option('-p',
146 dest='project_header', action='store_true',
147 help='Show project headers before output')
148 g.add_option('-v', '--verbose',
149 dest='verbose', action='store_true',
150 help='Show command error messages')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900151 g.add_option('-j', '--jobs',
152 dest='jobs', action='store', type='int', default=1,
153 help='number of commands to execute simultaneously')
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700154
155 def WantPager(self, opt):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900156 return opt.project_header and opt.jobs == 1
157
158 def _SerializeProject(self, project):
159 """ Serialize a project._GitGetByExec instance.
160
161 project._GitGetByExec is not pickle-able. Instead of trying to pass it
162 around between processes, make a dict ourselves containing only the
163 attributes that we need.
164
165 """
David Pursehouse30d13ee2015-05-07 15:01:15 +0900166 if not self.manifest.IsMirror:
167 lrev = project.GetRevisionId()
168 else:
169 lrev = None
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900170 return {
171 'name': project.name,
172 'relpath': project.relpath,
173 'remote_name': project.remote.name,
David Pursehouse30d13ee2015-05-07 15:01:15 +0900174 'lrev': lrev,
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900175 'rrev': project.revisionExpr,
176 'annotations': dict((a.name, a.value) for a in project.annotations),
177 'gitdir': project.gitdir,
178 'worktree': project.worktree,
179 }
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700180
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700181 def Execute(self, opt, args):
182 if not opt.command:
183 self.Usage()
184
185 cmd = [opt.command[0]]
186
187 shell = True
188 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
189 shell = False
190
191 if shell:
192 cmd.append(cmd[0])
193 cmd.extend(opt.command[1:])
194
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700195 if opt.project_header \
196 and not shell \
197 and cmd[0] == 'git':
198 # If this is a direct git command that can enable colorized
199 # output and the user prefers coloring, add --color into the
200 # command line because we are going to wrap the command into
201 # a pipe and git won't know coloring should activate.
202 #
203 for cn in cmd[1:]:
204 if not cn.startswith('-'):
205 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900206 else:
207 cn = None
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900208 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700209 class ColorCmd(Coloring):
210 def __init__(self, config, cmd):
211 Coloring.__init__(self, config, cmd)
212 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
213 cmd.insert(cmd.index(cn) + 1, '--color')
214
Shawn O. Pearce44469462009-03-03 17:51:01 -0800215 mirror = self.manifest.IsMirror
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700216 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700217
David Pursehouse6944cdb2015-05-07 14:39:44 +0900218 smart_sync_manifest_name = "smart_sync_override.xml"
219 smart_sync_manifest_path = os.path.join(
220 self.manifest.manifestProject.worktree, smart_sync_manifest_name)
221
222 if os.path.isfile(smart_sync_manifest_path):
223 self.manifest.Override(smart_sync_manifest_path)
224
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900225 if opt.regex:
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800226 projects = self.FindProjects(args)
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900227 elif opt.inverse_regex:
228 projects = self.FindProjects(args, inverse=True)
229 else:
230 projects = self.GetProjects(args, groups=opt.groups)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800231
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700232 os.environ['REPO_COUNT'] = str(len(projects))
233
Colin Cross31a7be52015-05-13 00:04:36 -0700234 pool = multiprocessing.Pool(opt.jobs, InitWorker)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900235 try:
236 config = self.manifest.manifestProject.config
237 results_it = pool.imap(
238 DoWorkWrapper,
Colin Cross31a7be52015-05-13 00:04:36 -0700239 self.ProjectArgs(projects, mirror, opt, cmd, shell, config))
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900240 pool.close()
241 for r in results_it:
242 rc = rc or r
243 if r != 0 and opt.abort_on_errors:
244 raise Exception('Aborting due to previous error')
245 except (KeyboardInterrupt, WorkerKeyboardInterrupt):
246 # Catch KeyboardInterrupt raised inside and outside of workers
247 print('Interrupted - terminating the pool')
248 pool.terminate()
249 rc = rc or errno.EINTR
250 except Exception as e:
251 # Catch any other exceptions raised
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200252 print('Got an error, terminating the pool: %s: %s' %
253 (type(e).__name__, e),
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900254 file=sys.stderr)
255 pool.terminate()
256 rc = rc or getattr(e, 'errno', 1)
257 finally:
258 pool.join()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700259 if rc != 0:
260 sys.exit(rc)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900261
Colin Cross31a7be52015-05-13 00:04:36 -0700262 def ProjectArgs(self, projects, mirror, opt, cmd, shell, config):
263 for cnt, p in enumerate(projects):
264 try:
265 project = self._SerializeProject(p)
266 except Exception as e:
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200267 print('Project list error on project %s: %s: %s' %
268 (p.name, type(e).__name__, e),
Colin Cross31a7be52015-05-13 00:04:36 -0700269 file=sys.stderr)
270 return
271 except KeyboardInterrupt:
272 print('Project list interrupted',
273 file=sys.stderr)
274 return
275 yield [mirror, opt, cmd, shell, cnt, config, project]
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900276
277class WorkerKeyboardInterrupt(Exception):
278 """ Keyboard interrupt exception for worker processes. """
279 pass
280
281
Colin Cross31a7be52015-05-13 00:04:36 -0700282def InitWorker():
283 signal.signal(signal.SIGINT, signal.SIG_IGN)
284
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900285def DoWorkWrapper(args):
286 """ A wrapper around the DoWork() method.
287
288 Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
289 ``Exception``-based exception to stop it flooding the console with stacktraces
290 and making the parent hang indefinitely.
291
292 """
293 project = args.pop()
294 try:
295 return DoWork(project, *args)
296 except KeyboardInterrupt:
297 print('%s: Worker interrupted' % project['name'])
298 raise WorkerKeyboardInterrupt()
299
300
301def DoWork(project, mirror, opt, cmd, shell, cnt, config):
302 env = os.environ.copy()
303 def setenv(name, val):
304 if val is None:
305 val = ''
Anthony Kingc116f942015-06-03 17:29:29 +0100306 if hasattr(val, 'encode'):
307 val = val.encode()
308 env[name] = val
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900309
310 setenv('REPO_PROJECT', project['name'])
311 setenv('REPO_PATH', project['relpath'])
312 setenv('REPO_REMOTE', project['remote_name'])
313 setenv('REPO_LREV', project['lrev'])
314 setenv('REPO_RREV', project['rrev'])
315 setenv('REPO_I', str(cnt + 1))
316 for name in project['annotations']:
317 setenv("REPO__%s" % (name), project['annotations'][name])
318
319 if mirror:
320 setenv('GIT_DIR', project['gitdir'])
321 cwd = project['gitdir']
322 else:
323 cwd = project['worktree']
324
325 if not os.path.exists(cwd):
326 if (opt.project_header and opt.verbose) \
327 or not opt.project_header:
328 print('skipping %s/' % project['relpath'], file=sys.stderr)
329 return
330
331 if opt.project_header:
332 stdin = subprocess.PIPE
333 stdout = subprocess.PIPE
334 stderr = subprocess.PIPE
335 else:
336 stdin = None
337 stdout = None
338 stderr = None
339
340 p = subprocess.Popen(cmd,
341 cwd=cwd,
342 shell=shell,
343 env=env,
344 stdin=stdin,
345 stdout=stdout,
346 stderr=stderr)
347
348 if opt.project_header:
349 out = ForallColoring(config)
350 out.redirect(sys.stdout)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900351 empty = True
352 errbuf = ''
353
354 p.stdin.close()
Renaud Paquay2e702912016-11-01 11:23:38 -0700355 s_in = platform_utils.FileDescriptorStreams.create()
356 s_in.add(p.stdout, sys.stdout, 'stdout')
357 s_in.add(p.stderr, sys.stderr, 'stderr')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900358
Renaud Paquay2e702912016-11-01 11:23:38 -0700359 while not s_in.is_done:
360 in_ready = s_in.select()
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900361 for s in in_ready:
Renaud Paquay2e702912016-11-01 11:23:38 -0700362 buf = s.read()
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900363 if not buf:
Renaud Paquay2e702912016-11-01 11:23:38 -0700364 s.close()
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900365 s_in.remove(s)
366 continue
367
368 if not opt.verbose:
Renaud Paquay2e702912016-11-01 11:23:38 -0700369 if s.std_name == 'stderr':
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900370 errbuf += buf
371 continue
372
373 if empty and out:
374 if not cnt == 0:
375 out.nl()
376
377 if mirror:
378 project_header_path = project['name']
379 else:
380 project_header_path = project['relpath']
381 out.project('project %s/', project_header_path)
382 out.nl()
383 out.flush()
384 if errbuf:
385 sys.stderr.write(errbuf)
386 sys.stderr.flush()
387 errbuf = ''
388 empty = False
389
390 s.dest.write(buf)
391 s.dest.flush()
392
393 r = p.wait()
394 return r