blob: 03ebcb21d73217793e0e73cef5c61c9a64c850e6 [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
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070017import fcntl
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import re
19import os
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070020import select
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
Shawn O. Pearce44469462009-03-03 17:51:01 -080025from command import Command, MirrorSafeCommand
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070026
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070027_CAN_COLOR = [
28 'branch',
29 'diff',
30 'grep',
31 'log',
32]
33
34class ForallColoring(Coloring):
35 def __init__(self, config):
36 Coloring.__init__(self, config, 'forall')
37 self.project = self.printer('project', attr='bold')
38
39
Shawn O. Pearce44469462009-03-03 17:51:01 -080040class Forall(Command, MirrorSafeCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070041 common = False
42 helpSummary = "Run a shell command in each project"
43 helpUsage = """
44%prog [<project>...] -c <command> [<arg>...]
Zhiguang Lia8864fb2013-03-15 10:32:10 +080045%prog -r str1 [str2] ... -c <command> [<arg>...]"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070046"""
47 helpDescription = """
48Executes the same shell command in each project.
49
Zhiguang Lia8864fb2013-03-15 10:32:10 +080050The -r option allows running the command only on projects matching
51regex or wildcard expression.
52
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070053Output Formatting
54-----------------
55
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
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070071Environment
72-----------
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
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700104Unless -p is used, stdin, stdout, stderr are inherited from the
105terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +0200106
107If -e is used, when a command exits unsuccessfully, '%prog' will abort
108without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700109"""
110
111 def _Options(self, p):
112 def cmd(option, opt_str, value, parser):
113 setattr(parser.values, option.dest, list(parser.rargs))
114 while parser.rargs:
115 del parser.rargs[0]
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800116 p.add_option('-r', '--regex',
117 dest='regex', action='store_true',
118 help="Execute the command only on projects matching regex or wildcard expression")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700119 p.add_option('-c', '--command',
120 help='Command (and arguments) to execute',
121 dest='command',
122 action='callback',
123 callback=cmd)
Victor Boivie88b86722011-09-07 09:43:28 +0200124 p.add_option('-e', '--abort-on-errors',
125 dest='abort_on_errors', action='store_true',
126 help='Abort if a command exits unsuccessfully')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700127
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700128 g = p.add_option_group('Output')
129 g.add_option('-p',
130 dest='project_header', action='store_true',
131 help='Show project headers before output')
132 g.add_option('-v', '--verbose',
133 dest='verbose', action='store_true',
134 help='Show command error messages')
135
136 def WantPager(self, opt):
137 return opt.project_header
138
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139 def Execute(self, opt, args):
140 if not opt.command:
141 self.Usage()
142
143 cmd = [opt.command[0]]
144
145 shell = True
146 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
147 shell = False
148
149 if shell:
150 cmd.append(cmd[0])
151 cmd.extend(opt.command[1:])
152
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700153 if opt.project_header \
154 and not shell \
155 and cmd[0] == 'git':
156 # If this is a direct git command that can enable colorized
157 # output and the user prefers coloring, add --color into the
158 # command line because we are going to wrap the command into
159 # a pipe and git won't know coloring should activate.
160 #
161 for cn in cmd[1:]:
162 if not cn.startswith('-'):
163 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900164 else:
165 cn = None
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900166 # pylint: disable=W0631
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900167 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700168 class ColorCmd(Coloring):
169 def __init__(self, config, cmd):
170 Coloring.__init__(self, config, cmd)
171 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
172 cmd.insert(cmd.index(cn) + 1, '--color')
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900173 # pylint: enable=W0631
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700174
Shawn O. Pearce44469462009-03-03 17:51:01 -0800175 mirror = self.manifest.IsMirror
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700176 out = ForallColoring(self.manifest.manifestProject.config)
Wink Savilleef9ce1d2009-04-21 10:00:16 -0700177 out.redirect(sys.stdout)
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700178
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700179 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700180 first = True
181
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800182 if not opt.regex:
183 projects = self.GetProjects(args)
184 else:
185 projects = self.FindProjects(args)
186
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700187 os.environ['REPO_COUNT'] = str(len(projects))
188
189 for (cnt, project) in enumerate(projects):
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800190 env = os.environ.copy()
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700191 def setenv(name, val):
192 if val is None:
193 val = ''
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800194 env[name] = val.encode()
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700195
196 setenv('REPO_PROJECT', project.name)
197 setenv('REPO_PATH', project.relpath)
198 setenv('REPO_REMOTE', project.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700199 setenv('REPO_LREV', project.GetRevisionId())
200 setenv('REPO_RREV', project.revisionExpr)
Mitchel Humpheryse81bc032014-03-31 11:36:56 -0700201 setenv('REPO_I', str(cnt + 1))
James W. Mills24c13082012-04-12 15:04:13 -0500202 for a in project.annotations:
203 setenv("REPO__%s" % (a.name), a.value)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700204
Shawn O. Pearce44469462009-03-03 17:51:01 -0800205 if mirror:
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700206 setenv('GIT_DIR', project.gitdir)
Shawn O. Pearce44469462009-03-03 17:51:01 -0800207 cwd = project.gitdir
208 else:
209 cwd = project.worktree
210
Shawn O. Pearce1b5a4a02009-08-22 18:50:45 -0700211 if not os.path.exists(cwd):
212 if (opt.project_header and opt.verbose) \
213 or not opt.project_header:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700214 print('skipping %s/' % project.relpath, file=sys.stderr)
Shawn O. Pearce1b5a4a02009-08-22 18:50:45 -0700215 continue
216
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700217 if opt.project_header:
218 stdin = subprocess.PIPE
219 stdout = subprocess.PIPE
220 stderr = subprocess.PIPE
221 else:
222 stdin = None
223 stdout = None
224 stderr = None
225
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700226 p = subprocess.Popen(cmd,
Shawn O. Pearce44469462009-03-03 17:51:01 -0800227 cwd = cwd,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700228 shell = shell,
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700229 env = env,
230 stdin = stdin,
231 stdout = stdout,
232 stderr = stderr)
233
234 if opt.project_header:
235 class sfd(object):
236 def __init__(self, fd, dest):
237 self.fd = fd
238 self.dest = dest
239 def fileno(self):
240 return self.fd.fileno()
241
242 empty = True
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700243 errbuf = ''
244
245 p.stdin.close()
246 s_in = [sfd(p.stdout, sys.stdout),
247 sfd(p.stderr, sys.stderr)]
248
249 for s in s_in:
250 flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
251 fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
252
253 while s_in:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900254 in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700255 for s in in_ready:
256 buf = s.fd.read(4096)
257 if not buf:
258 s.fd.close()
259 s_in.remove(s)
260 continue
261
262 if not opt.verbose:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900263 if s.fd != p.stdout:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700264 errbuf += buf
265 continue
266
267 if empty:
268 if first:
269 first = False
270 else:
271 out.nl()
Jorge Gonzalez5bca9fc2013-06-03 12:00:06 -0700272
273 if mirror:
274 project_header_path = project.name
275 else:
276 project_header_path = project.relpath
277 out.project('project %s/', project_header_path)
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700278 out.nl()
279 out.flush()
280 if errbuf:
281 sys.stderr.write(errbuf)
282 sys.stderr.flush()
283 errbuf = ''
284 empty = False
285
286 s.dest.write(buf)
287 s.dest.flush()
288
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700289 r = p.wait()
Victor Boivie88b86722011-09-07 09:43:28 +0200290 if r != 0:
291 if r != rc:
292 rc = r
293 if opt.abort_on_errors:
294 print("error: %s: Aborting due to previous error" % project.relpath,
295 file=sys.stderr)
296 sys.exit(r)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700297 if rc != 0:
298 sys.exit(rc)