forall.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import errno
  18. import multiprocessing
  19. import re
  20. import os
  21. import signal
  22. import sys
  23. import subprocess
  24. from color import Coloring
  25. from command import Command, MirrorSafeCommand
  26. import platform_utils
  27. _CAN_COLOR = [
  28. 'branch',
  29. 'diff',
  30. 'grep',
  31. 'log',
  32. ]
  33. class ForallColoring(Coloring):
  34. def __init__(self, config):
  35. Coloring.__init__(self, config, 'forall')
  36. self.project = self.printer('project', attr='bold')
  37. class Forall(Command, MirrorSafeCommand):
  38. common = False
  39. helpSummary = "Run a shell command in each project"
  40. helpUsage = """
  41. %prog [<project>...] -c <command> [<arg>...]
  42. %prog -r str1 [str2] ... -c <command> [<arg>...]"
  43. """
  44. helpDescription = """
  45. Executes the same shell command in each project.
  46. The -r option allows running the command only on projects matching
  47. regex or wildcard expression.
  48. # Output Formatting
  49. The -p option causes '%prog' to bind pipes to the command's stdin,
  50. stdout and stderr streams, and pipe all output into a continuous
  51. stream that is displayed in a single pager session. Project headings
  52. are inserted before the output of each command is displayed. If the
  53. command produces no output in a project, no heading is displayed.
  54. The formatting convention used by -p is very suitable for some
  55. types of searching, e.g. `repo forall -p -c git log -SFoo` will
  56. print all commits that add or remove references to Foo.
  57. The -v option causes '%prog' to display stderr messages if a
  58. command produces output only on stderr. Normally the -p option
  59. causes command output to be suppressed until the command produces
  60. at least one byte of output on stdout.
  61. # Environment
  62. pwd is the project's working directory. If the current client is
  63. a mirror client, then pwd is the Git repository.
  64. REPO_PROJECT is set to the unique name of the project.
  65. REPO_PATH is the path relative the the root of the client.
  66. REPO_REMOTE is the name of the remote system from the manifest.
  67. REPO_LREV is the name of the revision from the manifest, translated
  68. to a local tracking branch. If you need to pass the manifest
  69. revision to a locally executed git command, use REPO_LREV.
  70. REPO_RREV is the name of the revision from the manifest, exactly
  71. as written in the manifest.
  72. REPO_COUNT is the total number of projects being iterated.
  73. REPO_I is the current (1-based) iteration count. Can be used in
  74. conjunction with REPO_COUNT to add a simple progress indicator to your
  75. command.
  76. REPO__* are any extra environment variables, specified by the
  77. "annotation" element under any project element. This can be useful
  78. for differentiating trees based on user-specific criteria, or simply
  79. annotating tree details.
  80. shell positional arguments ($1, $2, .., $#) are set to any arguments
  81. following <command>.
  82. Example: to list projects:
  83. %prog -c 'echo $REPO_PROJECT'
  84. Notice that $REPO_PROJECT is quoted to ensure it is expanded in
  85. the context of running <command> instead of in the calling shell.
  86. Unless -p is used, stdin, stdout, stderr are inherited from the
  87. terminal and are not redirected.
  88. If -e is used, when a command exits unsuccessfully, '%prog' will abort
  89. without iterating through the remaining projects.
  90. """
  91. def _Options(self, p):
  92. def cmd(option, opt_str, value, parser):
  93. setattr(parser.values, option.dest, list(parser.rargs))
  94. while parser.rargs:
  95. del parser.rargs[0]
  96. p.add_option('-r', '--regex',
  97. dest='regex', action='store_true',
  98. help="Execute the command only on projects matching regex or wildcard expression")
  99. p.add_option('-i', '--inverse-regex',
  100. dest='inverse_regex', action='store_true',
  101. help="Execute the command only on projects not matching regex or "
  102. "wildcard expression")
  103. p.add_option('-g', '--groups',
  104. dest='groups',
  105. help="Execute the command only on projects matching the specified groups")
  106. p.add_option('-c', '--command',
  107. help='Command (and arguments) to execute',
  108. dest='command',
  109. action='callback',
  110. callback=cmd)
  111. p.add_option('-e', '--abort-on-errors',
  112. dest='abort_on_errors', action='store_true',
  113. help='Abort if a command exits unsuccessfully')
  114. p.add_option('--ignore-missing', action='store_true',
  115. help='Silently skip & do not exit non-zero due missing '
  116. 'checkouts')
  117. g = p.add_option_group('Output')
  118. g.add_option('-p',
  119. dest='project_header', action='store_true',
  120. help='Show project headers before output')
  121. g.add_option('-v', '--verbose',
  122. dest='verbose', action='store_true',
  123. help='Show command error messages')
  124. g.add_option('-j', '--jobs',
  125. dest='jobs', action='store', type='int', default=1,
  126. help='number of commands to execute simultaneously')
  127. def WantPager(self, opt):
  128. return opt.project_header and opt.jobs == 1
  129. def _SerializeProject(self, project):
  130. """ Serialize a project._GitGetByExec instance.
  131. project._GitGetByExec is not pickle-able. Instead of trying to pass it
  132. around between processes, make a dict ourselves containing only the
  133. attributes that we need.
  134. """
  135. if not self.manifest.IsMirror:
  136. lrev = project.GetRevisionId()
  137. else:
  138. lrev = None
  139. return {
  140. 'name': project.name,
  141. 'relpath': project.relpath,
  142. 'remote_name': project.remote.name,
  143. 'lrev': lrev,
  144. 'rrev': project.revisionExpr,
  145. 'annotations': dict((a.name, a.value) for a in project.annotations),
  146. 'gitdir': project.gitdir,
  147. 'worktree': project.worktree,
  148. 'upstream': project.upstream,
  149. 'dest_branch': project.dest_branch,
  150. }
  151. def ValidateOptions(self, opt, args):
  152. if not opt.command:
  153. self.Usage()
  154. def Execute(self, opt, args):
  155. cmd = [opt.command[0]]
  156. shell = True
  157. if re.compile(r'^[a-z0-9A-Z_/\.-]+$').match(cmd[0]):
  158. shell = False
  159. if shell:
  160. cmd.append(cmd[0])
  161. cmd.extend(opt.command[1:])
  162. if opt.project_header \
  163. and not shell \
  164. and cmd[0] == 'git':
  165. # If this is a direct git command that can enable colorized
  166. # output and the user prefers coloring, add --color into the
  167. # command line because we are going to wrap the command into
  168. # a pipe and git won't know coloring should activate.
  169. #
  170. for cn in cmd[1:]:
  171. if not cn.startswith('-'):
  172. break
  173. else:
  174. cn = None
  175. if cn and cn in _CAN_COLOR:
  176. class ColorCmd(Coloring):
  177. def __init__(self, config, cmd):
  178. Coloring.__init__(self, config, cmd)
  179. if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
  180. cmd.insert(cmd.index(cn) + 1, '--color')
  181. mirror = self.manifest.IsMirror
  182. rc = 0
  183. smart_sync_manifest_name = "smart_sync_override.xml"
  184. smart_sync_manifest_path = os.path.join(
  185. self.manifest.manifestProject.worktree, smart_sync_manifest_name)
  186. if os.path.isfile(smart_sync_manifest_path):
  187. self.manifest.Override(smart_sync_manifest_path)
  188. if opt.regex:
  189. projects = self.FindProjects(args)
  190. elif opt.inverse_regex:
  191. projects = self.FindProjects(args, inverse=True)
  192. else:
  193. projects = self.GetProjects(args, groups=opt.groups)
  194. os.environ['REPO_COUNT'] = str(len(projects))
  195. pool = multiprocessing.Pool(opt.jobs, InitWorker)
  196. try:
  197. config = self.manifest.manifestProject.config
  198. results_it = pool.imap(
  199. DoWorkWrapper,
  200. self.ProjectArgs(projects, mirror, opt, cmd, shell, config))
  201. pool.close()
  202. for r in results_it:
  203. rc = rc or r
  204. if r != 0 and opt.abort_on_errors:
  205. raise Exception('Aborting due to previous error')
  206. except (KeyboardInterrupt, WorkerKeyboardInterrupt):
  207. # Catch KeyboardInterrupt raised inside and outside of workers
  208. print('Interrupted - terminating the pool')
  209. pool.terminate()
  210. rc = rc or errno.EINTR
  211. except Exception as e:
  212. # Catch any other exceptions raised
  213. print('Got an error, terminating the pool: %s: %s' %
  214. (type(e).__name__, e),
  215. file=sys.stderr)
  216. pool.terminate()
  217. rc = rc or getattr(e, 'errno', 1)
  218. finally:
  219. pool.join()
  220. if rc != 0:
  221. sys.exit(rc)
  222. def ProjectArgs(self, projects, mirror, opt, cmd, shell, config):
  223. for cnt, p in enumerate(projects):
  224. try:
  225. project = self._SerializeProject(p)
  226. except Exception as e:
  227. print('Project list error on project %s: %s: %s' %
  228. (p.name, type(e).__name__, e),
  229. file=sys.stderr)
  230. return
  231. except KeyboardInterrupt:
  232. print('Project list interrupted',
  233. file=sys.stderr)
  234. return
  235. yield [mirror, opt, cmd, shell, cnt, config, project]
  236. class WorkerKeyboardInterrupt(Exception):
  237. """ Keyboard interrupt exception for worker processes. """
  238. pass
  239. def InitWorker():
  240. signal.signal(signal.SIGINT, signal.SIG_IGN)
  241. def DoWorkWrapper(args):
  242. """ A wrapper around the DoWork() method.
  243. Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
  244. ``Exception``-based exception to stop it flooding the console with stacktraces
  245. and making the parent hang indefinitely.
  246. """
  247. project = args.pop()
  248. try:
  249. return DoWork(project, *args)
  250. except KeyboardInterrupt:
  251. print('%s: Worker interrupted' % project['name'])
  252. raise WorkerKeyboardInterrupt()
  253. def DoWork(project, mirror, opt, cmd, shell, cnt, config):
  254. env = os.environ.copy()
  255. def setenv(name, val):
  256. if val is None:
  257. val = ''
  258. env[name] = val
  259. setenv('REPO_PROJECT', project['name'])
  260. setenv('REPO_PATH', project['relpath'])
  261. setenv('REPO_REMOTE', project['remote_name'])
  262. setenv('REPO_LREV', project['lrev'])
  263. setenv('REPO_RREV', project['rrev'])
  264. setenv('REPO_UPSTREAM', project['upstream'])
  265. setenv('REPO_DEST_BRANCH', project['dest_branch'])
  266. setenv('REPO_I', str(cnt + 1))
  267. for name in project['annotations']:
  268. setenv("REPO__%s" % (name), project['annotations'][name])
  269. if mirror:
  270. setenv('GIT_DIR', project['gitdir'])
  271. cwd = project['gitdir']
  272. else:
  273. cwd = project['worktree']
  274. if not os.path.exists(cwd):
  275. # Allow the user to silently ignore missing checkouts so they can run on
  276. # partial checkouts (good for infra recovery tools).
  277. if opt.ignore_missing:
  278. return 0
  279. if ((opt.project_header and opt.verbose)
  280. or not opt.project_header):
  281. print('skipping %s/' % project['relpath'], file=sys.stderr)
  282. return 1
  283. if opt.project_header:
  284. stdin = subprocess.PIPE
  285. stdout = subprocess.PIPE
  286. stderr = subprocess.PIPE
  287. else:
  288. stdin = None
  289. stdout = None
  290. stderr = None
  291. p = subprocess.Popen(cmd,
  292. cwd=cwd,
  293. shell=shell,
  294. env=env,
  295. stdin=stdin,
  296. stdout=stdout,
  297. stderr=stderr)
  298. if opt.project_header:
  299. out = ForallColoring(config)
  300. out.redirect(sys.stdout)
  301. empty = True
  302. errbuf = ''
  303. p.stdin.close()
  304. s_in = platform_utils.FileDescriptorStreams.create()
  305. s_in.add(p.stdout, sys.stdout, 'stdout')
  306. s_in.add(p.stderr, sys.stderr, 'stderr')
  307. while not s_in.is_done:
  308. in_ready = s_in.select()
  309. for s in in_ready:
  310. buf = s.read().decode()
  311. if not buf:
  312. s_in.remove(s)
  313. s.close()
  314. continue
  315. if not opt.verbose:
  316. if s.std_name == 'stderr':
  317. errbuf += buf
  318. continue
  319. if empty and out:
  320. if not cnt == 0:
  321. out.nl()
  322. if mirror:
  323. project_header_path = project['name']
  324. else:
  325. project_header_path = project['relpath']
  326. out.project('project %s/', project_header_path)
  327. out.nl()
  328. out.flush()
  329. if errbuf:
  330. sys.stderr.write(errbuf)
  331. sys.stderr.flush()
  332. errbuf = ''
  333. empty = False
  334. s.dest.write(buf)
  335. s.dest.flush()
  336. r = p.wait()
  337. return r