grep.py 7.7 KB

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