blob: 4c1c9ff8294c0d74dcc43cb1bda0151e1f127f9c [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>...]
45"""
46 helpDescription = """
47Executes the same shell command in each project.
48
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070049Output Formatting
50-----------------
51
52The -p option causes '%prog' to bind pipes to the command's stdin,
53stdout and stderr streams, and pipe all output into a continuous
54stream that is displayed in a single pager session. Project headings
55are inserted before the output of each command is displayed. If the
56command produces no output in a project, no heading is displayed.
57
58The formatting convention used by -p is very suitable for some
59types of searching, e.g. `repo forall -p -c git log -SFoo` will
60print all commits that add or remove references to Foo.
61
62The -v option causes '%prog' to display stderr messages if a
63command produces output only on stderr. Normally the -p option
64causes command output to be suppressed until the command produces
65at least one byte of output on stdout.
66
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070067Environment
68-----------
Shawn O. Pearceff84fea2009-04-13 12:11:59 -070069
Shawn O. Pearce44469462009-03-03 17:51:01 -080070pwd is the project's working directory. If the current client is
71a mirror client, then pwd is the Git repository.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070072
73REPO_PROJECT is set to the unique name of the project.
74
Jeff Baileybe0e8ac2009-01-21 19:05:15 -050075REPO_PATH is the path relative the the root of the client.
76
77REPO_REMOTE is the name of the remote system from the manifest.
78
79REPO_LREV is the name of the revision from the manifest, translated
80to a local tracking branch. If you need to pass the manifest
81revision to a locally executed git command, use REPO_LREV.
82
83REPO_RREV is the name of the revision from the manifest, exactly
84as written in the manifest.
85
James W. Mills24c13082012-04-12 15:04:13 -050086REPO__* are any extra environment variables, specified by the
87"annotation" element under any project element. This can be useful
88for differentiating trees based on user-specific criteria, or simply
89annotating tree details.
90
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070091shell positional arguments ($1, $2, .., $#) are set to any arguments
92following <command>.
93
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070094Unless -p is used, stdin, stdout, stderr are inherited from the
95terminal and are not redirected.
Victor Boivie88b86722011-09-07 09:43:28 +020096
97If -e is used, when a command exits unsuccessfully, '%prog' will abort
98without iterating through the remaining projects.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070099"""
100
101 def _Options(self, p):
102 def cmd(option, opt_str, value, parser):
103 setattr(parser.values, option.dest, list(parser.rargs))
104 while parser.rargs:
105 del parser.rargs[0]
106 p.add_option('-c', '--command',
107 help='Command (and arguments) to execute',
108 dest='command',
109 action='callback',
110 callback=cmd)
Victor Boivie88b86722011-09-07 09:43:28 +0200111 p.add_option('-e', '--abort-on-errors',
112 dest='abort_on_errors', action='store_true',
113 help='Abort if a command exits unsuccessfully')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700115 g = p.add_option_group('Output')
116 g.add_option('-p',
117 dest='project_header', action='store_true',
118 help='Show project headers before output')
119 g.add_option('-v', '--verbose',
120 dest='verbose', action='store_true',
121 help='Show command error messages')
122
123 def WantPager(self, opt):
124 return opt.project_header
125
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126 def Execute(self, opt, args):
127 if not opt.command:
128 self.Usage()
129
130 cmd = [opt.command[0]]
131
132 shell = True
133 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
134 shell = False
135
136 if shell:
137 cmd.append(cmd[0])
138 cmd.extend(opt.command[1:])
139
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700140 if opt.project_header \
141 and not shell \
142 and cmd[0] == 'git':
143 # If this is a direct git command that can enable colorized
144 # output and the user prefers coloring, add --color into the
145 # command line because we are going to wrap the command into
146 # a pipe and git won't know coloring should activate.
147 #
148 for cn in cmd[1:]:
149 if not cn.startswith('-'):
150 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900151 else:
152 cn = None
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900153 # pylint: disable=W0631
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900154 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700155 class ColorCmd(Coloring):
156 def __init__(self, config, cmd):
157 Coloring.__init__(self, config, cmd)
158 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
159 cmd.insert(cmd.index(cn) + 1, '--color')
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900160 # pylint: enable=W0631
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700161
Shawn O. Pearce44469462009-03-03 17:51:01 -0800162 mirror = self.manifest.IsMirror
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700163 out = ForallColoring(self.manifest.manifestProject.config)
Wink Savilleef9ce1d2009-04-21 10:00:16 -0700164 out.redirect(sys.stdout)
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700165
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700166 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700167 first = True
168
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700169 for project in self.GetProjects(args):
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800170 env = os.environ.copy()
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700171 def setenv(name, val):
172 if val is None:
173 val = ''
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800174 env[name] = val.encode()
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700175
176 setenv('REPO_PROJECT', project.name)
177 setenv('REPO_PATH', project.relpath)
178 setenv('REPO_REMOTE', project.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700179 setenv('REPO_LREV', project.GetRevisionId())
180 setenv('REPO_RREV', project.revisionExpr)
James W. Mills24c13082012-04-12 15:04:13 -0500181 for a in project.annotations:
182 setenv("REPO__%s" % (a.name), a.value)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700183
Shawn O. Pearce44469462009-03-03 17:51:01 -0800184 if mirror:
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700185 setenv('GIT_DIR', project.gitdir)
Shawn O. Pearce44469462009-03-03 17:51:01 -0800186 cwd = project.gitdir
187 else:
188 cwd = project.worktree
189
Shawn O. Pearce1b5a4a02009-08-22 18:50:45 -0700190 if not os.path.exists(cwd):
191 if (opt.project_header and opt.verbose) \
192 or not opt.project_header:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700193 print('skipping %s/' % project.relpath, file=sys.stderr)
Shawn O. Pearce1b5a4a02009-08-22 18:50:45 -0700194 continue
195
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700196 if opt.project_header:
197 stdin = subprocess.PIPE
198 stdout = subprocess.PIPE
199 stderr = subprocess.PIPE
200 else:
201 stdin = None
202 stdout = None
203 stderr = None
204
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700205 p = subprocess.Popen(cmd,
Shawn O. Pearce44469462009-03-03 17:51:01 -0800206 cwd = cwd,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700207 shell = shell,
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700208 env = env,
209 stdin = stdin,
210 stdout = stdout,
211 stderr = stderr)
212
213 if opt.project_header:
214 class sfd(object):
215 def __init__(self, fd, dest):
216 self.fd = fd
217 self.dest = dest
218 def fileno(self):
219 return self.fd.fileno()
220
221 empty = True
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700222 errbuf = ''
223
224 p.stdin.close()
225 s_in = [sfd(p.stdout, sys.stdout),
226 sfd(p.stderr, sys.stderr)]
227
228 for s in s_in:
229 flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
230 fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
231
232 while s_in:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900233 in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700234 for s in in_ready:
235 buf = s.fd.read(4096)
236 if not buf:
237 s.fd.close()
238 s_in.remove(s)
239 continue
240
241 if not opt.verbose:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900242 if s.fd != p.stdout:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700243 errbuf += buf
244 continue
245
246 if empty:
247 if first:
248 first = False
249 else:
250 out.nl()
251 out.project('project %s/', project.relpath)
252 out.nl()
253 out.flush()
254 if errbuf:
255 sys.stderr.write(errbuf)
256 sys.stderr.flush()
257 errbuf = ''
258 empty = False
259
260 s.dest.write(buf)
261 s.dest.flush()
262
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700263 r = p.wait()
Victor Boivie88b86722011-09-07 09:43:28 +0200264 if r != 0:
265 if r != rc:
266 rc = r
267 if opt.abort_on_errors:
268 print("error: %s: Aborting due to previous error" % project.relpath,
269 file=sys.stderr)
270 sys.exit(r)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700271 if rc != 0:
272 sys.exit(rc)