/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.49.1 by Jelmer Vernooij
Lazily load commands, saves (some) time loading at bzr startup.
1
# Copyright (C) 2010 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""Print lines matching PATTERN for specified files and revisions."""
18
19
from bzrlib import errors
20
from bzrlib.commands import Command, display_command
21
from bzrlib.option import Option, ListOption
22
23
# FIXME: _parse_levels should be shared with bzrlib.builtins. this is a copy
24
# to avoid the error
25
#   "IllegalUseOfScopeReplacer: ScopeReplacer object '_parse_levels' was used
26
#   incorrectly: Object already cleaned up, did you assign it to another
27
#   variable?: _factory
28
# with lazy import
29
def _parse_levels(s):
30
    try:
31
        return int(s)
32
    except ValueError:
33
        msg = "The levels argument must be an integer."
34
        raise errors.BzrCommandError(msg)
35
36
37
class GrepOptions(object):
38
    """Container to pass around grep options.
39
40
    This class is used as a container to pass around user option and
41
    some other params (like outf) to processing functions. This makes
42
    it easier to add more options as grep evolves.
43
    """
44
    verbose = False
45
    ignore_case = False
46
    no_recursive = False
47
    from_root = False
48
    null = False
49
    levels = None
50
    line_number = False
51
    path_list = None
52
    revision = None
53
    pattern = None
54
    include = None
55
    exclude = None
56
    fixed_string = False
57
    files_with_matches = False
58
    files_without_match = False
59
    color = None
60
    diff = False
61
62
    # derived options
63
    recursive = None
64
    eol_marker = None
65
    patternc = None
66
    sub_patternc = None
67
    print_revno = None
68
    fixed_string = None
69
    outf = None
70
    show_color = False
71
72
73
class cmd_grep(Command):
74
    """Print lines matching PATTERN for specified files and revisions.
75
76
    This command searches the specified files and revisions for a given
77
    pattern.  The pattern is specified as a Python regular expressions[1].
78
79
    If the file name is not specified, the revisions starting with the
80
    current directory are searched recursively. If the revision number is
81
    not specified, the working copy is searched. To search the last committed
82
    revision, use the '-r -1' or '-r last:1' option.
83
84
    Unversioned files are not searched unless explicitly specified on the
85
    command line. Unversioned directores are not searched.
86
87
    When searching a pattern, the output is shown in the 'filepath:string'
88
    format. If a revision is explicitly searched, the output is shown as
89
    'filepath~N:string', where N is the revision number.
90
91
    --include and --exclude options can be used to search only (or exclude
92
    from search) files with base name matches the specified Unix style GLOB
93
    pattern.  The GLOB pattern an use *, ?, and [...] as wildcards, and \\
94
    to quote wildcard or backslash character literally. Note that the glob
95
    pattern is not a regular expression.
96
97
    [1] http://docs.python.org/library/re.html#regular-expression-syntax
98
    """
99
100
    encoding_type = 'replace'
101
    takes_args = ['pattern', 'path*']
102
    takes_options = [
103
        'verbose',
104
        'revision',
105
        Option('color', type=str, argname='when',
106
               help='Show match in color. WHEN is never, always or auto.'),
107
        Option('diff', short_name='p',
108
               help='Grep for pattern in changeset for each revision.'),
109
        ListOption('exclude', type=str, argname='glob', short_name='X',
110
            help="Skip files whose base name matches GLOB."),
111
        ListOption('include', type=str, argname='glob', short_name='I',
112
            help="Search only files whose base name matches GLOB."),
113
        Option('files-with-matches', short_name='l',
114
               help='Print only the name of each input file in '
115
               'which PATTERN is found.'),
116
        Option('files-without-match', short_name='L',
117
               help='Print only the name of each input file in '
118
               'which PATTERN is not found.'),
119
        Option('fixed-string', short_name='F',
120
               help='Interpret PATTERN is a single fixed string (not regex).'),
121
        Option('from-root',
122
               help='Search for pattern starting from the root of the branch. '
123
               '(implies --recursive)'),
124
        Option('ignore-case', short_name='i',
125
               help='ignore case distinctions while matching.'),
126
        Option('levels',
127
           help='Number of levels to display - 0 for all, 1 for collapsed '
128
           '(1 is default).',
129
           argname='N',
130
           type=_parse_levels),
131
        Option('line-number', short_name='n',
132
               help='show 1-based line number.'),
133
        Option('no-recursive',
134
               help="Don't recurse into subdirectories. (default is --recursive)"),
135
        Option('null', short_name='Z',
136
               help='Write an ASCII NUL (\\0) separator '
137
               'between output lines rather than a newline.'),
138
        ]
