blob: 24fec5ce0ba6b95e6c0fe3511c072f0563672eb0 [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
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070028_CAN_COLOR = [
David Pursehouseabdf7502020-02-12 14:58:39 +090029 'branch',
30 'diff',
31 'grep',
32 'log',
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070033]
34
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090035
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070036class ForallColoring(Coloring):
37 def __init__(self, config):
38 Coloring.__init__(self, config, 'forall')
39 self.project = self.printer('project', attr='bold')
40
41
Shawn O. Pearce44469462009-03-03 17:51:01 -080042class Forall(Command, MirrorSafeCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070043 common = False
44 helpSummary = "Run a shell command in each project"
45 helpUsage = """
46%prog [<project>...] -c <command> [<arg>...]
Zhiguang Lia8864fb2013-03-15 10:32:10 +080047%prog -r str1 [str2] ... -c <command> [<arg>...]"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070048"""
49 helpDescription = """
50Executes the same shell command in each project.
51
Zhiguang Lia8864fb2013-03-15 10:32:10 +080052The -r option allows running the command only on projects matching
53regex or wildcard expression.
54
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040055# Output Formatting
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070056
57The -p option causes '%prog' to bind pipes to the command's stdin,
58stdout and stderr streams, and pipe all output into a continuous
59stream that is displayed in a single pager session. Project headings
60are inserted before the output of each command is displayed. If the
61command produces no output in a project, no heading is displayed.
62
63The formatting convention used by -p is very suitable for some
64types of searching, e.g. `repo forall -p -c git log -SFoo` will
65print all commits that add or remove references to Foo.
66
67The -v option causes '%prog' to display stderr messages if a
68command produces output only on stderr. Normally the -p option
69causes command output to be suppressed until the command produces
70at least one byte of output on stdout.
71
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040072# Environment
Shawn O. Pearceff84fea2009-04-13 12:11:59 -070073
Shawn O. Pearce44469462009-03-03 17:51:01 -080074pwd is the project's working directory. If the current client is
75a mirror client, then pwd is the Git repository.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070076
77REPO_PROJECT is set to the unique name of the project.
78
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050079REPO_PATH is the path relative the the root of the client.
80
81REPO_REMOTE is the name of the remote system from the manifest.
82
83REPO_LREV is the name of the revision from the manifest, translated
84to a local tracking branch. If you need to pass the manifest
85revision to a locally executed git command, use REPO_LREV.
86
87REPO_RREV is the name of the revision from the manifest, exactly
88as written in the manifest.
89
Mitchel Humpheryse81bc032014-03-31 11:36:56 -070090REPO_COUNT is the total number of projects being iterated.
91
92REPO_I is the current (1-based) iteration count. Can be used in
93conjunction with REPO_COUNT to add a simple progress indicator to your
94command.
95
James W. Mills24c13082012-04-12 15:04:13 -050096REPO__* are any extra environment variables, specified by the
97"annotation" element under any project element. This can be useful
98for differentiating trees based on user-specific criteria, or simply
99annotating tree details.
100
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700101shell positional arguments ($1, $2, .., $#) are set to any arguments
102following <command>.
103
David Pursehousef46902a2017-10-31 12:27:17 +0900104Example: to list projects:
105
Solomon Kinard490e1632019-07-08 15:09:55 -0700106 %prog -c 'echo $REPO_PROJECT'
David Pursehousef46902a2017-10-31 12:27:17 +0900107
108Notice that $REPO_PROJECT is quoted to ensure it is expanded in
109the context of running <command> instead of in the calling shell.
110
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700111Unless -p is used, stdin, stdout, stderr are inherited from the
112terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +0200113
114If -e is used, when a command exits unsuccessfully, '%prog' will abort
115without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116"""
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500117 PARALLEL_JOBS = DEFAULT_LOCAL_JOBS
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118
Mike Frysinger179a2422021-03-01 02:03:44 -0500119 @staticmethod
120 def _cmd_option(option, _opt_str, _value, parser):
121 setattr(parser.values, option.dest, list(parser.rargs))
122 while parser.rargs:
123 del parser.rargs[0]
124
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125 def _Options(self, p):
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500126 super()._Options(p)
127
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800128 p.add_option('-r', '--regex',
129 dest='regex', action='store_true',
130 help="Execute the command only on projects matching regex or wildcard expression")
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900131 p.add_option('-i', '--inverse-regex',
132 dest='inverse_regex', action='store_true',
David Pursehouse3cda50a2020-02-13 13:17:03 +0900133 help="Execute the command only on projects not matching regex or "
134 "wildcard expression")
Graham Christensen0369a062015-07-29 17:02:54 -0500135 p.add_option('-g', '--groups',
136 dest='groups',
137 help="Execute the command only on projects matching the specified groups")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700138 p.add_option('-c', '--command',
139 help='Command (and arguments) to execute',
140 dest='command',
141 action='callback',
Mike Frysinger179a2422021-03-01 02:03:44 -0500142 callback=self._cmd_option)
Victor Boivie88b86722011-09-07 09:43:28 +0200143 p.add_option('-e', '--abort-on-errors',
144 dest='abort_on_errors', action='store_true',
145 help='Abort if a command exits unsuccessfully')
Mike Frysingerb4668542019-10-21 22:53:46 -0400146 p.add_option('--ignore-missing', action='store_true',
147 help='Silently skip & do not exit non-zero due missing '
148 'checkouts')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700149
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700150 g = p.add_option_group('Output')
151 g.add_option('-p',
152 dest='project_header', action='store_true',
153 help='Show project headers before output')
154 g.add_option('-v', '--verbose',
155 dest='verbose', action='store_true',
156 help='Show command error messages')
157
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
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900240 try:
241 config = self.manifest.manifestProject.config
Mike Frysinger15e807c2021-02-16 01:56:30 -0500242 with multiprocessing.Pool(opt.jobs, InitWorker) as pool:
243 results_it = pool.imap(
Mike Frysinger819c7392021-03-01 02:06:10 -0500244 functools.partial(DoWorkWrapper, mirror, opt, cmd, shell, config),
245 enumerate(self._SerializeProject(x) for x in projects),
Mike Frysinger15e807c2021-02-16 01:56:30 -0500246 chunksize=WORKER_BATCH_SIZE)
Mike Frysingerfbab6062021-02-16 13:51:44 -0500247 first = True
248 for (r, output) in results_it:
249 if output:
250 if first:
251 first = False
252 elif opt.project_header:
253 print()
254 # To simplify the DoWorkWrapper, take care of automatic newlines.
255 end = '\n'
256 if output[-1] == '\n':
257 end = ''
258 print(output, end=end)
Mike Frysinger15e807c2021-02-16 01:56:30 -0500259 rc = rc or r
260 if r != 0 and opt.abort_on_errors:
261 raise Exception('Aborting due to previous error')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900262 except (KeyboardInterrupt, WorkerKeyboardInterrupt):
263 # Catch KeyboardInterrupt raised inside and outside of workers
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900264 rc = rc or errno.EINTR
265 except Exception as e:
266 # Catch any other exceptions raised
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200267 print('Got an error, terminating the pool: %s: %s' %
David Pursehouseabdf7502020-02-12 14:58:39 +0900268 (type(e).__name__, e),
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900269 file=sys.stderr)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900270 rc = rc or getattr(e, 'errno', 1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700271 if rc != 0:
272 sys.exit(rc)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900273
David Pursehouse819827a2020-02-12 15:20:19 +0900274
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900275class WorkerKeyboardInterrupt(Exception):
276 """ Keyboard interrupt exception for worker processes. """
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900277
278
Colin Cross31a7be52015-05-13 00:04:36 -0700279def InitWorker():
280 signal.signal(signal.SIGINT, signal.SIG_IGN)
281
David Pursehouse819827a2020-02-12 15:20:19 +0900282
Mike Frysinger819c7392021-03-01 02:06:10 -0500283def DoWorkWrapper(mirror, opt, cmd, shell, config, args):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900284 """ A wrapper around the DoWork() method.
285
286 Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
287 ``Exception``-based exception to stop it flooding the console with stacktraces
288 and making the parent hang indefinitely.
289
290 """
Mike Frysinger819c7392021-03-01 02:06:10 -0500291 cnt, project = args
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900292 try:
Mike Frysinger819c7392021-03-01 02:06:10 -0500293 return DoWork(project, mirror, opt, cmd, shell, cnt, config)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900294 except KeyboardInterrupt:
295 print('%s: Worker interrupted' % project['name'])
296 raise WorkerKeyboardInterrupt()
297
298
299def DoWork(project, mirror, opt, cmd, shell, cnt, config):
300 env = os.environ.copy()
David Pursehouse819827a2020-02-12 15:20:19 +0900301
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900302 def setenv(name, val):
303 if val is None:
304 val = ''
Anthony Kingc116f942015-06-03 17:29:29 +0100305 env[name] = val
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900306
307 setenv('REPO_PROJECT', project['name'])
308 setenv('REPO_PATH', project['relpath'])
309 setenv('REPO_REMOTE', project['remote_name'])
310 setenv('REPO_LREV', project['lrev'])
311 setenv('REPO_RREV', project['rrev'])
Sean McAllister74e8ed42020-04-15 12:24:43 -0600312 setenv('REPO_UPSTREAM', project['upstream'])
313 setenv('REPO_DEST_BRANCH', project['dest_branch'])
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900314 setenv('REPO_I', str(cnt + 1))
315 for name in project['annotations']:
316 setenv("REPO__%s" % (name), project['annotations'][name])
317
318 if mirror:
319 setenv('GIT_DIR', project['gitdir'])
320 cwd = project['gitdir']
321 else:
322 cwd = project['worktree']
323
324 if not os.path.exists(cwd):
Mike Frysingerb4668542019-10-21 22:53:46 -0400325 # Allow the user to silently ignore missing checkouts so they can run on
326 # partial checkouts (good for infra recovery tools).
327 if opt.ignore_missing:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500328 return (0, '')
329
330 output = ''
Mike Frysingerdc1b59d2019-09-30 23:47:03 -0400331 if ((opt.project_header and opt.verbose)
David Pursehouseabdf7502020-02-12 14:58:39 +0900332 or not opt.project_header):
Mike Frysingerfbab6062021-02-16 13:51:44 -0500333 output = 'skipping %s/' % project['relpath']
334 return (1, output)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900335
Mike Frysingerfbab6062021-02-16 13:51:44 -0500336 if opt.verbose:
337 stderr = subprocess.STDOUT
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900338 else:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500339 stderr = subprocess.DEVNULL
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900340
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',
344 stdin=subprocess.DEVNULL, 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:
353 project_header_path = project['name']
354 else:
355 project_header_path = project['relpath']
356 out.project('project %s/' % project_header_path)
357 out.nl()
358 buf.write(output)
359 output = buf.getvalue()
360 return (result.returncode, output)