forall.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. else:
  117. cn = None
  118. # pylint: disable=W0631
  119. if cn and cn in _CAN_COLOR:
  120. class ColorCmd(Coloring):
  121. def __init__(self, config, cmd):
  122. Coloring.__init__(self, config, cmd)
  123. if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
  124. cmd.insert(cmd.index(cn) + 1, '--color')
  125. # pylint: enable=W0631
  126. mirror = self.manifest.IsMirror
  127. out = ForallColoring(self.manifest.manifestProject.config)
  128. out.redirect(sys.stdout)
  129. rc = 0
  130. first = True
  131. for project in self.GetProjects(args):
  132. env = os.environ.copy()
  133. def setenv(name, val):
  134. if val is None:
  135. val = ''
  136. env[name] = val.encode()
  137. setenv('REPO_PROJECT', project.name)
  138. setenv('REPO_PATH', project.relpath)
  139. setenv('REPO_REMOTE', project.remote.name)
  140. setenv('REPO_LREV', project.GetRevisionId())
  141. setenv('REPO_RREV', project.revisionExpr)
  142. for a in project.annotations:
  143. setenv("REPO__%s" % (a.name), a.value)
  144. if mirror:
  145. setenv('GIT_DIR', project.gitdir)
  146. cwd = project.gitdir
  147. else:
  148. cwd = project.worktree
  149. if not os.path.exists(cwd):
  150. if (opt.project_header and opt.verbose) \
  151. or not opt.project_header:
  152. print >>sys.stderr, 'skipping %s/' % project.relpath
  153. continue
  154. if opt.project_header:
  155. stdin = subprocess.PIPE
  156. stdout = subprocess.PIPE
  157. stderr = subprocess.PIPE
  158. else:
  159. stdin = None
  160. stdout = None
  161. stderr = None
  162. p = subprocess.Popen(cmd,
  163. cwd = cwd,
  164. shell = shell,
  165. env = env,
  166. stdin = stdin,
  167. stdout = stdout,
  168. stderr = stderr)
  169. if opt.project_header:
  170. class sfd(object):
  171. def __init__(self, fd, dest):
  172. self.fd = fd
  173. self.dest = dest
  174. def fileno(self):
  175. return self.fd.fileno()
  176. empty = True
  177. errbuf = ''
  178. p.stdin.close()
  179. s_in = [sfd(p.stdout, sys.stdout),
  180. sfd(p.stderr, sys.stderr)]
  181. for s in s_in:
  182. flags = fcntl.fcntl(s.fd, fcntl.F_GETFL)
  183. fcntl.fcntl(s.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  184. while s_in:
  185. in_ready, _out_ready, _err_ready = select.select(s_in, [], [])
  186. for s in in_ready:
  187. buf = s.fd.read(4096)
  188. if not buf:
  189. s.fd.close()
  190. s_in.remove(s)
  191. continue
  192. if not opt.verbose:
  193. if s.fd != p.stdout:
  194. errbuf += buf
  195. continue
  196. if empty:
  197. if first:
  198. first = False
  199. else:
  200. out.nl()
  201. out.project('project %s/', project.relpath)
  202. out.nl()
  203. out.flush()
  204. if errbuf:
  205. sys.stderr.write(errbuf)
  206. sys.stderr.flush()
  207. errbuf = ''
  208. empty = False
  209. s.dest.write(buf)
  210. s.dest.flush()
  211. r = p.wait()
  212. if r != 0 and r != rc:
  213. rc = r
  214. if rc != 0:
  215. sys.exit(rc)