blob: 55d61ecb2a38d0105fcd7ba57c6565068e4f8ffb [file] [log] [blame]
Mike Frysingerf6013762019-06-13 02:30:51 -04001# -*- coding:utf-8 -*-
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002#
3# Copyright (C) 2008 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Sarah Owenscecd1d82012-11-01 22:59:27 -070017from __future__ import print_function
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090018import errno
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090019import multiprocessing
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import re
21import os
Colin Cross31a7be52015-05-13 00:04:36 -070022import signal
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023import sys
24import subprocess
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070025
26from color import Coloring
Shawn O. Pearce44469462009-03-03 17:51:01 -080027from command import Command, MirrorSafeCommand
Renaud Paquay2e702912016-11-01 11:23:38 -070028import platform_utils
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070030_CAN_COLOR = [
David Pursehouseabdf7502020-02-12 14:58:39 +090031 'branch',
32 'diff',
33 'grep',
34 'log',
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070035]
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
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040057# Output Formatting
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070058
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
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040074# Environment
Shawn O. Pearceff84fea2009-04-13 12:11:59 -070075
Shawn O. Pearce44469462009-03-03 17:51:01 -080076pwd is the project's working directory. If the current client is
77a mirror client, then pwd is the Git repository.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070078
79REPO_PROJECT is set to the unique name of the project.
80
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050081REPO_PATH is the path relative the the root of the client.
82
83REPO_REMOTE is the name of the remote system from the manifest.
84
85REPO_LREV is the name of the revision from the manifest, translated
86to a local tracking branch. If you need to pass the manifest
87revision to a locally executed git command, use REPO_LREV.
88
89REPO_RREV is the name of the revision from the manifest, exactly
90as written in the manifest.
91
Mitchel Humpheryse81bc032014-03-31 11:36:56 -070092REPO_COUNT is the total number of projects being iterated.
93
94REPO_I is the current (1-based) iteration count. Can be used in
95conjunction with REPO_COUNT to add a simple progress indicator to your
96command.
97
James W. Mills24c13082012-04-12 15:04:13 -050098REPO__* are any extra environment variables, specified by the
99"annotation" element under any project element. This can be useful
100for differentiating trees based on user-specific criteria, or simply
101annotating tree details.
102
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103shell positional arguments ($1, $2, .., $#) are set to any arguments
104following <command>.
105
David Pursehousef46902a2017-10-31 12:27:17 +0900106Example: to list projects:
107
Solomon Kinard490e1632019-07-08 15:09:55 -0700108 %prog -c 'echo $REPO_PROJECT'
David Pursehousef46902a2017-10-31 12:27:17 +0900109
110Notice that $REPO_PROJECT is quoted to ensure it is expanded in
111the context of running <command> instead of in the calling shell.
112
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700113Unless -p is used, stdin, stdout, stderr are inherited from the
114terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +0200115
116If -e is used, when a command exits unsuccessfully, '%prog' will abort
117without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118"""
119
120 def _Options(self, p):
121 def cmd(option, opt_str, value, parser):
122 setattr(parser.values, option.dest, list(parser.rargs))
123 while parser.rargs:
124 del parser.rargs[0]
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800125 p.add_option('-r', '--regex',
126 dest='regex', action='store_true',
127 help="Execute the command only on projects matching regex or wildcard expression")
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900128 p.add_option('-i', '--inverse-regex',
129 dest='inverse_regex', action='store_true',
David Pursehouse3cda50a2020-02-13 13:17:03 +0900130 help="Execute the command only on projects not matching regex or "
131 "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')
Mike Frysingerb4668542019-10-21 22:53:46 -0400143 p.add_option('--ignore-missing', action='store_true',
144 help='Silently skip & do not exit non-zero due missing '
145 'checkouts')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700146
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700147 g = p.add_option_group('Output')
148 g.add_option('-p',
149 dest='project_header', action='store_true',
150 help='Show project headers before output')
151 g.add_option('-v', '--verbose',
152 dest='verbose', action='store_true',
153 help='Show command error messages')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900154 g.add_option('-j', '--jobs',
155 dest='jobs', action='store', type='int', default=1,
156 help='number of commands to execute simultaneously')
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700157
158 def WantPager(self, opt):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900159 return opt.project_header and opt.jobs == 1
160
161 def _SerializeProject(self, project):
162 """ Serialize a project._GitGetByExec instance.
163
164 project._GitGetByExec is not pickle-able. Instead of trying to pass it
165 around between processes, make a dict ourselves containing only the
166 attributes that we need.
167
168 """
David Pursehouse30d13ee2015-05-07 15:01:15 +0900169 if not self.manifest.IsMirror:
170 lrev = project.GetRevisionId()
171 else:
172 lrev = None
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900173 return {
David Pursehouseabdf7502020-02-12 14:58:39 +0900174 'name': project.name,
175 'relpath': project.relpath,
176 'remote_name': project.remote.name,
177 'lrev': lrev,
178 'rrev': project.revisionExpr,
179 'annotations': dict((a.name, a.value) for a in project.annotations),
180 'gitdir': project.gitdir,
181 'worktree': project.worktree,
Sean McAllister74e8ed42020-04-15 12:24:43 -0600182 'upstream': project.upstream,
183 'dest_branch': project.dest_branch,
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900184 }
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700185
Mike Frysingerae6cb082019-08-27 01:10:59 -0400186 def ValidateOptions(self, opt, args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700187 if not opt.command:
188 self.Usage()
189
Mike Frysingerae6cb082019-08-27 01:10:59 -0400190 def Execute(self, opt, args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700191 cmd = [opt.command[0]]
192
193 shell = True
194 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
195 shell = False
196
197 if shell:
198 cmd.append(cmd[0])
199 cmd.extend(opt.command[1:])
200
David Pursehouse54a4e602020-02-12 14:31:05 +0900201 if opt.project_header \
David Pursehouseabdf7502020-02-12 14:58:39 +0900202 and not shell \
203 and cmd[0] == 'git':
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700204 # If this is a direct git command that can enable colorized
205 # output and the user prefers coloring, add --color into the
206 # command line because we are going to wrap the command into
207 # a pipe and git won't know coloring should activate.
208 #
209 for cn in cmd[1:]:
210 if not cn.startswith('-'):
211 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900212 else:
213 cn = None
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900214 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700215 class ColorCmd(Coloring):
216 def __init__(self, config, cmd):
217 Coloring.__init__(self, config, cmd)
218 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
219 cmd.insert(cmd.index(cn) + 1, '--color')
220
Shawn O. Pearce44469462009-03-03 17:51:01 -0800221 mirror = self.manifest.IsMirror
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700223
David Pursehouse6944cdb2015-05-07 14:39:44 +0900224 smart_sync_manifest_name = "smart_sync_override.xml"
225 smart_sync_manifest_path = os.path.join(
David Pursehouseabdf7502020-02-12 14:58:39 +0900226 self.manifest.manifestProject.worktree, smart_sync_manifest_name)
David Pursehouse6944cdb2015-05-07 14:39:44 +0900227
228 if os.path.isfile(smart_sync_manifest_path):
229 self.manifest.Override(smart_sync_manifest_path)
230
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900231 if opt.regex:
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800232 projects = self.FindProjects(args)
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900233 elif opt.inverse_regex:
234 projects = self.FindProjects(args, inverse=True)
235 else:
236 projects = self.GetProjects(args, groups=opt.groups)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800237
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700238 os.environ['REPO_COUNT'] = str(len(projects))
239
Colin Cross31a7be52015-05-13 00:04:36 -0700240 pool = multiprocessing.Pool(opt.jobs, InitWorker)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900241 try:
242 config = self.manifest.manifestProject.config
243 results_it = pool.imap(
David Pursehouseabdf7502020-02-12 14:58:39 +0900244 DoWorkWrapper,
245 self.ProjectArgs(projects, mirror, opt, cmd, shell, config))
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900246 pool.close()
247 for r in results_it:
248 rc = rc or r
249 if r != 0 and opt.abort_on_errors:
250 raise Exception('Aborting due to previous error')
251 except (KeyboardInterrupt, WorkerKeyboardInterrupt):
252 # Catch KeyboardInterrupt raised inside and outside of workers
253 print('Interrupted - terminating the pool')
254 pool.terminate()
255 rc = rc or errno.EINTR
256 except Exception as e:
257 # Catch any other exceptions raised
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200258 print('Got an error, terminating the pool: %s: %s' %
David Pursehouseabdf7502020-02-12 14:58:39 +0900259 (type(e).__name__, e),
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900260 file=sys.stderr)
261 pool.terminate()
262 rc = rc or getattr(e, 'errno', 1)
263 finally:
264 pool.join()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700265 if rc != 0:
266 sys.exit(rc)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900267
Colin Cross31a7be52015-05-13 00:04:36 -0700268 def ProjectArgs(self, projects, mirror, opt, cmd, shell, config):
269 for cnt, p in enumerate(projects):
270 try:
271 project = self._SerializeProject(p)
272 except Exception as e:
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200273 print('Project list error on project %s: %s: %s' %
David Pursehouseabdf7502020-02-12 14:58:39 +0900274 (p.name, type(e).__name__, e),
Colin Cross31a7be52015-05-13 00:04:36 -0700275 file=sys.stderr)
276 return
277 except KeyboardInterrupt:
278 print('Project list interrupted',
279 file=sys.stderr)
280 return
281 yield [mirror, opt, cmd, shell, cnt, config, project]
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900282
David Pursehouse819827a2020-02-12 15:20:19 +0900283
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900284class WorkerKeyboardInterrupt(Exception):
285 """ Keyboard interrupt exception for worker processes. """
286 pass
287
288
Colin Cross31a7be52015-05-13 00:04:36 -0700289def InitWorker():
290 signal.signal(signal.SIGINT, signal.SIG_IGN)
291
David Pursehouse819827a2020-02-12 15:20:19 +0900292
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900293def DoWorkWrapper(args):
294 """ A wrapper around the DoWork() method.
295
296 Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
297 ``Exception``-based exception to stop it flooding the console with stacktraces
298 and making the parent hang indefinitely.
299
300 """
301 project = args.pop()
302 try:
303 return DoWork(project, *args)
304 except KeyboardInterrupt:
305 print('%s: Worker interrupted' % project['name'])
306 raise WorkerKeyboardInterrupt()
307
308
309def DoWork(project, mirror, opt, cmd, shell, cnt, config):
310 env = os.environ.copy()
David Pursehouse819827a2020-02-12 15:20:19 +0900311
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900312 def setenv(name, val):
313 if val is None:
314 val = ''
Anthony Kingc116f942015-06-03 17:29:29 +0100315 env[name] = val
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900316
317 setenv('REPO_PROJECT', project['name'])
318 setenv('REPO_PATH', project['relpath'])
319 setenv('REPO_REMOTE', project['remote_name'])
320 setenv('REPO_LREV', project['lrev'])
321 setenv('REPO_RREV', project['rrev'])
Sean McAllister74e8ed42020-04-15 12:24:43 -0600322 setenv('REPO_UPSTREAM', project['upstream'])
323 setenv('REPO_DEST_BRANCH', project['dest_branch'])
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900324 setenv('REPO_I', str(cnt + 1))
325 for name in project['annotations']:
326 setenv("REPO__%s" % (name), project['annotations'][name])
327
328 if mirror:
329 setenv('GIT_DIR', project['gitdir'])
330 cwd = project['gitdir']
331 else:
332 cwd = project['worktree']
333
334 if not os.path.exists(cwd):
Mike Frysingerb4668542019-10-21 22:53:46 -0400335 # Allow the user to silently ignore missing checkouts so they can run on
336 # partial checkouts (good for infra recovery tools).
337 if opt.ignore_missing:
338 return 0
Mike Frysingerdc1b59d2019-09-30 23:47:03 -0400339 if ((opt.project_header and opt.verbose)
David Pursehouseabdf7502020-02-12 14:58:39 +0900340 or not opt.project_header):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900341 print('skipping %s/' % project['relpath'], file=sys.stderr)
Mike Frysingerdc1b59d2019-09-30 23:47:03 -0400342 return 1
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900343
344 if opt.project_header:
345 stdin = subprocess.PIPE
346 stdout = subprocess.PIPE
347 stderr = subprocess.PIPE
348 else:
349 stdin = None
350 stdout = None
351 stderr = None
352
353 p = subprocess.Popen(cmd,
354 cwd=cwd,
355 shell=shell,
356 env=env,
357 stdin=stdin,
358 stdout=stdout,
359 stderr=stderr)
360
361 if opt.project_header:
362 out = ForallColoring(config)
363 out.redirect(sys.stdout)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900364 empty = True
365 errbuf = ''
366
367 p.stdin.close()
Renaud Paquay2e702912016-11-01 11:23:38 -0700368 s_in = platform_utils.FileDescriptorStreams.create()
369 s_in.add(p.stdout, sys.stdout, 'stdout')
370 s_in.add(p.stderr, sys.stderr, 'stderr')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900371
Renaud Paquay2e702912016-11-01 11:23:38 -0700372 while not s_in.is_done:
373 in_ready = s_in.select()
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900374 for s in in_ready:
Jiri Tyr83a32272020-02-06 16:32:46 +0000375 buf = s.read().decode()
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900376 if not buf:
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900377 s_in.remove(s)
Karsten Pfeiffer-Raddatzd0864672020-04-13 13:48:04 +0200378 s.close()
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900379 continue
380
381 if not opt.verbose:
Renaud Paquay2e702912016-11-01 11:23:38 -0700382 if s.std_name == 'stderr':
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900383 errbuf += buf
384 continue
385
386 if empty and out:
387 if not cnt == 0:
388 out.nl()
389
390 if mirror:
391 project_header_path = project['name']
392 else:
393 project_header_path = project['relpath']
394 out.project('project %s/', project_header_path)
395 out.nl()
396 out.flush()
397 if errbuf:
398 sys.stderr.write(errbuf)
399 sys.stderr.flush()
400 errbuf = ''
401 empty = False
402
403 s.dest.write(buf)
404 s.dest.flush()
405
406 r = p.wait()
407 return r