forall.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. from __future__ import print_function
  16. import fcntl
  17. import re
  18. import os
  19. import select
  20. import sys
  21. import subprocess
  22. from color import Coloring
  23. from command import Command, MirrorSafeCommand
  24. _CAN_COLOR = [
  25. 'branch',
  26. 'diff',
  27. 'grep',
  28. 'log',
  29. ]
  30. class ForallColoring(Coloring):
  31. def __init__(self, config):
  32. Coloring.__init__(self, config, 'forall')
  33. self.project = self.printer('project', attr='bold')
  34. class Forall(Command, MirrorSafeCommand):
  35. common = False
  36. helpSummary = "Run a shell command in each project"
  37. helpUsage = """
  38. %prog [<project>...] -c <command> [<arg>...]
  39. """
  40. helpDescription = """
  41. Executes the same shell command in each project.
  42. Output Formatting
  43. -----------------
  44. The -p option causes '%prog' to bind pipes to the command's stdin,
  45. stdout and stderr streams, and pipe all output into a continuous
  46. stream that is displayed in a single pager session. Project headings
  47. are inserted before the output of each command is displayed. If the
  48. command produces no output in a project, no heading is displayed.
  49. The formatting convention used by -p is very suitable for some
  50. types of searching, e.g. `repo forall -p -c git log -SFoo` will
  51. print all commits that add or remove references to Foo.
  52. The -v option causes '%prog' to display stderr messages if a
  53. command produces output only on stderr. Normally the -p option
  54. causes command output to be suppressed until the command produces
  55. at least one byte of output on stdout.
  56. Environment
  57. -----------
  58. pwd is the project's working directory. If the current client is
  59. a mirror client, then pwd is the Git repository.
  60. REPO_PROJECT is set to the unique name of the project.
  61. REPO_PATH is the path relative the the root of the client.
  62. REPO_REMOTE is the name of the remote system from the manifest.
  63. REPO_LREV is the name of the revision from the manifest, translated
  64. to a local tracking branch. If you need to pass the manifest
  65. revision to a locally executed git command, use REPO_LREV.
  66. REPO_RREV is the name of the revision from the manifest, exactly
  67. as written in the manifest.
  68. REPO__* are any extra environment variables, specified by the
  69. "annotation" element under any project element. This can be useful
  70. for differentiating trees based on user-specific criteria, or simply
  71. annotating tree details.
  72. shell positional arguments ($1, $2, .., $#) are set to any arguments
  73. following <command>.
  74. Unless -p is used, stdin, stdout, stderr are inherited from the
  75. terminal and are not redirected.
  76. If -e is used, when a command exits unsuccessfully, '%prog' will abort
  77. without iterating through the remaining projects.
  78. """
  79. def _Options(self, p):
  80. def cmd(option, opt_str, value, parser):
  81. setattr(parser.values, option.dest, list(parser.rargs))
  82. while parser.rargs:
  83. del parser.rargs[0]
  84. p.add_option('-c', '--command',
  85. help='Command (and arguments) to execute',
  86. dest='command',
  87. action='callback',
  88. callback=cmd)
  89. p.add_option('-e', '--abort-on-errors',
  90. dest='abort_on_errors', action='store_true',
  91. help='Abort if a command exits unsuccessfully')
  92. g = p.add_option_group('Output')
  93. g.add_option('-p',
  94. dest='project_header', action='store_true',
  95. help='Show project headers before output')
  96. g.add_option('-v', '--verbose',
  97. dest='verbose', action='store_true',
  98. help='Show command error messages')
  99. def WantPager(self, opt):
  100. return opt.project_header
  101. def Execute(self, opt, args):
  102. if not opt.command:
  103. self.Usage()
  104. cmd = [opt.command[0]]
  105. shell = True
  106. if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
  107. shell = False
  108. if shell:
  109. cmd.append(cmd[0])
  110. cmd.extend(opt.command[1:])
  111. if opt.project_header \
  112. and not shell \
  113. and cmd[0] == 'git':
  114. # If this is a direct git command that can enable colorized
  115. # output and the user prefers coloring, add --color into the
  116. # command line because we are going to wrap the command into
  117. # a pipe and git won't know coloring should activate.
  118. #
  119. for cn in cmd[1:]:
  120. if not cn.startswith('-'):
  121. break
  122. else:
  123. cn = None
  124. # pylint: disable=W0631
  125. if cn and cn in _CAN_COLOR:
  126. class ColorCmd(Coloring):
  127. def __init__(self, config, cmd):
  128. Coloring.__init__(self, config, cmd)
  129. if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
  130. cmd.insert(cmd.index(cn) + 1, '--color')
  131. # pylint: enable=W0631
  132. mirror = self.manifest.IsMirror
  133. out = ForallColoring(self.manifest.manifestProject.config)
  134. out.redirect(sys.stdout)
  135. rc = 0
  136. first = True
  137. for project in self.GetProjects(args):
  138. env = os.environ.copy()
  139. def setenv(name, val):
  140. if val is None:
  141. val = ''
  142. env[name] = val.encode()
  143. setenv('REPO_PROJECT', project.name)
  144. setenv('REPO_PATH', project.relpath)
  145. setenv('REPO_REMOTE', project.remote.name)
  146. setenv('REPO_LREV', project.GetRevisionId())
  147. setenv('REPO_RREV', project.revisionExpr)
  148. for a in project.annotations:
  149. setenv("REPO__%s" % (a.name), a.value)
  150. if mirror:
  151. setenv('GIT_DIR', project.gitdir)
  152. cwd = project.gitdir
  153. else:
  154. cwd = project.worktree
  155. if not os.path.exists(cwd):
  156. if (opt.project_header and opt.verbose) \
  157. or not opt.project_header:
  158. print('skipping %s/' % project.relpath, file=sys.stderr)
  159. continue
  160. if opt.project_header:
  161. stdin = subprocess.PIPE
  162. stdout = subprocess.PIPE
  163. stderr = subprocess.PIPE
  164. else:
  165. stdin = None
  166. stdout = None
  167. stderr = None
  168. p = subprocess.Popen(cmd,
  169. cwd = cwd,
  170. shell = shell,
  171. env = env,
  172. stdin = stdin,
  173. stdout = stdout,
  174. stderr = stderr)
  175. if opt.project_header:
  176. class sfd(object):
  177. def __init__(self, fd, dest):
  178. self.fd = fd
  179. self.dest = dest
  180. def fileno(self):
  181. return self.fd.fileno()
  182. empty = True
  183. errbuf = ''
  184. p.stdin.close()
  185. s_in = [sfd(p.stdout, sys.stdout),
  186. sfd(p.stderr, sys.stderr)]
  187. for s in s_in:
  188. flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
  189. fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  190. while s_in:
  191. in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
  192. for s in in_ready:
  193. buf = s.fd.read(4096)
  194. if not buf:
  195. s.fd.close()
  196. s_in.remove(s)
  197. continue
  198. if not opt.verbose:
  199. if s.fd != p.stdout:
  200. errbuf += buf
  201. continue
  202. if empty:
  203. if first:
  204. first = False
  205. else:
  206. out.nl()
  207. out.project('project %s/', project.relpath)
  208. out.nl()
  209. out.flush()
  210. if errbuf:
  211. sys.stderr.write(errbuf)
  212. sys.stderr.flush()
  213. errbuf = ''
  214. empty = False
  215. s.dest.write(buf)
  216. s.dest.flush()
  217. r = p.wait()
  218. if r != 0:
  219. if r != rc:
  220. rc = r
  221. if opt.abort_on_errors:
  222. print("error: %s: Aborting due to previous error" % project.relpath,
  223. file=sys.stderr)
  224. sys.exit(r)
  225. if rc != 0:
  226. sys.exit(rc)