forall.py 7.6 KB

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