~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# Copyright (C) 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""Print lines matching PATTERN for specified files and revisions."""

import os
import sys

from bzrlib import errors
from bzrlib.commands import Command, register_command, display_command
from bzrlib.option import Option, ListOption

from bzrlib.lazy_import import lazy_import
lazy_import(globals(), """
import re

from termcolor import allow_color
import grep

import bzrlib
from bzrlib.revisionspec import RevisionSpec
from bzrlib import (
    osutils,
    bzrdir,
    trace,
    )
""")

version_info = (0, 3, 0, 'dev', 0)

# FIXME: _parse_levels should be shared with bzrlib.builtins. this is a copy
# to avoid the error
#   "IllegalUseOfScopeReplacer: ScopeReplacer object '_parse_levels' was used
#   incorrectly: Object already cleaned up, did you assign it to another
#   variable?: _factory
# with lazy import
def _parse_levels(s):
    try:
        return int(s)
    except ValueError:
        msg = "The levels argument must be an integer."
        raise errors.BzrCommandError(msg)


class GrepOptions(object):
    """Container to pass around grep options.

    This class is used as a container to pass around user option and
    some other params (like outf) to processing functions. This makes
    it easier to add more options as grep evolves.
    """
    verbose = False
    ignore_case = False
    no_recursive = False
    from_root = False
    null = False
    levels = None
    line_number = False
    path_list = None
    revision = None
    pattern = None
    include = None
    exclude = None
    fixed_string = False
    files_with_matches = False
    files_without_match = False
    color = None

    # derived options
    recursive = None
    eol_marker = None
    patternc = None
    sub_patternc = None
    print_revno = None
    fixed_string = None
    outf = None
    show_color = False


class cmd_grep(Command):
    """Print lines matching PATTERN for specified files and revisions.

    This command searches the specified files and revisions for a given
    pattern.  The pattern is specified as a Python regular expressions[1].

    If the file name is not specified, the revisions starting with the
    current directory are searched recursively. If the revision number is
    not specified, the working copy is searched. To search the last committed
    revision, use the '-r -1' or '-r last:1' option.

    Unversioned files are not searched unless explicitly specified on the
    command line. Unversioned directores are not searched.

    When searching a pattern, the output is shown in the 'filepath:string'
    format. If a revision is explicitly searched, the output is shown as
    'filepath~N:string', where N is the revision number.

    --include and --exclude options can be used to search only (or exclude
    from search) files with base name matches the specified Unix style GLOB
    pattern.  The GLOB pattern an use *, ?, and [...] as wildcards, and \\
    to quote wildcard or backslash character literally. Note that the glob
    pattern is not a regular expression.

    [1] http://docs.python.org/library/re.html#regular-expression-syntax
    """

    encoding_type = 'replace'
    takes_args = ['pattern', 'path*']
    takes_options = [
        'verbose',
        'revision',
        Option('color', type=str, argname='when',
               help='Show match in color. WHEN is never, always or auto.'),
        ListOption('exclude', type=str, argname='glob', short_name='X',
            help="Skip files whose base name matches GLOB."),
        ListOption('include', type=str, argname='glob', short_name='I',
            help="Search only files whose base name matches GLOB."),
        Option('files-with-matches', short_name='l',
               help='Print only the name of each input file in '
               'which PATTERN is found.'),
        Option('files-without-match', short_name='L',
               help='Print only the name of each input file in '
               'which PATTERN is not found.'),
        Option('fixed-string', short_name='F',
               help='Interpret PATTERN is a single fixed string (not regex).'),
        Option('from-root',
               help='Search for pattern starting from the root of the branch. '
               '(implies --recursive)'),
        Option('ignore-case', short_name='i',
               help='ignore case distinctions while matching.'),
        Option('levels',
           help='Number of levels to display - 0 for all, 1 for collapsed '
           '(1 is default).',
           argname='N',
           type=_parse_levels),
        Option('line-number', short_name='n',
               help='show 1-based line number.'),
        Option('no-recursive',
               help="Don't recurse into subdirectories. (default is --recursive)"),
        Option('null', short_name='Z',
               help='Write an ASCII NUL (\\0) separator '
               'between output lines rather than a newline.'),
        ]


    @display_command
    def run(self, verbose=False, ignore_case=False, no_recursive=False,
            from_root=False, null=False, levels=None, line_number=False,
            path_list=None, revision=None, pattern=None, include=None,
            exclude=None, fixed_string=False, files_with_matches=False,
            files_without_match=False, color='never'):

        if path_list == None:
            path_list = ['.']
        else:
            if from_root:
                raise errors.BzrCommandError('cannot specify both --from-root and PATH.')

        if files_with_matches and files_without_match:
            raise errors.BzrCommandError('cannot specify both '
                '-l/--files-with-matches and -L/--files-without-matches.')

        if color not in ['always', 'never', 'auto']:
            raise errors.BzrCommandError('Valid values for --color are '
                '"always", "never" or "auto".')

        if levels==None:
            levels=1

        print_revno = False
        if revision != None or levels == 0:
            # print revision numbers as we may be showing multiple revisions
            print_revno = True

        eol_marker = '\n'
        if null:
            eol_marker = '\0'

        # if the pattern isalnum, implicitly switch to fixed_string for faster grep
        if grep.is_fixed_string(pattern):
            fixed_string = True

        patternc = None
        re_flags = 0
        if ignore_case:
            re_flags = re.IGNORECASE

        if not fixed_string:
            patternc = grep.compile_pattern(pattern, re_flags)

        if color == 'always':
            show_color = True
        elif color == 'never':
            show_color = False
        elif color == 'auto':
            show_color = allow_color()

        sub_patternc = None
        if show_color:
            sub_pattern = '(' + pattern + ')' # make pattern capturing
            # sub_patternc is used for color display even for fixed_string
            # when ignore_case is set
            sub_patternc = grep.compile_pattern(sub_pattern, re_flags)

        GrepOptions.verbose = verbose
        GrepOptions.ignore_case = ignore_case
        GrepOptions.no_recursive = no_recursive
        GrepOptions.from_root = from_root
        GrepOptions.null = null
        GrepOptions.levels = levels
        GrepOptions.line_number = line_number
        GrepOptions.path_list = path_list
        GrepOptions.revision = revision
        GrepOptions.pattern = pattern
        GrepOptions.include = include
        GrepOptions.exclude = exclude
        GrepOptions.fixed_string = fixed_string
        GrepOptions.files_with_matches = files_with_matches
        GrepOptions.files_without_match = files_without_match
        GrepOptions.color = color

        GrepOptions.eol_marker = eol_marker
        GrepOptions.print_revno = print_revno
        GrepOptions.patternc = patternc
        GrepOptions.sub_patternc = sub_patternc
        GrepOptions.recursive = not no_recursive
        GrepOptions.fixed_string = fixed_string
        GrepOptions.outf = self.outf
        GrepOptions.show_color = show_color

        if revision == None:
            grep.workingtree_grep(GrepOptions)
        else:
            grep.versioned_grep(GrepOptions)


register_command(cmd_grep)

def test_suite():
    from bzrlib.tests import TestUtil

    suite = TestUtil.TestSuite()
    loader = TestUtil.TestLoader()
    testmod_names = [
        'test_grep',
        ]

    suite.addTest(loader.loadTestsFromModuleNames(
            ["%s.%s" % (__name__, tmn) for tmn in testmod_names]))
    return suite