blob: a2ccb7b68ad4b291d66419c086b405795811b656 [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 Frysingerfbab6062021-02-16 13:51:44 -050016import io
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090017import multiprocessing
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import re
19import os
Colin Cross31a7be52015-05-13 00:04:36 -070020import signal
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070021import sys
22import subprocess
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070023
24from color import Coloring
Mike Frysinger15e807c2021-02-16 01:56:30 -050025from command import DEFAULT_LOCAL_JOBS, Command, MirrorSafeCommand, WORKER_BATCH_SIZE
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070026
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070027_CAN_COLOR = [
David Pursehouseabdf7502020-02-12 14:58:39 +090028 'branch',
29 'diff',
30 'grep',
31 'log',
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070032]
33
Takeshi Kanemotoa7694982014-04-14 17:36:57 +090034
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070035class ForallColoring(Coloring):
36 def __init__(self, config):
37 Coloring.__init__(self, config, 'forall')
38 self.project = self.printer('project', attr='bold')
39
40
Shawn O. Pearce44469462009-03-03 17:51:01 -080041class Forall(Command, MirrorSafeCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042 common = False
43 helpSummary = "Run a shell command in each project"
44 helpUsage = """
45%prog [<project>...] -c <command> [<arg>...]
Zhiguang Lia8864fb2013-03-15 10:32:10 +080046%prog -r str1 [str2] ... -c <command> [<arg>...]"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070047"""
48 helpDescription = """
49Executes the same shell command in each project.
50
Zhiguang Lia8864fb2013-03-15 10:32:10 +080051The -r option allows running the command only on projects matching
52regex or wildcard expression.
53
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040054# Output Formatting
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070055
56The -p option causes '%prog' to bind pipes to the command's stdin,
57stdout and stderr streams, and pipe all output into a continuous
58stream that is displayed in a single pager session. Project headings
59are inserted before the output of each command is displayed. If the
60command produces no output in a project, no heading is displayed.
61
62The formatting convention used by -p is very suitable for some
63types of searching, e.g. `repo forall -p -c git log -SFoo` will
64print all commits that add or remove references to Foo.
65
66The -v option causes '%prog' to display stderr messages if a
67command produces output only on stderr. Normally the -p option
68causes command output to be suppressed until the command produces
69at least one byte of output on stdout.
70
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040071# Environment
Shawn O. Pearceff84fea2009-04-13 12:11:59 -070072
Shawn O. Pearce44469462009-03-03 17:51:01 -080073pwd is the project's working directory. If the current client is
74a mirror client, then pwd is the Git repository.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070075
76REPO_PROJECT is set to the unique name of the project.
77
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050078REPO_PATH is the path relative the the root of the client.
79
80REPO_REMOTE is the name of the remote system from the manifest.
81
82REPO_LREV is the name of the revision from the manifest, translated
83to a local tracking branch. If you need to pass the manifest
84revision to a locally executed git command, use REPO_LREV.
85
86REPO_RREV is the name of the revision from the manifest, exactly
87as written in the manifest.
88
Mitchel Humpheryse81bc032014-03-31 11:36:56 -070089REPO_COUNT is the total number of projects being iterated.
90
91REPO_I is the current (1-based) iteration count. Can be used in
92conjunction with REPO_COUNT to add a simple progress indicator to your
93command.
94
James W. Mills24c13082012-04-12 15:04:13 -050095REPO__* are any extra environment variables, specified by the
96"annotation" element under any project element. This can be useful
97for differentiating trees based on user-specific criteria, or simply
98annotating tree details.
99
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700100shell positional arguments ($1, $2, .., $#) are set to any arguments
101following <command>.
102
David Pursehousef46902a2017-10-31 12:27:17 +0900103Example: to list projects:
104
Solomon Kinard490e1632019-07-08 15:09:55 -0700105 %prog -c 'echo $REPO_PROJECT'
David Pursehousef46902a2017-10-31 12:27:17 +0900106
107Notice that $REPO_PROJECT is quoted to ensure it is expanded in
108the context of running <command> instead of in the calling shell.
109
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700110Unless -p is used, stdin, stdout, stderr are inherited from the
111terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +0200112
113If -e is used, when a command exits unsuccessfully, '%prog' will abort
114without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700115"""
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500116 PARALLEL_JOBS = DEFAULT_LOCAL_JOBS
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700117
Mike Frysinger179a2422021-03-01 02:03:44 -0500118 @staticmethod
119 def _cmd_option(option, _opt_str, _value, parser):
120 setattr(parser.values, option.dest, list(parser.rargs))
121 while parser.rargs:
122 del parser.rargs[0]
123
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124 def _Options(self, p):
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500125 super()._Options(p)
126
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800127 p.add_option('-r', '--regex',
128 dest='regex', action='store_true',
129 help="Execute the command only on projects matching regex or wildcard expression")
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900130 p.add_option('-i', '--inverse-regex',
131 dest='inverse_regex', action='store_true',
David Pursehouse3cda50a2020-02-13 13:17:03 +0900132 help="Execute the command only on projects not matching regex or "
133 "wildcard expression")
Graham Christensen0369a062015-07-29 17:02:54 -0500134 p.add_option('-g', '--groups',
135 dest='groups',
136 help="Execute the command only on projects matching the specified groups")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137 p.add_option('-c', '--command',
138 help='Command (and arguments) to execute',
139 dest='command',
140 action='callback',
Mike Frysinger179a2422021-03-01 02:03:44 -0500141 callback=self._cmd_option)
Victor Boivie88b86722011-09-07 09:43:28 +0200142 p.add_option('-e', '--abort-on-errors',
143 dest='abort_on_errors', action='store_true',
144 help='Abort if a command exits unsuccessfully')
Mike Frysingerb4668542019-10-21 22:53:46 -0400145 p.add_option('--ignore-missing', action='store_true',
146 help='Silently skip & do not exit non-zero due missing '
147 'checkouts')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700148
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700149 g = p.add_option_group('Output')
150 g.add_option('-p',
151 dest='project_header', action='store_true',
152 help='Show project headers before output')
153 g.add_option('-v', '--verbose',
154 dest='verbose', action='store_true',
155 help='Show command error messages')
156
157 def WantPager(self, opt):
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900158 return opt.project_header and opt.jobs == 1
159
160 def _SerializeProject(self, project):
161 """ Serialize a project._GitGetByExec instance.
162
163 project._GitGetByExec is not pickle-able. Instead of trying to pass it
164 around between processes, make a dict ourselves containing only the
165 attributes that we need.
166
167 """
David Pursehouse30d13ee2015-05-07 15:01:15 +0900168 if not self.manifest.IsMirror:
169 lrev = project.GetRevisionId()
170 else:
171 lrev = None
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900172 return {
David Pursehouseabdf7502020-02-12 14:58:39 +0900173 'name': project.name,
174 'relpath': project.relpath,
175 'remote_name': project.remote.name,
176 'lrev': lrev,
177 'rrev': project.revisionExpr,
178 'annotations': dict((a.name, a.value) for a in project.annotations),
179 'gitdir': project.gitdir,
180 'worktree': project.worktree,
Sean McAllister74e8ed42020-04-15 12:24:43 -0600181 'upstream': project.upstream,
182 'dest_branch': project.dest_branch,
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900183 }
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700184
Mike Frysingerae6cb082019-08-27 01:10:59 -0400185 def ValidateOptions(self, opt, args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700186 if not opt.command:
187 self.Usage()
188
Mike Frysingerae6cb082019-08-27 01:10:59 -0400189 def Execute(self, opt, args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700190 cmd = [opt.command[0]]
191
192 shell = True
193 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
194 shell = False
195
196 if shell:
197 cmd.append(cmd[0])
198 cmd.extend(opt.command[1:])
199
David Pursehouse54a4e602020-02-12 14:31:05 +0900200 if opt.project_header \
David Pursehouseabdf7502020-02-12 14:58:39 +0900201 and not shell \
202 and cmd[0] == 'git':
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700203 # If this is a direct git command that can enable colorized
204 # output and the user prefers coloring, add --color into the
205 # command line because we are going to wrap the command into
206 # a pipe and git won't know coloring should activate.
207 #
208 for cn in cmd[1:]:
209 if not cn.startswith('-'):
210 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900211 else:
212 cn = None
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900213 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700214 class ColorCmd(Coloring):
215 def __init__(self, config, cmd):
216 Coloring.__init__(self, config, cmd)
217 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
218 cmd.insert(cmd.index(cn) + 1, '--color')
219
Shawn O. Pearce44469462009-03-03 17:51:01 -0800220 mirror = self.manifest.IsMirror
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700221 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700222
David Pursehouse6944cdb2015-05-07 14:39:44 +0900223 smart_sync_manifest_name = "smart_sync_override.xml"
224 smart_sync_manifest_path = os.path.join(
David Pursehouseabdf7502020-02-12 14:58:39 +0900225 self.manifest.manifestProject.worktree, smart_sync_manifest_name)
David Pursehouse6944cdb2015-05-07 14:39:44 +0900226
227 if os.path.isfile(smart_sync_manifest_path):
228 self.manifest.Override(smart_sync_manifest_path)
229
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900230 if opt.regex:
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800231 projects = self.FindProjects(args)
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900232 elif opt.inverse_regex:
233 projects = self.FindProjects(args, inverse=True)
234 else:
235 projects = self.GetProjects(args, groups=opt.groups)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800236
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700237 os.environ['REPO_COUNT'] = str(len(projects))
238
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900239 try:
240 config = self.manifest.manifestProject.config
Mike Frysinger15e807c2021-02-16 01:56:30 -0500241 with multiprocessing.Pool(opt.jobs, InitWorker) as pool:
242 results_it = pool.imap(
243 DoWorkWrapper,
244 self.ProjectArgs(projects, mirror, opt, cmd, shell, config),
245 chunksize=WORKER_BATCH_SIZE)
Mike Frysingerfbab6062021-02-16 13:51:44 -0500246 first = True
247 for (r, output) in results_it:
248 if output:
249 if first:
250 first = False
251 elif opt.project_header:
252 print()
253 # To simplify the DoWorkWrapper, take care of automatic newlines.
254 end = '\n'
255 if output[-1] == '\n':
256 end = ''
257 print(output, end=end)
Mike Frysinger15e807c2021-02-16 01:56:30 -0500258 rc = rc or r
259 if r != 0 and opt.abort_on_errors:
260 raise Exception('Aborting due to previous error')
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900261 except (KeyboardInterrupt, WorkerKeyboardInterrupt):
262 # Catch KeyboardInterrupt raised inside and outside of workers
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900263 rc = rc or errno.EINTR
264 except Exception as e:
265 # Catch any other exceptions raised
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200266 print('Got an error, terminating the pool: %s: %s' %
David Pursehouseabdf7502020-02-12 14:58:39 +0900267 (type(e).__name__, e),
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900268 file=sys.stderr)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900269 rc = rc or getattr(e, 'errno', 1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700270 if rc != 0:
271 sys.exit(rc)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900272
Colin Cross31a7be52015-05-13 00:04:36 -0700273 def ProjectArgs(self, projects, mirror, opt, cmd, shell, config):
274 for cnt, p in enumerate(projects):
275 try:
276 project = self._SerializeProject(p)
277 except Exception as e:
Alexandre Garnier4cfb6d72015-09-09 15:51:31 +0200278 print('Project list error on project %s: %s: %s' %
David Pursehouseabdf7502020-02-12 14:58:39 +0900279 (p.name, type(e).__name__, e),
Colin Cross31a7be52015-05-13 00:04:36 -0700280 file=sys.stderr)
281 return
282 except KeyboardInterrupt:
283 print('Project list interrupted',
284 file=sys.stderr)
285 return
286 yield [mirror, opt, cmd, shell, cnt, config, project]
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900287
David Pursehouse819827a2020-02-12 15:20:19 +0900288
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900289class WorkerKeyboardInterrupt(Exception):
290 """ Keyboard interrupt exception for worker processes. """
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900291
292
Colin Cross31a7be52015-05-13 00:04:36 -0700293def InitWorker():
294 signal.signal(signal.SIGINT, signal.SIG_IGN)
295
David Pursehouse819827a2020-02-12 15:20:19 +0900296
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900297def DoWorkWrapper(args):
298 """ A wrapper around the DoWork() method.
299
300 Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
301 ``Exception``-based exception to stop it flooding the console with stacktraces
302 and making the parent hang indefinitely.
303
304 """
305 project = args.pop()
306 try:
307 return DoWork(project, *args)
308 except KeyboardInterrupt:
309 print('%s: Worker interrupted' % project['name'])
310 raise WorkerKeyboardInterrupt()
311
312
313def DoWork(project, mirror, opt, cmd, shell, cnt, config):
314 env = os.environ.copy()
David Pursehouse819827a2020-02-12 15:20:19 +0900315
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900316 def setenv(name, val):
317 if val is None:
318 val = ''
Anthony Kingc116f942015-06-03 17:29:29 +0100319 env[name] = val
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900320
321 setenv('REPO_PROJECT', project['name'])
322 setenv('REPO_PATH', project['relpath'])
323 setenv('REPO_REMOTE', project['remote_name'])
324 setenv('REPO_LREV', project['lrev'])
325 setenv('REPO_RREV', project['rrev'])
Sean McAllister74e8ed42020-04-15 12:24:43 -0600326 setenv('REPO_UPSTREAM', project['upstream'])
327 setenv('REPO_DEST_BRANCH', project['dest_branch'])
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900328 setenv('REPO_I', str(cnt + 1))
329 for name in project['annotations']:
330 setenv("REPO__%s" % (name), project['annotations'][name])
331
332 if mirror:
333 setenv('GIT_DIR', project['gitdir'])
334 cwd = project['gitdir']
335 else:
336 cwd = project['worktree']
337
338 if not os.path.exists(cwd):
Mike Frysingerb4668542019-10-21 22:53:46 -0400339 # Allow the user to silently ignore missing checkouts so they can run on
340 # partial checkouts (good for infra recovery tools).
341 if opt.ignore_missing:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500342 return (0, '')
343
344 output = ''
Mike Frysingerdc1b59d2019-09-30 23:47:03 -0400345 if ((opt.project_header and opt.verbose)
David Pursehouseabdf7502020-02-12 14:58:39 +0900346 or not opt.project_header):
Mike Frysingerfbab6062021-02-16 13:51:44 -0500347 output = 'skipping %s/' % project['relpath']
348 return (1, output)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900349
Mike Frysingerfbab6062021-02-16 13:51:44 -0500350 if opt.verbose:
351 stderr = subprocess.STDOUT
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900352 else:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500353 stderr = subprocess.DEVNULL
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900354
Mike Frysingerfbab6062021-02-16 13:51:44 -0500355 result = subprocess.run(
356 cmd, cwd=cwd, shell=shell, env=env, check=False,
357 encoding='utf-8', errors='replace',
358 stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=stderr)
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900359
Mike Frysingerfbab6062021-02-16 13:51:44 -0500360 output = result.stdout
Takeshi Kanemotoa7694982014-04-14 17:36:57 +0900361 if opt.project_header:
Mike Frysingerfbab6062021-02-16 13:51:44 -0500362 if output:
363 buf = io.StringIO()
364 out = ForallColoring(config)
365 out.redirect(buf)
366 if mirror:
367 project_header_path = project['name']
368 else:
369 project_header_path = project['relpath']
370 out.project('project %s/' % project_header_path)
371 out.nl()
372 buf.write(output)
373 output = buf.getvalue()
374 return (result.returncode, output)