blob: b10f34b3864c6c3e3ae633e18eb6b87eff615f42 [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")
Graham Christensen0369a062015-07-29 17:02:54 -0500123 p.add_option('-g', '--groups',
124 dest='groups',
125 help="Execute the command only on projects matching the specified groups")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126 p.add_option('-c', '--command',
127 help='Command (and arguments) to execute',
128 dest='command',
129 action='callback',
130 callback=cmd)
Victor Boivie88b86722011-09-07 09:43:28 +0200131 p.add_option('-e', '--abort-on-errors',
132 dest='abort_on_errors', action='store_true',
133 help='Abort if a command exits unsuccessfully')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700135 g = p.add_option_group('Output')
136 g.add_option('-p',
137 dest='project_header', action='store_true',
138 help='Show project headers before output')
139 g.add_option('-v', '--verbose',
140 dest='verbose', action='store_true',
141 help='Show command error messages')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900142 g.add_option('-j', '--jobs',
143 dest='jobs', action='store', type='int', default=1,
144 help='number of commands to execute simultaneously')
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700145
146 def WantPager(self, opt):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900147 return opt.project_header and opt.jobs == 1
148
149 def _SerializeProject(self, project):
150 """ Serialize a project._GitGetByExec instance.
151
152 project._GitGetByExec is not pickle-able. Instead of trying to pass it
153 around between processes, make a dict ourselves containing only the
154 attributes that we need.
155
156 """
David Pursehouse30d13ee2015-05-07 15:01:15 +0900157 if not self.manifest.IsMirror:
158 lrev = project.GetRevisionId()
159 else:
160 lrev = None
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900161 return {
162 'name': project.name,
163 'relpath': project.relpath,
164 'remote_name': project.remote.name,
David Pursehouse30d13ee2015-05-07 15:01:15 +0900165 'lrev': lrev,
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900166 'rrev': project.revisionExpr,
167 'annotations': dict((a.name, a.value) for a in project.annotations),
168 'gitdir': project.gitdir,
169 'worktree': project.worktree,
170 }
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700171
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700172 def Execute(self, opt, args):
173 if not opt.command:
174 self.Usage()
175
176 cmd = [opt.command[0]]
177
178 shell = True
179 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
180 shell = False
181
182 if shell:
183 cmd.append(cmd[0])
184 cmd.extend(opt.command[1:])
185
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700186 if opt.project_header \
187 and not shell \
188 and cmd[0] == 'git':
189 # If this is a direct git command that can enable colorized
190 # output and the user prefers coloring, add --color into the
191 # command line because we are going to wrap the command into
192 # a pipe and git won't know coloring should activate.
193 #
194 for cn in cmd[1:]:
195 if not cn.startswith('-'):
196 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900197 else:
198 cn = None
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900199 # pylint: disable=W0631
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900200 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700201 class ColorCmd(Coloring):
202 def __init__(self, config, cmd):
203 Coloring.__init__(self, config, cmd)
204 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
205 cmd.insert(cmd.index(cn) + 1, '--color')
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900206 # pylint: enable=W0631
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700207
Shawn O. Pearce44469462009-03-03 17:51:01 -0800208 mirror = self.manifest.IsMirror
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700209 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700210
David Pursehouse6944cdb2015-05-07 14:39:44 +0900211 smart_sync_manifest_name = "smart_sync_override.xml"
212 smart_sync_manifest_path = os.path.join(
213 self.manifest.manifestProject.worktree, smart_sync_manifest_name)
214
215 if os.path.isfile(smart_sync_manifest_path):
216 self.manifest.Override(smart_sync_manifest_path)
217
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800218 if not opt.regex:
Graham Christensen0369a062015-07-29 17:02:54 -0500219 projects = self.GetProjects(args, groups=opt.groups)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800220 else:
221 projects = self.FindProjects(args)
222
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700223 os.environ['REPO_COUNT'] = str(len(projects))
224
Colin Cross31a7be52015-05-13 00:04:36 -0700225 pool = multiprocessing.Pool(opt.jobs, InitWorker)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900226 try:
227 config = self.manifest.manifestProject.config
228 results_it = pool.imap(
229 DoWorkWrapper,
Colin Cross31a7be52015-05-13 00:04:36 -0700230 self.ProjectArgs(projects, mirror, opt, cmd, shell, config))
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900231 pool.close()
232 for r in results_it:
233 rc = rc or r
234 if r != 0 and opt.abort_on_errors:
235 raise Exception('Aborting due to previous error')
236 except (KeyboardInterrupt, WorkerKeyboardInterrupt):
237 # Catch KeyboardInterrupt raised inside and outside of workers
238 print('Interrupted - terminating the pool')
239 pool.terminate()
240 rc = rc or errno.EINTR
241 except Exception as e:
242 # Catch any other exceptions raised
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200243 print('Got an error, terminating the pool: %s: %s' %
244 (type(e).__name__, e),
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900245 file=sys.stderr)
246 pool.terminate()
247 rc = rc or getattr(e, 'errno', 1)
248 finally:
249 pool.join()
250 if rc != 0:
251 sys.exit(rc)
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700252
Colin Cross31a7be52015-05-13 00:04:36 -0700253 def ProjectArgs(self, projects, mirror, opt, cmd, shell, config):
254 for cnt, p in enumerate(projects):
255 try:
256 project = self._SerializeProject(p)
257 except Exception as e:
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200258 print('Project list error on project %s: %s: %s' %
259 (p.name, type(e).__name__, e),
Colin Cross31a7be52015-05-13 00:04:36 -0700260 file=sys.stderr)
261 return
262 except KeyboardInterrupt:
263 print('Project list interrupted',
264 file=sys.stderr)
265 return
266 yield [mirror, opt, cmd, shell, cnt, config, project]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900268class WorkerKeyboardInterrupt(Exception):
269 """ Keyboard interrupt exception for worker processes. """
270 pass
Shawn O. Pearce44469462009-03-03 17:51:01 -0800271
Shawn O. Pearce1b5a4a02009-08-22 18:50:45 -0700272
Colin Cross31a7be52015-05-13 00:04:36 -0700273def InitWorker():
274 signal.signal(signal.SIGINT, signal.SIG_IGN)
275
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900276def DoWorkWrapper(args):
277 """ A wrapper around the DoWork() method.
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700278
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900279 Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
280 ``Exception``-based exception to stop it flooding the console with stacktraces
281 and making the parent hang indefinitely.
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700282
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900283 """
284 project = args.pop()
285 try:
286 return DoWork(project, *args)
287 except KeyboardInterrupt:
288 print('%s: Worker interrupted' % project['name'])
289 raise WorkerKeyboardInterrupt()
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700290
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700291
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900292def DoWork(project, mirror, opt, cmd, shell, cnt, config):
293 env = os.environ.copy()
294 def setenv(name, val):
295 if val is None:
296 val = ''
Anthony Kingc116f942015-06-03 17:29:29 +0100297 if hasattr(val, 'encode'):
298 val = val.encode()
299 env[name] = val
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700300
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900301 setenv('REPO_PROJECT', project['name'])
302 setenv('REPO_PATH', project['relpath'])
303 setenv('REPO_REMOTE', project['remote_name'])
304 setenv('REPO_LREV', project['lrev'])
305 setenv('REPO_RREV', project['rrev'])
306 setenv('REPO_I', str(cnt + 1))
307 for name in project['annotations']:
308 setenv("REPO__%s" % (name), project['annotations'][name])
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700309
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900310 if mirror:
311 setenv('GIT_DIR', project['gitdir'])
312 cwd = project['gitdir']
313 else:
314 cwd = project['worktree']
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700315
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900316 if not os.path.exists(cwd):
317 if (opt.project_header and opt.verbose) \
318 or not opt.project_header:
319 print('skipping %s/' % project['relpath'], file=sys.stderr)
320 return
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700321
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900322 if opt.project_header:
323 stdin = subprocess.PIPE
324 stdout = subprocess.PIPE
325 stderr = subprocess.PIPE
326 else:
327 stdin = None
328 stdout = None
329 stderr = None
Jorge Gonzalez5bca9fc2013-06-03 12:00:06 -0700330
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900331 p = subprocess.Popen(cmd,
332 cwd=cwd,
333 shell=shell,
334 env=env,
335 stdin=stdin,
336 stdout=stdout,
337 stderr=stderr)
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700338
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900339 if opt.project_header:
340 out = ForallColoring(config)
341 out.redirect(sys.stdout)
342 class sfd(object):
343 def __init__(self, fd, dest):
344 self.fd = fd
345 self.dest = dest
346 def fileno(self):
347 return self.fd.fileno()
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700348
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900349 empty = True
350 errbuf = ''
351
352 p.stdin.close()
353 s_in = [sfd(p.stdout, sys.stdout),
354 sfd(p.stderr, sys.stderr)]
355
356 for s in s_in:
357 flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
358 fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
359
360 while s_in:
361 in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
362 for s in in_ready:
363 buf = s.fd.read(4096)
364 if not buf:
365 s.fd.close()
366 s_in.remove(s)
367 continue
368
369 if not opt.verbose:
370 if s.fd != p.stdout:
371 errbuf += buf
372 continue
373
374 if empty and out:
375 if not cnt == 0:
376 out.nl()
377
378 if mirror:
379 project_header_path = project['name']
380 else:
381 project_header_path = project['relpath']
382 out.project('project %s/', project_header_path)
383 out.nl()
384 out.flush()
385 if errbuf:
386 sys.stderr.write(errbuf)
387 sys.stderr.flush()
388 errbuf = ''
389 empty = False
390
391 s.dest.write(buf)
392 s.dest.flush()
393
394 r = p.wait()
395 return r