blob: 49e725c2afb1c649fe31e0c167e5cc3c5ea59803 [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.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070096"""
97
98 def _Options(self, p):
99 def cmd(option, opt_str, value, parser):
100 setattr(parser.values, option.dest, list(parser.rargs))
101 while parser.rargs:
102 del parser.rargs[0]
103 p.add_option('-c', '--command',
104 help='Command (and arguments) to execute',
105 dest='command',
106 action='callback',
107 callback=cmd)
108
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700109 g = p.add_option_group('Output')
110 g.add_option('-p',
111 dest='project_header', action='store_true',
112 help='Show project headers before output')
113 g.add_option('-v', '--verbose',
114 dest='verbose', action='store_true',
115 help='Show command error messages')
116
117 def WantPager(self, opt):
118 return opt.project_header
119
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700120 def Execute(self, opt, args):
121 if not opt.command:
122 self.Usage()
123
124 cmd = [opt.command[0]]
125
126 shell = True
127 if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
128 shell = False
129
130 if shell:
131 cmd.append(cmd[0])
132 cmd.extend(opt.command[1:])
133
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700134 if opt.project_header \
135 and not shell \
136 and cmd[0] == 'git':
137 # If this is a direct git command that can enable colorized
138 # output and the user prefers coloring, add --color into the
139 # command line because we are going to wrap the command into
140 # a pipe and git won't know coloring should activate.
141 #
142 for cn in cmd[1:]:
143 if not cn.startswith('-'):
144 break
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900145 else:
146 cn = None
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900147 # pylint: disable=W0631
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900148 if cn and cn in _CAN_COLOR:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700149 class ColorCmd(Coloring):
150 def __init__(self, config, cmd):
151 Coloring.__init__(self, config, cmd)
152 if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
153 cmd.insert(cmd.index(cn) + 1, '--color')
David Pursehouse4f7bdea2012-10-22 12:50:15 +0900154 # pylint: enable=W0631
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700155
Shawn O. Pearce44469462009-03-03 17:51:01 -0800156 mirror = self.manifest.IsMirror
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700157 out = ForallColoring(self.manifest.manifestProject.config)
Wink Savilleef9ce1d2009-04-21 10:00:16 -0700158 out.redirect(sys.stdout)
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700159
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160 rc = 0
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700161 first = True
162
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700163 for project in self.GetProjects(args):
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800164 env = os.environ.copy()
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700165 def setenv(name, val):
166 if val is None:
167 val = ''
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800168 env[name] = val.encode()
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700169
170 setenv('REPO_PROJECT', project.name)
171 setenv('REPO_PATH', project.relpath)
172 setenv('REPO_REMOTE', project.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700173 setenv('REPO_LREV', project.GetRevisionId())
174 setenv('REPO_RREV', project.revisionExpr)
James W. Mills24c13082012-04-12 15:04:13 -0500175 for a in project.annotations:
176 setenv("REPO__%s" % (a.name), a.value)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700177
Shawn O. Pearce44469462009-03-03 17:51:01 -0800178 if mirror:
Shawn O. Pearce1775dbe2009-03-17 08:03:04 -0700179 setenv('GIT_DIR', project.gitdir)
Shawn O. Pearce44469462009-03-03 17:51:01 -0800180 cwd = project.gitdir
181 else:
182 cwd = project.worktree
183
Shawn O. Pearce1b5a4a02009-08-22 18:50:45 -0700184 if not os.path.exists(cwd):
185 if (opt.project_header and opt.verbose) \
186 or not opt.project_header:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700187 print('skipping %s/' % project.relpath, file=sys.stderr)
Shawn O. Pearce1b5a4a02009-08-22 18:50:45 -0700188 continue
189
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700190 if opt.project_header:
191 stdin = subprocess.PIPE
192 stdout = subprocess.PIPE
193 stderr = subprocess.PIPE
194 else:
195 stdin = None
196 stdout = None
197 stderr = None
198
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700199 p = subprocess.Popen(cmd,
Shawn O. Pearce44469462009-03-03 17:51:01 -0800200 cwd = cwd,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201 shell = shell,
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700202 env = env,
203 stdin = stdin,
204 stdout = stdout,
205 stderr = stderr)
206
207 if opt.project_header:
208 class sfd(object):
209 def __init__(self, fd, dest):
210 self.fd = fd
211 self.dest = dest
212 def fileno(self):
213 return self.fd.fileno()
214
215 empty = True
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700216 errbuf = ''
217
218 p.stdin.close()
219 s_in = [sfd(p.stdout, sys.stdout),
220 sfd(p.stderr, sys.stderr)]
221
222 for s in s_in:
223 flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
224 fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
225
226 while s_in:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900227 in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700228 for s in in_ready:
229 buf = s.fd.read(4096)
230 if not buf:
231 s.fd.close()
232 s_in.remove(s)
233 continue
234
235 if not opt.verbose:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900236 if s.fd != p.stdout:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700237 errbuf += buf
238 continue
239
240 if empty:
241 if first:
242 first = False
243 else:
244 out.nl()
245 out.project('project %s/', project.relpath)
246 out.nl()
247 out.flush()
248 if errbuf:
249 sys.stderr.write(errbuf)
250 sys.stderr.flush()
251 errbuf = ''
252 empty = False
253
254 s.dest.write(buf)
255 s.dest.flush()
256
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700257 r = p.wait()
258 if r != 0 and r != rc:
259 rc = r
260 if rc != 0:
261 sys.exit(rc)