grep.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2009 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 sys
  18. from color import Coloring
  19. from command import PagedCommand
  20. from error import GitError
  21. from git_command import git_require, GitCommand
  22. class GrepColoring(Coloring):
  23. def __init__(self, config):
  24. Coloring.__init__(self, config, 'grep')
  25. self.project = self.printer('project', attr='bold')
  26. self.fail = self.printer('fail', fg='red')
  27. class Grep(PagedCommand):
  28. common = True
  29. helpSummary = "Print lines matching a pattern"
  30. helpUsage = """
  31. %prog {pattern | -e pattern} [<project>...]
  32. """
  33. helpDescription = """
  34. Search for the specified patterns in all project files.
  35. # Boolean Options
  36. The following options can appear as often as necessary to express
  37. the pattern to locate:
  38. -e PATTERN
  39. --and, --or, --not, -(, -)
  40. Further, the -r/--revision option may be specified multiple times
  41. in order to scan multiple trees. If the same file matches in more
  42. than one tree, only the first result is reported, prefixed by the
  43. revision name it was found under.
  44. # Examples
  45. Look for a line that has '#define' and either 'MAX_PATH or 'PATH_MAX':
  46. repo grep -e '#define' --and -\\( -e MAX_PATH -e PATH_MAX \\)
  47. Look for a line that has 'NODE' or 'Unexpected' in files that
  48. contain a line that matches both expressions:
  49. repo grep --all-match -e NODE -e Unexpected
  50. """
  51. def _Options(self, p):
  52. def carry(option,
  53. opt_str,
  54. value,
  55. parser):
  56. pt = getattr(parser.values, 'cmd_argv', None)
  57. if pt is None:
  58. pt = []
  59. setattr(parser.values, 'cmd_argv', pt)
  60. if opt_str == '-(':
  61. pt.append('(')
  62. elif opt_str == '-)':
  63. pt.append(')')
  64. else:
  65. pt.append(opt_str)
  66. if value is not None:
  67. pt.append(value)
  68. g = p.add_option_group('Sources')
  69. g.add_option('--cached',
  70. action='callback', callback=carry,
  71. help='Search the index, instead of the work tree')
  72. g.add_option('-r', '--revision',
  73. dest='revision', action='append', metavar='TREEish',
  74. help='Search TREEish, instead of the work tree')
  75. g = p.add_option_group('Pattern')
  76. g.add_option('-e',
  77. action='callback', callback=carry,
  78. metavar='PATTERN', type='str',
  79. help='Pattern to search for')
  80. g.add_option('-i', '--ignore-case',
  81. action='callback', callback=carry,
  82. help='Ignore case differences')
  83. g.add_option('-a', '--text',
  84. action='callback', callback=carry,
  85. help="Process binary files as if they were text")
  86. g.add_option('-I',
  87. action='callback', callback=carry,
  88. help="Don't match the pattern in binary files")
  89. g.add_option('-w', '--word-regexp',
  90. action='callback', callback=carry,
  91. help='Match the pattern only at word boundaries')
  92. g.add_option('-v', '--invert-match',
  93. action='callback', callback=carry,
  94. help='Select non-matching lines')
  95. g.add_option('-G', '--basic-regexp',
  96. action='callback', callback=carry,
  97. help='Use POSIX basic regexp for patterns (default)')
  98. g.add_option('-E', '--extended-regexp',
  99. action='callback', callback=carry,
  100. help='Use POSIX extended regexp for patterns')
  101. g.add_option('-F', '--fixed-strings',
  102. action='callback', callback=carry,
  103. help='Use fixed strings (not regexp) for pattern')
  104. g = p.add_option_group('Pattern Grouping')
  105. g.add_option('--all-match',
  106. action='callback', callback=carry,
  107. help='Limit match to lines that have all patterns')
  108. g.add_option('--and', '--or', '--not',
  109. action='callback', callback=carry,
  110. help='Boolean operators to combine patterns')
  111. g.add_option('-(', '-)',
  112. action='callback', callback=carry,
  113. help='Boolean operator grouping')
  114. g = p.add_option_group('Output')
  115. g.add_option('-n',
  116. action='callback', callback=carry,
  117. help='Prefix the line number to matching lines')
  118. g.add_option('-C',
  119. action='callback', callback=carry,
  120. metavar='CONTEXT', type='str',
  121. help='Show CONTEXT lines around match')
  122. g.add_option('-B',
  123. action='callback', callback=carry,
  124. metavar='CONTEXT', type='str',
  125. help='Show CONTEXT lines before match')
  126. g.add_option('-A',
  127. action='callback', callback=carry,
  128. metavar='CONTEXT', type='str',
  129. help='Show CONTEXT lines after match')
  130. g.add_option('-l', '--name-only', '--files-with-matches',
  131. action='callback', callback=carry,
  132. help='Show only file names containing matching lines')
  133. g.add_option('-L', '--files-without-match',
  134. action='callback', callback=carry,
  135. help='Show only file names not containing matching lines')
  136. def Execute(self, opt, args):
  137. out = GrepColoring(self.manifest.manifestProject.config)
  138. cmd_argv = ['grep']
  139. if out.is_on and git_require((1, 6, 3)):
  140. cmd_argv.append('--color')
  141. cmd_argv.extend(getattr(opt, 'cmd_argv', []))
  142. if '-e' not in cmd_argv:
  143. if not args:
  144. self.Usage()
  145. cmd_argv.append('-e')
  146. cmd_argv.append(args[0])
  147. args = args[1:]
  148. projects = self.GetProjects(args)
  149. full_name = False
  150. if len(projects) > 1:
  151. cmd_argv.append('--full-name')
  152. full_name = True
  153. have_rev = False
  154. if opt.revision:
  155. if '--cached' in cmd_argv:
  156. print('fatal: cannot combine --cached and --revision', file=sys.stderr)
  157. sys.exit(1)
  158. have_rev = True
  159. cmd_argv.extend(opt.revision)
  160. cmd_argv.append('--')
  161. git_failed = False
  162. bad_rev = False
  163. have_match = False
  164. for project in projects:
  165. try:
  166. p = GitCommand(project,
  167. cmd_argv,
  168. bare=False,
  169. capture_stdout=True,
  170. capture_stderr=True)
  171. except GitError as e:
  172. git_failed = True
  173. out.project('--- project %s ---' % project.relpath)
  174. out.nl()
  175. out.fail('%s', str(e))
  176. out.nl()
  177. continue
  178. if p.Wait() != 0:
  179. # no results
  180. #
  181. if p.stderr:
  182. if have_rev and 'fatal: ambiguous argument' in p.stderr:
  183. bad_rev = True
  184. else:
  185. out.project('--- project %s ---' % project.relpath)
  186. out.nl()
  187. out.fail('%s', p.stderr.strip())
  188. out.nl()
  189. continue
  190. have_match = True
  191. # We cut the last element, to avoid a blank line.
  192. #
  193. r = p.stdout.split('\n')
  194. r = r[0:-1]
  195. if have_rev and full_name:
  196. for line in r:
  197. rev, line = line.split(':', 1)
  198. out.write("%s", rev)
  199. out.write(':')
  200. out.project(project.relpath)
  201. out.write('/')
  202. out.write("%s", line)
  203. out.nl()
  204. elif full_name:
  205. for line in r:
  206. out.project(project.relpath)
  207. out.write('/')
  208. out.write("%s", line)
  209. out.nl()
  210. else:
  211. for line in r:
  212. print(line)
  213. if git_failed:
  214. sys.exit(1)
  215. elif have_match:
  216. sys.exit(0)
  217. elif have_rev and bad_rev:
  218. for r in opt.revision:
  219. print("error: can't search revision %s" % r, file=sys.stderr)
  220. sys.exit(1)
  221. else:
  222. sys.exit(1)