blob: f9f34e332cf76953cf8560e4dbd869aeac2f48ad [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# Copyright (C) 2008 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090015import errno
Mike Frysinger819c7392021-03-01 02:06:10 -050016import functools
Mike Frysingerfbab6062021-02-16 13:51:44 -050017import io
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
Mike Frysinger15e807c2021-02-16 01:56:30 -050026from command import DEFAULT_LOCAL_JOBS, Command, MirrorSafeCommand, WORKER_BATCH_SIZE
Mike Frysingerddab0602021-03-25 01:58:20 -040027from error import ManifestInvalidRevisionError
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070029_CAN_COLOR = [
David Pursehouseabdf7502020-02-12 14:58:39 +090030 'branch',
31 'diff',
32 'grep',
33 'log',
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070034]
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):
Mike Frysinger4f210542021-06-14 16:05:19 -040044 COMMON = False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070045 helpSummary = "Run a shell command in each project"
46 helpUsage = """
47%prog [<project>...] -c <command> [<arg>...]
Mike Frysinger323b1132021-03-19 13:45:57 -040048%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
Mike Frysingerd34af282021-03-18 13:54:34 -040056By default, projects are processed non-interactively in parallel. If you want
57to run interactive commands, make sure to pass --interactive to force --jobs 1.
58While the processing order of projects is not guaranteed, the order of project
59output is stable.
60
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040061# Output Formatting
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070062
63The -p option causes '%prog' to bind pipes to the command's stdin,
64stdout and stderr streams, and pipe all output into a continuous
65stream that is displayed in a single pager session. Project headings
66are inserted before the output of each command is displayed. If the
67command produces no output in a project, no heading is displayed.
68
69The formatting convention used by -p is very suitable for some
70types of searching, e.g. `repo forall -p -c git log -SFoo` will
71print all commits that add or remove references to Foo.
72
73The -v option causes '%prog' to display stderr messages if a
74command produces output only on stderr. Normally the -p option
75causes command output to be suppressed until the command produces
76at least one byte of output on stdout.
77
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040078# Environment
Shawn O. Pearceff84fea2009-04-13 12:11:59 -070079
Shawn O. Pearce44469462009-03-03 17:51:01 -080080pwd is the project's working directory. If the current client is
81a mirror client, then pwd is the Git repository.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070082
83REPO_PROJECT is set to the unique name of the project.
84
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050085REPO_PATH is the path relative the the root of the client.
86
LaMont Jonesd8de29c2022-04-12 23:33:59 +000087REPO_OUTERPATH is the path of the sub manifest's root relative to the root of
88the client.
89
90REPO_INNERPATH is the path relative to the root of the sub manifest.
91
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050092REPO_REMOTE is the name of the remote system from the manifest.
93
94REPO_LREV is the name of the revision from the manifest, translated
95to a local tracking branch. If you need to pass the manifest
96revision to a locally executed git command, use REPO_LREV.
97
98REPO_RREV is the name of the revision from the manifest, exactly
99as written in the manifest.
100
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700101REPO_COUNT is the total number of projects being iterated.
102
103REPO_I is the current (1-based) iteration count. Can be used in
104conjunction with REPO_COUNT to add a simple progress indicator to your
105command.
106
James W. Mills24c13082012-04-12 15:04:13 -0500107REPO__* are any extra environment variables, specified by the
108"annotation" element under any project element. This can be useful
109for differentiating trees based on user-specific criteria, or simply
110annotating tree details.
111
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700112shell positional arguments ($1, $2, .., $#) are set to any arguments
113following <command>.
114
David Pursehousef46902a2017-10-31 12:27:17 +0900115Example: to list projects:
116
Solomon Kinard490e1632019-07-08 15:09:55 -0700117 %prog -c 'echo $REPO_PROJECT'
David Pursehousef46902a2017-10-31 12:27:17 +0900118
119Notice that $REPO_PROJECT is quoted to ensure it is expanded in
120the context of running <command> instead of in the calling shell.
121
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700122Unless -p is used, stdin, stdout, stderr are inherited from the
123terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +0200124
125If -e is used, when a command exits unsuccessfully, '%prog' will abort
126without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700127"""
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500128 PARALLEL_JOBS = DEFAULT_LOCAL_JOBS
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700129
Mike Frysinger179a2422021-03-01 02:03:44 -0500130 @staticmethod
131 def _cmd_option(option, _opt_str, _value, parser):
132 setattr(parser.values, option.dest, list(parser.rargs))
133 while parser.rargs:
134 del parser.rargs[0]
135
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136 def _Options(self, p):
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800137 p.add_option('-r', '--regex',
138 dest='regex', action='store_true',
Mike Frysingerc177f942021-05-04 08:06:36 -0400139 help='execute the command only on projects matching regex or wildcard expression')
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900140 p.add_option('-i', '--inverse-regex',
141 dest='inverse_regex', action='store_true',
Mike Frysingerc177f942021-05-04 08:06:36 -0400142 help='execute the command only on projects not matching regex or '
143 'wildcard expression')
Graham Christensen0369a062015-07-29 17:02:54 -0500144 p.add_option('-g', '--groups',
145 dest='groups',
Mike Frysingerc177f942021-05-04 08:06:36 -0400146 help='execute the command only on projects matching the specified groups')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147 p.add_option('-c', '--command',
Mike Frysingerc177f942021-05-04 08:06:36 -0400148 help='command (and arguments) to execute',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700149 dest='command',
150 action='callback',
Mike Frysinger179a2422021-03-01 02:03:44 -0500151 callback=self._cmd_option)
Victor Boivie88b86722011-09-07 09:43:28 +0200152 p.add_option('-e', '--abort-on-errors',
153 dest='abort_on_errors', action='store_true',
Mike Frysingerc177f942021-05-04 08:06:36 -0400154 help='abort if a command exits unsuccessfully')
Mike Frysingerb4668542019-10-21 22:53:46 -0400155 p.add_option('--ignore-missing', action='store_true',
Mike Frysingerc177f942021-05-04 08:06:36 -0400156 help='silently skip & do not exit non-zero due missing '
Mike Frysingerb4668542019-10-21 22:53:46 -0400157 'checkouts')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700158
Mike Frysinger9180a072021-04-13 14:57:40 -0400159 g = p.get_option_group('--quiet')
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700160 g.add_option('-p',
161 dest='project_header', action='store_true',
Mike Frysingerc177f942021-05-04 08:06:36 -0400162 help='show project headers before output')
Mike Frysingerd34af282021-03-18 13:54:34 -0400163 p.add_option('--interactive',
164 action='store_true',
165 help='force interactive usage')
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700166
167 def WantPager(self, opt):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900168 return opt.project_header and opt.jobs == 1
169
Mike Frysingerae6cb082019-08-27 01:10:59 -0400170 def ValidateOptions(self, opt, args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700171 if not opt.command:
172 self.Usage()
173
Mike Frysingerae6cb082019-08-27 01:10:59 -0400174 def Execute(self, opt, args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700175 cmd = [opt.command[0]]
LaMont Jonescc879a92021-11-18 22:40:18 +0000176 all_trees = not opt.this_manifest_only
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700177
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
Mike Frysingerd34af282021-03-18 13:54:34 -0400186 # Historically, forall operated interactively, and in serial. If the user
187 # has selected 1 job, then default to interacive mode.
188 if opt.jobs == 1:
189 opt.interactive = True
190
David Pursehouse54a4e602020-02-12 14:31:05 +0900191 if opt.project_header \
David Pursehouseabdf7502020-02-12 14:58:39 +0900192 and not shell \
193 and cmd[0] == 'git':
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700194 # If this is a direct git command that can enable colorized
195 # output and the user prefers coloring, add --color into the
196 # command line because we are going to wrap the command into
197 # a pipe and git won't know coloring should activate.
198 #
199 for cn in cmd[1:]:
200 if not cn.startswith('-'):
201 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900202 else:
203 cn = None
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900204 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700205 class ColorCmd(Coloring):
206 def __init__(self, config, cmd):
207 Coloring.__init__(self, config, cmd)
208 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
209 cmd.insert(cmd.index(cn) + 1, '--color')
210
Shawn O. Pearce44469462009-03-03 17:51:01 -0800211 mirror = self.manifest.IsMirror
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700212 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700213
David Pursehouse6944cdb2015-05-07 14:39:44 +0900214 smart_sync_manifest_name = "smart_sync_override.xml"
215 smart_sync_manifest_path = os.path.join(
David Pursehouseabdf7502020-02-12 14:58:39 +0900216 self.manifest.manifestProject.worktree, smart_sync_manifest_name)
David Pursehouse6944cdb2015-05-07 14:39:44 +0900217
218 if os.path.isfile(smart_sync_manifest_path):
219 self.manifest.Override(smart_sync_manifest_path)
220
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900221 if opt.regex:
LaMont Jonescc879a92021-11-18 22:40:18 +0000222 projects = self.FindProjects(args, all_manifests=all_trees)
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900223 elif opt.inverse_regex:
LaMont Jonescc879a92021-11-18 22:40:18 +0000224 projects = self.FindProjects(args, inverse=True, all_manifests=all_trees)
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900225 else:
LaMont Jonescc879a92021-11-18 22:40:18 +0000226 projects = self.GetProjects(args, groups=opt.groups, all_manifests=all_trees)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800227
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700228 os.environ['REPO_COUNT'] = str(len(projects))
229
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900230 try:
231 config = self.manifest.manifestProject.config
Mike Frysinger15e807c2021-02-16 01:56:30 -0500232 with multiprocessing.Pool(opt.jobs, InitWorker) as pool:
233 results_it = pool.imap(
Mike Frysinger819c7392021-03-01 02:06:10 -0500234 functools.partial(DoWorkWrapper, mirror, opt, cmd, shell, config),
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500235 enumerate(projects),
Mike Frysinger15e807c2021-02-16 01:56:30 -0500236 chunksize=WORKER_BATCH_SIZE)
Mike Frysingerfbab6062021-02-16 13:51:44 -0500237 first = True
238 for (r, output) in results_it:
239 if output:
240 if first:
241 first = False
242 elif opt.project_header:
243 print()
244 # To simplify the DoWorkWrapper, take care of automatic newlines.
245 end = '\n'
246 if output[-1] == '\n':
247 end = ''
248 print(output, end=end)
Mike Frysinger15e807c2021-02-16 01:56:30 -0500249 rc = rc or r
250 if r != 0 and opt.abort_on_errors:
251 raise Exception('Aborting due to previous error')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900252 except (KeyboardInterrupt, WorkerKeyboardInterrupt):
253 # Catch KeyboardInterrupt raised inside and outside of workers
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900254 rc = rc or errno.EINTR
255 except Exception as e:
256 # Catch any other exceptions raised
Mike Frysingerddab0602021-03-25 01:58:20 -0400257 print('forall: unhandled error, terminating the pool: %s: %s' %
David Pursehouseabdf7502020-02-12 14:58:39 +0900258 (type(e).__name__, e),
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900259 file=sys.stderr)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900260 rc = rc or getattr(e, 'errno', 1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700261 if rc != 0:
262 sys.exit(rc)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900263
David Pursehouse819827a2020-02-12 15:20:19 +0900264
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900265class WorkerKeyboardInterrupt(Exception):
266 """ Keyboard interrupt exception for worker processes. """
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900267
268
Colin Cross31a7be52015-05-13 00:04:36 -0700269def InitWorker():
270 signal.signal(signal.SIGINT, signal.SIG_IGN)
271
David Pursehouse819827a2020-02-12 15:20:19 +0900272
Mike Frysinger819c7392021-03-01 02:06:10 -0500273def DoWorkWrapper(mirror, opt, cmd, shell, config, args):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900274 """ A wrapper around the DoWork() method.
275
276 Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
277 ``Exception``-based exception to stop it flooding the console with stacktraces
278 and making the parent hang indefinitely.
279
280 """
Mike Frysinger819c7392021-03-01 02:06:10 -0500281 cnt, project = args
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900282 try:
Mike Frysinger819c7392021-03-01 02:06:10 -0500283 return DoWork(project, mirror, opt, cmd, shell, cnt, config)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900284 except KeyboardInterrupt:
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500285 print('%s: Worker interrupted' % project.name)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900286 raise WorkerKeyboardInterrupt()
287
288
289def DoWork(project, mirror, opt, cmd, shell, cnt, config):
290 env = os.environ.copy()
David Pursehouse819827a2020-02-12 15:20:19 +0900291
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900292 def setenv(name, val):
293 if val is None:
294 val = ''
Anthony Kingc116f942015-06-03 17:29:29 +0100295 env[name] = val
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900296
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500297 setenv('REPO_PROJECT', project.name)
LaMont Jonesd8de29c2022-04-12 23:33:59 +0000298 setenv('REPO_OUTERPATH', project.manifest.path_prefix)
299 setenv('REPO_INNERPATH', project.relpath)
300 setenv('REPO_PATH', project.RelPath(local=opt.this_manifest_only))
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500301 setenv('REPO_REMOTE', project.remote.name)
Mike Frysingerddab0602021-03-25 01:58:20 -0400302 try:
303 # If we aren't in a fully synced state and we don't have the ref the manifest
304 # wants, then this will fail. Ignore it for the purposes of this code.
305 lrev = '' if mirror else project.GetRevisionId()
306 except ManifestInvalidRevisionError:
307 lrev = ''
308 setenv('REPO_LREV', lrev)
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500309 setenv('REPO_RREV', project.revisionExpr)
310 setenv('REPO_UPSTREAM', project.upstream)
311 setenv('REPO_DEST_BRANCH', project.dest_branch)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900312 setenv('REPO_I', str(cnt + 1))
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500313 for annotation in project.annotations:
314 setenv("REPO__%s" % (annotation.name), annotation.value)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900315
316 if mirror:
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500317 setenv('GIT_DIR', project.gitdir)
318 cwd = project.gitdir
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900319 else:
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500320 cwd = project.worktree
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900321
322 if not os.path.exists(cwd):
Mike Frysingerb4668542019-10-21 22:53:46 -0400323 # Allow the user to silently ignore missing checkouts so they can run on
324 # partial checkouts (good for infra recovery tools).
325 if opt.ignore_missing:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500326 return (0, '')
327
328 output = ''
Mike Frysingerdc1b59d2019-09-30 23:47:03 -0400329 if ((opt.project_header and opt.verbose)
David Pursehouseabdf7502020-02-12 14:58:39 +0900330 or not opt.project_header):
LaMont Jonescc879a92021-11-18 22:40:18 +0000331 output = 'skipping %s/' % project.RelPath(local=opt.this_manifest_only)
Mike Frysingerfbab6062021-02-16 13:51:44 -0500332 return (1, output)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900333
Mike Frysingerfbab6062021-02-16 13:51:44 -0500334 if opt.verbose:
335 stderr = subprocess.STDOUT
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900336 else:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500337 stderr = subprocess.DEVNULL
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900338
Mike Frysingerd34af282021-03-18 13:54:34 -0400339 stdin = None if opt.interactive else subprocess.DEVNULL
340
Mike Frysingerfbab6062021-02-16 13:51:44 -0500341 result = subprocess.run(
342 cmd, cwd=cwd, shell=shell, env=env, check=False,
343 encoding='utf-8', errors='replace',
Mike Frysingerd34af282021-03-18 13:54:34 -0400344 stdin=stdin, stdout=subprocess.PIPE, stderr=stderr)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900345
Mike Frysingerfbab6062021-02-16 13:51:44 -0500346 output = result.stdout
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900347 if opt.project_header:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500348 if output:
349 buf = io.StringIO()
350 out = ForallColoring(config)
351 out.redirect(buf)
352 if mirror:
Mike Frysinger13cb7f72021-03-01 02:06:10 -0500353 project_header_path = project.name
Mike Frysingerfbab6062021-02-16 13:51:44 -0500354 else:
LaMont Jonescc879a92021-11-18 22:40:18 +0000355 project_header_path = project.RelPath(local=opt.this_manifest_only)
Mike Frysingerfbab6062021-02-16 13:51:44 -0500356 out.project('project %s/' % project_header_path)
357 out.nl()
358 buf.write(output)
359 output = buf.getvalue()
360 return (result.returncode, output)