forall.py 8.7 KB

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