forall.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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_COUNT is the total number of projects being iterated.
  72. REPO_I is the current (1-based) iteration count. Can be used in
  73. conjunction with REPO_COUNT to add a simple progress indicator to your
  74. command.
  75. REPO__* are any extra environment variables, specified by the
  76. "annotation" element under any project element. This can be useful
  77. for differentiating trees based on user-specific criteria, or simply
  78. annotating tree details.
  79. shell positional arguments ($1, $2, .., $#) are set to any arguments
  80. following <command>.
  81. Unless -p is used, stdin, stdout, stderr are inherited from the
  82. terminal and are not redirected.
  83. If -e is used, when a command exits unsuccessfully, '%prog' will abort
  84. without iterating through the remaining projects.
  85. """
  86. def _Options(self, p):
  87. def cmd(option, opt_str, value, parser):
  88. setattr(parser.values, option.dest, list(parser.rargs))
  89. while parser.rargs:
  90. del parser.rargs[0]
  91. p.add_option('-r', '--regex',
  92. dest='regex', action='store_true',
  93. help="Execute the command only on projects matching regex or wildcard expression")
  94. p.add_option('-c', '--command',
  95. help='Command (and arguments) to execute',
  96. dest='command',
  97. action='callback',
  98. callback=cmd)
  99. p.add_option('-e', '--abort-on-errors',
  100. dest='abort_on_errors', action='store_true',
  101. help='Abort if a command exits unsuccessfully')
  102. g = p.add_option_group('Output')
  103. g.add_option('-p',
  104. dest='project_header', action='store_true',
  105. help='Show project headers before output')
  106. g.add_option('-v', '--verbose',
  107. dest='verbose', action='store_true',
  108. help='Show command error messages')
  109. def WantPager(self, opt):
  110. return opt.project_header
  111. def Execute(self, opt, args):
  112. if not opt.command:
  113. self.Usage()
  114. cmd = [opt.command[0]]
  115. shell = True
  116. if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
  117. shell = False
  118. if shell:
  119. cmd.append(cmd[0])
  120. cmd.extend(opt.command[1:])
  121. if opt.project_header \
  122. and not shell \
  123. and cmd[0] == 'git':
  124. # If this is a direct git command that can enable colorized
  125. # output and the user prefers coloring, add --color into the
  126. # command line because we are going to wrap the command into
  127. # a pipe and git won't know coloring should activate.
  128. #
  129. for cn in cmd[1:]:
  130. if not cn.startswith('-'):
  131. break
  132. else:
  133. cn = None
  134. # pylint: disable=W0631
  135. if cn and cn in _CAN_COLOR:
  136. class ColorCmd(Coloring):
  137. def __init__(self, config, cmd):
  138. Coloring.__init__(self, config, cmd)
  139. if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
  140. cmd.insert(cmd.index(cn) + 1, '--color')
  141. # pylint: enable=W0631
  142. mirror = self.manifest.IsMirror
  143. out = ForallColoring(self.manifest.manifestProject.config)
  144. out.redirect(sys.stdout)
  145. rc = 0
  146. first = True
  147. if not opt.regex:
  148. projects = self.GetProjects(args)
  149. else:
  150. projects = self.FindProjects(args)
  151. os.environ['REPO_COUNT'] = str(len(projects))
  152. for (cnt, project) in enumerate(projects):
  153. env = os.environ.copy()
  154. def setenv(name, val):
  155. if val is None:
  156. val = ''
  157. env[name] = val.encode()
  158. setenv('REPO_PROJECT', project.name)
  159. setenv('REPO_PATH', project.relpath)
  160. setenv('REPO_REMOTE', project.remote.name)
  161. setenv('REPO_LREV', project.GetRevisionId())
  162. setenv('REPO_RREV', project.revisionExpr)
  163. setenv('REPO_I', str(cnt + 1))
  164. for a in project.annotations:
  165. setenv("REPO__%s" % (a.name), a.value)
  166. if mirror:
  167. setenv('GIT_DIR', project.gitdir)
  168. cwd = project.gitdir
  169. else:
  170. cwd = project.worktree
  171. if not os.path.exists(cwd):
  172. if (opt.project_header and opt.verbose) \
  173. or not opt.project_header:
  174. print('skipping %s/' % project.relpath, file=sys.stderr)
  175. continue
  176. if opt.project_header:
  177. stdin = subprocess.PIPE
  178. stdout = subprocess.PIPE
  179. stderr = subprocess.PIPE
  180. else:
  181. stdin = None
  182. stdout = None
  183. stderr = None
  184. p = subprocess.Popen(cmd,
  185. cwd = cwd,
  186. shell = shell,
  187. env = env,
  188. stdin = stdin,
  189. stdout = stdout,
  190. stderr = stderr)
  191. if opt.project_header:
  192. class sfd(object):
  193. def __init__(self, fd, dest):
  194. self.fd = fd
  195. self.dest = dest
  196. def fileno(self):
  197. return self.fd.fileno()
  198. empty = True
  199. errbuf = ''
  200. p.stdin.close()
  201. s_in = [sfd(p.stdout, sys.stdout),
  202. sfd(p.stderr, sys.stderr)]
  203. for s in s_in:
  204. flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
  205. fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  206. while s_in:
  207. in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
  208. for s in in_ready:
  209. buf = s.fd.read(4096)
  210. if not buf:
  211. s.fd.close()
  212. s_in.remove(s)
  213. continue
  214. if not opt.verbose:
  215. if s.fd != p.stdout:
  216. errbuf += buf
  217. continue
  218. if empty:
  219. if first:
  220. first = False
  221. else:
  222. out.nl()
  223. if mirror:
  224. project_header_path = project.name
  225. else:
  226. project_header_path = project.relpath
  227. out.project('project %s/', project_header_path)
  228. out.nl()
  229. out.flush()
  230. if errbuf:
  231. sys.stderr.write(errbuf)
  232. sys.stderr.flush()
  233. errbuf = ''
  234. empty = False
  235. s.dest.write(buf)
  236. s.dest.flush()
  237. r = p.wait()
  238. if r != 0:
  239. if r != rc:
  240. rc = r
  241. if opt.abort_on_errors:
  242. print("error: %s: Aborting due to previous error" % project.relpath,
  243. file=sys.stderr)
  244. sys.exit(r)
  245. if rc != 0:
  246. sys.exit(rc)