forall.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. """
  77. def _Options(self, p):
  78. def cmd(option, opt_str, value, parser):
  79. setattr(parser.values, option.dest, list(parser.rargs))
  80. while parser.rargs:
  81. del parser.rargs[0]
  82. p.add_option('-c', '--command',
  83. help='Command (and arguments) to execute',
  84. dest='command',
  85. action='callback',
  86. callback=cmd)
  87. g = p.add_option_group('Output')
  88. g.add_option('-p',
  89. dest='project_header', action='store_true',
  90. help='Show project headers before output')
  91. g.add_option('-v', '--verbose',
  92. dest='verbose', action='store_true',
  93. help='Show command error messages')
  94. def WantPager(self, opt):
  95. return opt.project_header
  96. def Execute(self, opt, args):
  97. if not opt.command:
  98. self.Usage()
  99. cmd = [opt.command[0]]
  100. shell = True
  101. if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
  102. shell = False
  103. if shell:
  104. cmd.append(cmd[0])
  105. cmd.extend(opt.command[1:])
  106. if opt.project_header \
  107. and not shell \
  108. and cmd[0] == 'git':
  109. # If this is a direct git command that can enable colorized
  110. # output and the user prefers coloring, add --color into the
  111. # command line because we are going to wrap the command into
  112. # a pipe and git won't know coloring should activate.
  113. #
  114. for cn in cmd[1:]:
  115. if not cn.startswith('-'):
  116. break
  117. else:
  118. cn = None
  119. # pylint: disable=W0631
  120. if cn and cn in _CAN_COLOR:
  121. class ColorCmd(Coloring):
  122. def __init__(self, config, cmd):
  123. Coloring.__init__(self, config, cmd)
  124. if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
  125. cmd.insert(cmd.index(cn) + 1, '--color')
  126. # pylint: enable=W0631
  127. mirror = self.manifest.IsMirror
  128. out = ForallColoring(self.manifest.manifestProject.config)
  129. out.redirect(sys.stdout)
  130. rc = 0
  131. first = True
  132. for project in self.GetProjects(args):
  133. env = os.environ.copy()
  134. def setenv(name, val):
  135. if val is None:
  136. val = ''
  137. env[name] = val.encode()
  138. setenv('REPO_PROJECT', project.name)
  139. setenv('REPO_PATH', project.relpath)
  140. setenv('REPO_REMOTE', project.remote.name)
  141. setenv('REPO_LREV', project.GetRevisionId())
  142. setenv('REPO_RREV', project.revisionExpr)
  143. for a in project.annotations:
  144. setenv("REPO__%s" % (a.name), a.value)
  145. if mirror:
  146. setenv('GIT_DIR', project.gitdir)
  147. cwd = project.gitdir
  148. else:
  149. cwd = project.worktree
  150. if not os.path.exists(cwd):
  151. if (opt.project_header and opt.verbose) \
  152. or not opt.project_header:
  153. print('skipping %s/' % project.relpath, file=sys.stderr)
  154. continue
  155. if opt.project_header:
  156. stdin = subprocess.PIPE
  157. stdout = subprocess.PIPE
  158. stderr = subprocess.PIPE
  159. else:
  160. stdin = None
  161. stdout = None
  162. stderr = None
  163. p = subprocess.Popen(cmd,
  164. cwd = cwd,
  165. shell = shell,
  166. env = env,
  167. stdin = stdin,
  168. stdout = stdout,
  169. stderr = stderr)
  170. if opt.project_header:
  171. class sfd(object):
  172. def __init__(self, fd, dest):
  173. self.fd = fd
  174. self.dest = dest
  175. def fileno(self):
  176. return self.fd.fileno()
  177. empty = True
  178. errbuf = ''
  179. p.stdin.close()
  180. s_in = [sfd(p.stdout, sys.stdout),
  181. sfd(p.stderr, sys.stderr)]
  182. for s in s_in:
  183. flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
  184. fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  185. while s_in:
  186. in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
  187. for s in in_ready:
  188. buf = s.fd.read(4096)
  189. if not buf:
  190. s.fd.close()
  191. s_in.remove(s)
  192. continue
  193. if not opt.verbose:
  194. if s.fd != p.stdout:
  195. errbuf += buf
  196. continue
  197. if empty:
  198. if first:
  199. first = False
  200. else:
  201. out.nl()
  202. out.project('project %s/', project.relpath)
  203. out.nl()
  204. out.flush()
  205. if errbuf:
  206. sys.stderr.write(errbuf)
  207. sys.stderr.flush()
  208. errbuf = ''
  209. empty = False
  210. s.dest.write(buf)
  211. s.dest.flush()
  212. r = p.wait()
  213. if r != 0 and r != rc:
  214. rc = r
  215. if rc != 0:
  216. sys.exit(rc)