The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1 | # |
| 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 Owens | cecd1d8 | 2012-11-01 22:59:27 -0700 | [diff] [blame] | 16 | from __future__ import print_function |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 17 | import errno |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 18 | import fcntl |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 19 | import multiprocessing |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 20 | import re |
| 21 | import os |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 22 | import select |
Colin Cross | 31a7be5 | 2015-05-13 00:04:36 -0700 | [diff] [blame] | 23 | import signal |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 24 | import sys |
| 25 | import subprocess |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 26 | |
| 27 | from color import Coloring |
Shawn O. Pearce | 4446946 | 2009-03-03 17:51:01 -0800 | [diff] [blame] | 28 | from command import Command, MirrorSafeCommand |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 29 | |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 30 | _CAN_COLOR = [ |
| 31 | 'branch', |
| 32 | 'diff', |
| 33 | 'grep', |
| 34 | 'log', |
| 35 | ] |
| 36 | |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 37 | |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 38 | class ForallColoring(Coloring): |
| 39 | def __init__(self, config): |
| 40 | Coloring.__init__(self, config, 'forall') |
| 41 | self.project = self.printer('project', attr='bold') |
| 42 | |
| 43 | |
Shawn O. Pearce | 4446946 | 2009-03-03 17:51:01 -0800 | [diff] [blame] | 44 | class Forall(Command, MirrorSafeCommand): |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 45 | common = False |
| 46 | helpSummary = "Run a shell command in each project" |
| 47 | helpUsage = """ |
| 48 | %prog [<project>...] -c <command> [<arg>...] |
Zhiguang Li | a8864fb | 2013-03-15 10:32:10 +0800 | [diff] [blame] | 49 | %prog -r str1 [str2] ... -c <command> [<arg>...]" |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 50 | """ |
| 51 | helpDescription = """ |
| 52 | Executes the same shell command in each project. |
| 53 | |
Zhiguang Li | a8864fb | 2013-03-15 10:32:10 +0800 | [diff] [blame] | 54 | The -r option allows running the command only on projects matching |
| 55 | regex or wildcard expression. |
| 56 | |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 57 | Output Formatting |
| 58 | ----------------- |
| 59 | |
| 60 | The -p option causes '%prog' to bind pipes to the command's stdin, |
| 61 | stdout and stderr streams, and pipe all output into a continuous |
| 62 | stream that is displayed in a single pager session. Project headings |
| 63 | are inserted before the output of each command is displayed. If the |
| 64 | command produces no output in a project, no heading is displayed. |
| 65 | |
| 66 | The formatting convention used by -p is very suitable for some |
| 67 | types of searching, e.g. `repo forall -p -c git log -SFoo` will |
| 68 | print all commits that add or remove references to Foo. |
| 69 | |
| 70 | The -v option causes '%prog' to display stderr messages if a |
| 71 | command produces output only on stderr. Normally the -p option |
| 72 | causes command output to be suppressed until the command produces |
| 73 | at least one byte of output on stdout. |
| 74 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 75 | Environment |
| 76 | ----------- |
Shawn O. Pearce | ff84fea | 2009-04-13 12:11:59 -0700 | [diff] [blame] | 77 | |
Shawn O. Pearce | 4446946 | 2009-03-03 17:51:01 -0800 | [diff] [blame] | 78 | pwd is the project's working directory. If the current client is |
| 79 | a mirror client, then pwd is the Git repository. |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 80 | |
| 81 | REPO_PROJECT is set to the unique name of the project. |
| 82 | |
Jeff Bailey | be0e8ac | 2009-01-21 19:05:15 -0500 | [diff] [blame] | 83 | REPO_PATH is the path relative the the root of the client. |
| 84 | |
| 85 | REPO_REMOTE is the name of the remote system from the manifest. |
| 86 | |
| 87 | REPO_LREV is the name of the revision from the manifest, translated |
| 88 | to a local tracking branch. If you need to pass the manifest |
| 89 | revision to a locally executed git command, use REPO_LREV. |
| 90 | |
| 91 | REPO_RREV is the name of the revision from the manifest, exactly |
| 92 | as written in the manifest. |
| 93 | |
Mitchel Humpherys | e81bc03 | 2014-03-31 11:36:56 -0700 | [diff] [blame] | 94 | REPO_COUNT is the total number of projects being iterated. |
| 95 | |
| 96 | REPO_I is the current (1-based) iteration count. Can be used in |
| 97 | conjunction with REPO_COUNT to add a simple progress indicator to your |
| 98 | command. |
| 99 | |
James W. Mills | 24c1308 | 2012-04-12 15:04:13 -0500 | [diff] [blame] | 100 | REPO__* are any extra environment variables, specified by the |
| 101 | "annotation" element under any project element. This can be useful |
| 102 | for differentiating trees based on user-specific criteria, or simply |
| 103 | annotating tree details. |
| 104 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 105 | shell positional arguments ($1, $2, .., $#) are set to any arguments |
| 106 | following <command>. |
| 107 | |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 108 | Unless -p is used, stdin, stdout, stderr are inherited from the |
| 109 | terminal and are not redirected. |
Victor Boivie | 88b8672 | 2011-09-07 09:43:28 +0200 | [diff] [blame] | 110 | |
| 111 | If -e is used, when a command exits unsuccessfully, '%prog' will abort |
| 112 | without iterating through the remaining projects. |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 113 | """ |
| 114 | |
| 115 | def _Options(self, p): |
| 116 | def cmd(option, opt_str, value, parser): |
| 117 | setattr(parser.values, option.dest, list(parser.rargs)) |
| 118 | while parser.rargs: |
| 119 | del parser.rargs[0] |
Zhiguang Li | a8864fb | 2013-03-15 10:32:10 +0800 | [diff] [blame] | 120 | p.add_option('-r', '--regex', |
| 121 | dest='regex', action='store_true', |
| 122 | help="Execute the command only on projects matching regex or wildcard expression") |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 123 | p.add_option('-c', '--command', |
| 124 | help='Command (and arguments) to execute', |
| 125 | dest='command', |
| 126 | action='callback', |
| 127 | callback=cmd) |
Victor Boivie | 88b8672 | 2011-09-07 09:43:28 +0200 | [diff] [blame] | 128 | p.add_option('-e', '--abort-on-errors', |
| 129 | dest='abort_on_errors', action='store_true', |
| 130 | help='Abort if a command exits unsuccessfully') |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 131 | |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 132 | g = p.add_option_group('Output') |
| 133 | g.add_option('-p', |
| 134 | dest='project_header', action='store_true', |
| 135 | help='Show project headers before output') |
| 136 | g.add_option('-v', '--verbose', |
| 137 | dest='verbose', action='store_true', |
| 138 | help='Show command error messages') |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 139 | g.add_option('-j', '--jobs', |
| 140 | dest='jobs', action='store', type='int', default=1, |
| 141 | help='number of commands to execute simultaneously') |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 142 | |
| 143 | def WantPager(self, opt): |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 144 | return opt.project_header and opt.jobs == 1 |
| 145 | |
| 146 | def _SerializeProject(self, project): |
| 147 | """ Serialize a project._GitGetByExec instance. |
| 148 | |
| 149 | project._GitGetByExec is not pickle-able. Instead of trying to pass it |
| 150 | around between processes, make a dict ourselves containing only the |
| 151 | attributes that we need. |
| 152 | |
| 153 | """ |
David Pursehouse | 30d13ee | 2015-05-07 15:01:15 +0900 | [diff] [blame] | 154 | if not self.manifest.IsMirror: |
| 155 | lrev = project.GetRevisionId() |
| 156 | else: |
| 157 | lrev = None |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 158 | return { |
| 159 | 'name': project.name, |
| 160 | 'relpath': project.relpath, |
| 161 | 'remote_name': project.remote.name, |
David Pursehouse | 30d13ee | 2015-05-07 15:01:15 +0900 | [diff] [blame] | 162 | 'lrev': lrev, |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 163 | 'rrev': project.revisionExpr, |
| 164 | 'annotations': dict((a.name, a.value) for a in project.annotations), |
| 165 | 'gitdir': project.gitdir, |
| 166 | 'worktree': project.worktree, |
| 167 | } |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 168 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 169 | def Execute(self, opt, args): |
| 170 | if not opt.command: |
| 171 | self.Usage() |
| 172 | |
| 173 | cmd = [opt.command[0]] |
| 174 | |
| 175 | shell = True |
| 176 | if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]): |
| 177 | shell = False |
| 178 | |
| 179 | if shell: |
| 180 | cmd.append(cmd[0]) |
| 181 | cmd.extend(opt.command[1:]) |
| 182 | |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 183 | if opt.project_header \ |
| 184 | and not shell \ |
| 185 | and cmd[0] == 'git': |
| 186 | # If this is a direct git command that can enable colorized |
| 187 | # output and the user prefers coloring, add --color into the |
| 188 | # command line because we are going to wrap the command into |
| 189 | # a pipe and git won't know coloring should activate. |
| 190 | # |
| 191 | for cn in cmd[1:]: |
| 192 | if not cn.startswith('-'): |
| 193 | break |
David Pursehouse | 5c6eeac | 2012-10-11 16:44:48 +0900 | [diff] [blame] | 194 | else: |
| 195 | cn = None |
David Pursehouse | 4f7bdea | 2012-10-22 12:50:15 +0900 | [diff] [blame] | 196 | # pylint: disable=W0631 |
David Pursehouse | 5c6eeac | 2012-10-11 16:44:48 +0900 | [diff] [blame] | 197 | if cn and cn in _CAN_COLOR: |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 198 | class ColorCmd(Coloring): |
| 199 | def __init__(self, config, cmd): |
| 200 | Coloring.__init__(self, config, cmd) |
| 201 | if ColorCmd(self.manifest.manifestProject.config, cn).is_on: |
| 202 | cmd.insert(cmd.index(cn) + 1, '--color') |
David Pursehouse | 4f7bdea | 2012-10-22 12:50:15 +0900 | [diff] [blame] | 203 | # pylint: enable=W0631 |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 204 | |
Shawn O. Pearce | 4446946 | 2009-03-03 17:51:01 -0800 | [diff] [blame] | 205 | mirror = self.manifest.IsMirror |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 206 | rc = 0 |
Shawn O. Pearce | db45da1 | 2009-04-18 13:49:13 -0700 | [diff] [blame] | 207 | |
David Pursehouse | 6944cdb | 2015-05-07 14:39:44 +0900 | [diff] [blame] | 208 | smart_sync_manifest_name = "smart_sync_override.xml" |
| 209 | smart_sync_manifest_path = os.path.join( |
| 210 | self.manifest.manifestProject.worktree, smart_sync_manifest_name) |
| 211 | |
| 212 | if os.path.isfile(smart_sync_manifest_path): |
| 213 | self.manifest.Override(smart_sync_manifest_path) |
| 214 | |
Zhiguang Li | a8864fb | 2013-03-15 10:32:10 +0800 | [diff] [blame] | 215 | if not opt.regex: |
| 216 | projects = self.GetProjects(args) |
| 217 | else: |
| 218 | projects = self.FindProjects(args) |
| 219 | |
Mitchel Humpherys | e81bc03 | 2014-03-31 11:36:56 -0700 | [diff] [blame] | 220 | os.environ['REPO_COUNT'] = str(len(projects)) |
| 221 | |
Colin Cross | 31a7be5 | 2015-05-13 00:04:36 -0700 | [diff] [blame] | 222 | pool = multiprocessing.Pool(opt.jobs, InitWorker) |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 223 | try: |
| 224 | config = self.manifest.manifestProject.config |
| 225 | results_it = pool.imap( |
| 226 | DoWorkWrapper, |
Colin Cross | 31a7be5 | 2015-05-13 00:04:36 -0700 | [diff] [blame] | 227 | self.ProjectArgs(projects, mirror, opt, cmd, shell, config)) |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 228 | pool.close() |
| 229 | for r in results_it: |
| 230 | rc = rc or r |
| 231 | if r != 0 and opt.abort_on_errors: |
| 232 | raise Exception('Aborting due to previous error') |
| 233 | except (KeyboardInterrupt, WorkerKeyboardInterrupt): |
| 234 | # Catch KeyboardInterrupt raised inside and outside of workers |
| 235 | print('Interrupted - terminating the pool') |
| 236 | pool.terminate() |
| 237 | rc = rc or errno.EINTR |
| 238 | except Exception as e: |
| 239 | # Catch any other exceptions raised |
| 240 | print('Got an error, terminating the pool: %r' % e, |
| 241 | file=sys.stderr) |
| 242 | pool.terminate() |
| 243 | rc = rc or getattr(e, 'errno', 1) |
| 244 | finally: |
| 245 | pool.join() |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 246 | if rc != 0: |
| 247 | sys.exit(rc) |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 248 | |
Colin Cross | 31a7be5 | 2015-05-13 00:04:36 -0700 | [diff] [blame] | 249 | def ProjectArgs(self, projects, mirror, opt, cmd, shell, config): |
| 250 | for cnt, p in enumerate(projects): |
| 251 | try: |
| 252 | project = self._SerializeProject(p) |
| 253 | except Exception as e: |
| 254 | print('Project list error: %r' % e, |
| 255 | file=sys.stderr) |
| 256 | return |
| 257 | except KeyboardInterrupt: |
| 258 | print('Project list interrupted', |
| 259 | file=sys.stderr) |
| 260 | return |
| 261 | yield [mirror, opt, cmd, shell, cnt, config, project] |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 262 | |
| 263 | class WorkerKeyboardInterrupt(Exception): |
| 264 | """ Keyboard interrupt exception for worker processes. """ |
| 265 | pass |
| 266 | |
| 267 | |
Colin Cross | 31a7be5 | 2015-05-13 00:04:36 -0700 | [diff] [blame] | 268 | def InitWorker(): |
| 269 | signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 270 | |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 271 | def DoWorkWrapper(args): |
| 272 | """ A wrapper around the DoWork() method. |
| 273 | |
| 274 | Catch the KeyboardInterrupt exceptions here and re-raise them as a different, |
| 275 | ``Exception``-based exception to stop it flooding the console with stacktraces |
| 276 | and making the parent hang indefinitely. |
| 277 | |
| 278 | """ |
| 279 | project = args.pop() |
| 280 | try: |
| 281 | return DoWork(project, *args) |
| 282 | except KeyboardInterrupt: |
| 283 | print('%s: Worker interrupted' % project['name']) |
| 284 | raise WorkerKeyboardInterrupt() |
| 285 | |
| 286 | |
| 287 | def DoWork(project, mirror, opt, cmd, shell, cnt, config): |
| 288 | env = os.environ.copy() |
| 289 | def setenv(name, val): |
| 290 | if val is None: |
| 291 | val = '' |
Anthony King | c116f94 | 2015-06-03 17:29:29 +0100 | [diff] [blame] | 292 | if hasattr(val, 'encode'): |
| 293 | val = val.encode() |
| 294 | env[name] = val |
Takeshi Kanemoto | a769498 | 2014-04-14 17:36:57 +0900 | [diff] [blame] | 295 | |
| 296 | setenv('REPO_PROJECT', project['name']) |
| 297 | setenv('REPO_PATH', project['relpath']) |
| 298 | setenv('REPO_REMOTE', project['remote_name']) |
| 299 | setenv('REPO_LREV', project['lrev']) |
| 300 | setenv('REPO_RREV', project['rrev']) |
| 301 | setenv('REPO_I', str(cnt + 1)) |
| 302 | for name in project['annotations']: |
| 303 | setenv("REPO__%s" % (name), project['annotations'][name]) |
| 304 | |
| 305 | if mirror: |
| 306 | setenv('GIT_DIR', project['gitdir']) |
| 307 | cwd = project['gitdir'] |
| 308 | else: |
| 309 | cwd = project['worktree'] |
| 310 | |
| 311 | if not os.path.exists(cwd): |
| 312 | if (opt.project_header and opt.verbose) \ |
| 313 | or not opt.project_header: |
| 314 | print('skipping %s/' % project['relpath'], file=sys.stderr) |
| 315 | return |
| 316 | |
| 317 | if opt.project_header: |
| 318 | stdin = subprocess.PIPE |
| 319 | stdout = subprocess.PIPE |
| 320 | stderr = subprocess.PIPE |
| 321 | else: |
| 322 | stdin = None |
| 323 | stdout = None |
| 324 | stderr = None |
| 325 | |
| 326 | p = subprocess.Popen(cmd, |
| 327 | cwd=cwd, |
| 328 | shell=shell, |
| 329 | env=env, |
| 330 | stdin=stdin, |
| 331 | stdout=stdout, |
| 332 | stderr=stderr) |
| 333 | |
| 334 | if opt.project_header: |
| 335 | out = ForallColoring(config) |
| 336 | out.redirect(sys.stdout) |
| 337 | class sfd(object): |
| 338 | def __init__(self, fd, dest): |
| 339 | self.fd = fd |
| 340 | self.dest = dest |
| 341 | def fileno(self): |
| 342 | return self.fd.fileno() |
| 343 | |
| 344 | empty = True |
| 345 | errbuf = '' |
| 346 | |
| 347 | p.stdin.close() |
| 348 | s_in = [sfd(p.stdout, sys.stdout), |
| 349 | sfd(p.stderr, sys.stderr)] |
| 350 | |
| 351 | for s in s_in: |
| 352 | flags = fcntl.fcntl(s.fd, fcntl.F_GETFL) |
| 353 | fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) |
| 354 | |
| 355 | while s_in: |
| 356 | in_ready, _out_ready, _err_ready = select.select(s_in, [], []) |
| 357 | for s in in_ready: |
| 358 | buf = s.fd.read(4096) |
| 359 | if not buf: |
| 360 | s.fd.close() |
| 361 | s_in.remove(s) |
| 362 | continue |
| 363 | |
| 364 | if not opt.verbose: |
| 365 | if s.fd != p.stdout: |
| 366 | errbuf += buf |
| 367 | continue |
| 368 | |
| 369 | if empty and out: |
| 370 | if not cnt == 0: |
| 371 | out.nl() |
| 372 | |
| 373 | if mirror: |
| 374 | project_header_path = project['name'] |
| 375 | else: |
| 376 | project_header_path = project['relpath'] |
| 377 | out.project('project %s/', project_header_path) |
| 378 | out.nl() |
| 379 | out.flush() |
| 380 | if errbuf: |
| 381 | sys.stderr.write(errbuf) |
| 382 | sys.stderr.flush() |
| 383 | errbuf = '' |
| 384 | empty = False |
| 385 | |
| 386 | s.dest.write(buf) |
| 387 | s.dest.flush() |
| 388 | |
| 389 | r = p.wait() |
| 390 | return r |