139
140
141
    @display_command
142
    def run(self, verbose=False, ignore_case=False, no_recursive=False,
143
            from_root=False, null=False, levels=None, line_number=False,
144
            path_list=None, revision=None, pattern=None, include=None,
145
            exclude=None, fixed_string=False, files_with_matches=False,
146
            files_without_match=False, color='never', diff=False):
147
        from bzrlib.plugins.grep import (
148
            grep,
149
            termcolor,
150
            )
151
        import re
152
        if path_list == None:
153
            path_list = ['.']
154
        else:
155
            if from_root:
156
                raise errors.BzrCommandError('cannot specify both --from-root and PATH.')
157
158
        if files_with_matches and files_without_match:
159
            raise errors.BzrCommandError('cannot specify both '
160
                '-l/--files-with-matches and -L/--files-without-matches.')
161
162
        if color not in ['always', 'never', 'auto']:
163
            raise errors.BzrCommandError('Valid values for --color are '
164
                '"always", "never" or "auto".')
165
166
        if levels==None:
167
            levels=1
168
169
        print_revno = False
170
        if revision != None or levels == 0:
171
            # print revision numbers as we may be showing multiple revisions
172
            print_revno = True
173
174
        eol_marker = '\n'
175
        if null:
176
            eol_marker = '\0'
177
178
        if not ignore_case and grep.is_fixed_string(pattern):
179
            # if the pattern isalnum, implicitly use to -F for faster grep
180
            fixed_string = True
181
        elif ignore_case and fixed_string:
182
            # GZ 2010-06-02: Fall back to regexp rather than lowercasing
183
            #                pattern and text which will cause pain later
184
            fixed_string = False
185
            pattern = re.escape(pattern)
186
187
        patternc = None
188
        re_flags = re.MULTILINE
189
        if ignore_case:
190
            re_flags |= re.IGNORECASE
191
192
        if not fixed_string:
193
            patternc = grep.compile_pattern(pattern, re_flags)
194
195
        if color == 'always':
196
            show_color = True
197
        elif color == 'never':
198
            show_color = False
199
        elif color == 'auto':
200
            show_color = termcolor.allow_color()
201
202
        GrepOptions.verbose = verbose
203
        GrepOptions.ignore_case = ignore_case
204
        GrepOptions.no_recursive = no_recursive
205
        GrepOptions.from_root = from_root
206
        GrepOptions.null = null
207
        GrepOptions.levels = levels
208
        GrepOptions.line_number = line_number
209
        GrepOptions.path_list = path_list
210
        GrepOptions.revision = revision
211
        GrepOptions.pattern = pattern
212
        GrepOptions.include = include
213
        GrepOptions.exclude = exclude
214
        GrepOptions.fixed_string = fixed_string
215
        GrepOptions.files_with_matches = files_with_matches
216
        GrepOptions.files_without_match = files_without_match
217
        GrepOptions.color = color
218
        GrepOptions.diff = False
219
220
        GrepOptions.eol_marker = eol_marker
221
        GrepOptions.print_revno = print_revno
222
        GrepOptions.patternc = patternc
223
        GrepOptions.recursive = not no_recursive
224
        GrepOptions.fixed_string = fixed_string
225
        GrepOptions.outf = self.outf
226
        GrepOptions.show_color = show_color
227
228
        if diff == True:
229
            # options not used:
230
            # files_with_matches, files_without_match
231
            # levels(?), line_number, from_root
232
            # include, exclude
233
            # These are silently ignored.
234
            grep.grep_diff(GrepOptions)
235
        elif revision == None:
236
            grep.workingtree_grep(GrepOptions)
237
        else:
238
            grep.versioned_grep(GrepOptions)