grep.py 7.7 KB

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