forall.py 7.1 KB

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