/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.40.10 by Parth Malwankar
assigned copyright to canonical
1
# Copyright (C) 2010 Canonical Ltd
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
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
0.40.147 by Jelmer Vernooij
Fix compatibility with newer versions of bzr: don't use relative imports in lazy imports, and import features from bzrlib.tests.features.
17
from __future__ import absolute_import
18
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
19
import re
0.47.1 by Martin
Implement whole text search for fast failure on no match
20
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
21
from ...lazy_import import lazy_import
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
22
lazy_import(globals(), """
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
23
from fnmatch import fnmatch
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
24
6667.2.1 by Jelmer Vernooij
Some cleanup; s/BzrDir/ControlDir/, remove some unused imports.
25
from breezy._termcolor import color_string, FG
0.43.4 by Parth Malwankar
initial support for color for fixed string grep.
26
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
27
from breezy import (
6667.2.1 by Jelmer Vernooij
Some cleanup; s/BzrDir/ControlDir/, remove some unused imports.
28
    controldir,
0.48.5 by Parth Malwankar
fixed imports
29
    diff,
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
30
    errors,
31
    lazy_regex,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
32
    revision as _mod_revision,
33
    )
34
""")
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
35
from breezy import (
0.40.47 by Parth Malwankar
fixes bug #531336. binary files are now skipped.
36
    osutils,
37
    trace,
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
38
    )
6800.1.5 by Jelmer Vernooij
Fix more imports.
39
from breezy.revisionspec import (
40
    RevisionSpec,
41
    RevisionSpec_revid,
42
    RevisionSpec_revno,
43
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
44
from breezy.sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
45
    BytesIO,
46
    )
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
47
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
48
_user_encoding = osutils.get_user_encoding()
49
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
50
0.40.95 by Parth Malwankar
faster mainline rev grep
51
class _RevisionNotLinear(Exception):
52
    """Raised when a revision is not on left-hand history."""
53
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
54
0.40.95 by Parth Malwankar
faster mainline rev grep
55
def _rev_on_mainline(rev_tuple):
56
    """returns True is rev tuple is on mainline"""
57
    if len(rev_tuple) == 1:
58
        return True
59
    return rev_tuple[1] == 0 and rev_tuple[2] == 0
60
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
61
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
62
# NOTE: _linear_view_revisions is basided on
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
63
# breezy.log._linear_view_revisions.
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
64
# This should probably be a common public API
0.40.95 by Parth Malwankar
faster mainline rev grep
65
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
0.40.106 by Parth Malwankar
fixed error in dotted rev reverse search.
66
    # requires that start is older than end
0.40.95 by Parth Malwankar
faster mainline rev grep
67
    repo = branch.repository
6531.3.6 by Jelmer Vernooij
Use iter_lefthand_ancestry rather than removed iter_reverse_revision_history.
68
    graph = repo.get_graph()
6531.3.7 by Jelmer Vernooij
Formatting.
69
    for revision_id in graph.iter_lefthand_ancestry(
70
            end_rev_id, (_mod_revision.NULL_REVISION, )):
0.40.95 by Parth Malwankar
faster mainline rev grep
71
        revno = branch.revision_id_to_dotted_revno(revision_id)
72
        revno_str = '.'.join(str(n) for n in revno)
73
        if revision_id == start_rev_id:
74
            yield revision_id, revno_str, 0
75
            break
76
        yield revision_id, revno_str, 0
77
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
78
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
79
# NOTE: _graph_view_revisions is copied from
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
80
# breezy.log._graph_view_revisions.
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
81
# This should probably be a common public API
82
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
83
                          rebase_initial_depths=True):
84
    """Calculate revisions to view including merges, newest to oldest.
85
86
    :param branch: the branch
87
    :param start_rev_id: the lower revision-id
88
    :param end_rev_id: the upper revision-id
89
    :param rebase_initial_depth: should depths be rebased until a mainline
90
      revision is found?
91
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
92
    """
0.40.106 by Parth Malwankar
fixed error in dotted rev reverse search.
93
    # requires that start is older than end
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
94
    view_revisions = branch.iter_merge_sorted_revisions(
95
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
96
        stop_rule="with-merges")
97
    if not rebase_initial_depths:
98
        for (rev_id, merge_depth, revno, end_of_merge
99
             ) in view_revisions:
100
            yield rev_id, '.'.join(map(str, revno)), merge_depth
101
    else:
102
        # We're following a development line starting at a merged revision.
103
        # We need to adjust depths down by the initial depth until we find
104
        # a depth less than it. Then we use that depth as the adjustment.
105
        # If and when we reach the mainline, depth adjustment ends.
106
        depth_adjustment = None
107
        for (rev_id, merge_depth, revno, end_of_merge
108
             ) in view_revisions:
109
            if depth_adjustment is None:
110
                depth_adjustment = merge_depth
111
            if depth_adjustment:
112
                if merge_depth < depth_adjustment:
113
                    # From now on we reduce the depth adjustement, this can be
114
                    # surprising for users. The alternative requires two passes
115
                    # which breaks the fast display of the first revision
116
                    # though.
117
                    depth_adjustment = merge_depth
118
                merge_depth -= depth_adjustment
119
            yield rev_id, '.'.join(map(str, revno)), merge_depth
120
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
121
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
122
def compile_pattern(pattern, flags=0):
123
    patternc = None
124
    try:
125
        # use python's re.compile as we need to catch re.error in case of bad pattern
126
        lazy_regex.reset_compile()
127
        patternc = re.compile(pattern, flags)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
128
    except re.error as e:
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
129
        raise errors.BzrError("Invalid pattern: '%s'" % pattern)
130
    return patternc
131
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
132
0.40.86 by Parth Malwankar
the check for implicit fixed_string now allows for spaces.
133
def is_fixed_string(s):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
134
    if re.match("^([A-Za-z0-9_]|\\s)*$", s):
0.40.86 by Parth Malwankar
the check for implicit fixed_string now allows for spaces.
135
        return True
136
    return False
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
137
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
138
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
139
class _GrepDiffOutputter(object):
140
    """Precalculate formatting based on options given for diff grep.
141
    """
6531.3.8 by Jelmer Vernooij
Move color feature into bzrlib.tests.features.
142
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
143
    def __init__(self, opts):
0.48.8 by Parth Malwankar
colored header for diff grep output
144
        self.opts = opts
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
145
        self.outf = opts.outf
146
        if opts.show_color:
147
            if opts.fixed_string:
7027.9.1 by Jelmer Vernooij
Fix all but one remaining grep tests.
148
                self._old = opts.pattern
149
                self._new = color_string(opts.pattern, FG.BOLD_RED)
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
150
                self.get_writer = self._get_writer_fixed_highlighted
151
            else:
152
                flags = opts.patternc.flags
7143.15.2 by Jelmer Vernooij
Run autopep8.
153
                self._sub = re.compile(
154
                    opts.pattern.join(("((?:", ")+)")), flags).sub
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
155
                self._highlight = color_string("\\1", FG.BOLD_RED)
156
                self.get_writer = self._get_writer_regexp_highlighted
157
        else:
158
            self.get_writer = self._get_writer_plain
159
0.48.8 by Parth Malwankar
colored header for diff grep output
160
    def get_file_header_writer(self):
161
        """Get function for writing file headers"""
162
        write = self.outf.write
163
        eol_marker = self.opts.eol_marker
7143.15.2 by Jelmer Vernooij
Run autopep8.
164
0.48.8 by Parth Malwankar
colored header for diff grep output
165
        def _line_writer(line):
166
            write(line + eol_marker)
7143.15.2 by Jelmer Vernooij
Run autopep8.
167
0.48.8 by Parth Malwankar
colored header for diff grep output
168
        def _line_writer_color(line):
169
            write(FG.BOLD_MAGENTA + line + FG.NONE + eol_marker)
170
        if self.opts.show_color:
171
            return _line_writer_color
172
        else:
173
            return _line_writer
174
        return _line_writer
175
176
    def get_revision_header_writer(self):
177
        """Get function for writing revno lines"""
178
        write = self.outf.write
179
        eol_marker = self.opts.eol_marker
7143.15.2 by Jelmer Vernooij
Run autopep8.
180
0.48.8 by Parth Malwankar
colored header for diff grep output
181
        def _line_writer(line):
182
            write(line + eol_marker)
7143.15.2 by Jelmer Vernooij
Run autopep8.
183
0.48.8 by Parth Malwankar
colored header for diff grep output
184
        def _line_writer_color(line):
185
            write(FG.BOLD_BLUE + line + FG.NONE + eol_marker)
186
        if self.opts.show_color:
187
            return _line_writer_color
188
        else:
189
            return _line_writer
190
        return _line_writer
191
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
192
    def _get_writer_plain(self):
193
        """Get function for writing uncoloured output"""
194
        write = self.outf.write
0.48.8 by Parth Malwankar
colored header for diff grep output
195
        eol_marker = self.opts.eol_marker
7143.15.2 by Jelmer Vernooij
Run autopep8.
196
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
197
        def _line_writer(line):
0.48.8 by Parth Malwankar
colored header for diff grep output
198
            write(line + eol_marker)
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
199
        return _line_writer
200
201
    def _get_writer_regexp_highlighted(self):
202
        """Get function for writing output with regexp match highlighted"""
203
        _line_writer = self._get_writer_plain()
204
        sub, highlight = self._sub, self._highlight
7143.15.2 by Jelmer Vernooij
Run autopep8.
205
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
206
        def _line_writer_regexp_highlighted(line):
207
            """Write formatted line with matched pattern highlighted"""
208
            return _line_writer(line=sub(highlight, line))
209
        return _line_writer_regexp_highlighted
210
211
    def _get_writer_fixed_highlighted(self):
212
        """Get function for writing output with search string highlighted"""
213
        _line_writer = self._get_writer_plain()
214
        old, new = self._old, self._new
7143.15.2 by Jelmer Vernooij
Run autopep8.
215
0.48.7 by Parth Malwankar
initial outputter support for diff_grep
216
        def _line_writer_fixed_highlighted(line):
217
            """Write formatted line with string searched for highlighted"""
218
            return _line_writer(line=line.replace(old, new))
219
        return _line_writer_fixed_highlighted
220
221
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
222
def grep_diff(opts):
223
    wt, branch, relpath = \
6667.2.1 by Jelmer Vernooij
Some cleanup; s/BzrDir/ControlDir/, remove some unused imports.
224
        controldir.ControlDir.open_containing_tree_or_branch('.')
6754.8.4 by Jelmer Vernooij
Use new context stuff.
225
    with branch.lock_read():
0.48.3 by Parth Malwankar
for grep_diff, if rev is not specified, last is used as start.
226
        if opts.revision:
227
            start_rev = opts.revision[0]
228
        else:
0.48.9 by Parth Malwankar
added inital test for 'grep -p'
229
            # if no revision is sepcified for diff grep we grep all changesets.
230
            opts.revision = [RevisionSpec.from_string('revno:1'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
231
                             RevisionSpec.from_string('last:1')]
0.48.3 by Parth Malwankar
for grep_diff, if rev is not specified, last is used as start.
232
            start_rev = opts.revision[0]
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
233
        start_revid = start_rev.as_revision_id(branch)
6973.14.6 by Jelmer Vernooij
Fix some more tests.
234
        if start_revid == b'null:':
0.48.4 by Parth Malwankar
diff grep now works.
235
            return
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
236
        srevno_tuple = branch.revision_id_to_dotted_revno(start_revid)
237
        if len(opts.revision) == 2:
238
            end_rev = opts.revision[1]
239
            end_revid = end_rev.as_revision_id(branch)
6531.3.8 by Jelmer Vernooij
Move color feature into bzrlib.tests.features.
240
            if end_revid is None:
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
241
                end_revno, end_revid = branch.last_revision_info()
242
            erevno_tuple = branch.revision_id_to_dotted_revno(end_revid)
243
7143.15.2 by Jelmer Vernooij
Run autopep8.
244
            grep_mainline = (_rev_on_mainline(srevno_tuple)
245
                             and _rev_on_mainline(erevno_tuple))
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
246
247
            # ensure that we go in reverse order
248
            if srevno_tuple > erevno_tuple:
249
                srevno_tuple, erevno_tuple = erevno_tuple, srevno_tuple
250
                start_revid, end_revid = end_revid, start_revid
251
252
            # Optimization: Traversing the mainline in reverse order is much
253
            # faster when we don't want to look at merged revs. We try this
254
            # with _linear_view_revisions. If all revs are to be grepped we
255
            # use the slower _graph_view_revisions
7143.15.2 by Jelmer Vernooij
Run autopep8.
256
            if opts.levels == 1 and grep_mainline:
257
                given_revs = _linear_view_revisions(
258
                    branch, start_revid, end_revid)
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
259
            else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
260
                given_revs = _graph_view_revisions(
261
                    branch, start_revid, end_revid)
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
262
        else:
263
            # We do an optimization below. For grepping a specific revison
264
            # We don't need to call _graph_view_revisions which is slow.
265
            # We create the start_rev_tuple for only that specific revision.
266
            # _graph_view_revisions is used only for revision range.
267
            start_revno = '.'.join(map(str, srevno_tuple))
268
            start_rev_tuple = (start_revid, start_revno, 0)
269
            given_revs = [start_rev_tuple]
270
        repo = branch.repository
7143.15.2 by Jelmer Vernooij
Run autopep8.
271
        diff_pattern = re.compile(
272
            b"^[+\\-].*(" + opts.pattern.encode(_user_encoding) + b")")
7027.9.1 by Jelmer Vernooij
Fix all but one remaining grep tests.
273
        file_pattern = re.compile(b"=== (modified|added|removed) file '.*'")
0.48.8 by Parth Malwankar
colored header for diff grep output
274
        outputter = _GrepDiffOutputter(opts)
275
        writeline = outputter.get_writer()
276
        writerevno = outputter.get_revision_header_writer()
277
        writefileheader = outputter.get_file_header_writer()
0.48.11 by Parth Malwankar
unicode decode fix for diff grep.
278
        file_encoding = _user_encoding
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
279
        for revid, revno, merge_depth in given_revs:
280
            if opts.levels == 1 and merge_depth != 0:
281
                # with level=1 show only top level
282
                continue
283
7143.15.2 by Jelmer Vernooij
Run autopep8.
284
            rev_spec = RevisionSpec_revid.from_string(
285
                "revid:" + revid.decode('utf-8'))
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
286
            new_rev = repo.get_revision(revid)
287
            new_tree = rev_spec.as_tree(branch)
288
            if len(new_rev.parent_ids) == 0:
289
                ancestor_id = _mod_revision.NULL_REVISION
290
            else:
291
                ancestor_id = new_rev.parent_ids[0]
292
            old_tree = repo.revision_tree(ancestor_id)
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
293
            s = BytesIO()
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
294
            diff.show_diff_trees(old_tree, new_tree, s,
7143.15.2 by Jelmer Vernooij
Run autopep8.
295
                                 old_label='', new_label='')
0.48.4 by Parth Malwankar
diff grep now works.
296
            display_revno = True
297
            display_file = False
298
            file_header = None
299
            text = s.getvalue()
0.48.6 by Parth Malwankar
removed fixed_string condition for diff grep
300
            for line in text.splitlines():
301
                if file_pattern.search(line):
302
                    file_header = line
303
                    display_file = True
0.48.11 by Parth Malwankar
unicode decode fix for diff grep.
304
                elif diff_pattern.search(line):
0.48.6 by Parth Malwankar
removed fixed_string condition for diff grep
305
                    if display_revno:
0.48.10 by Parth Malwankar
more tests for 'grep --diff'
306
                        writerevno("=== revno:%s ===" % (revno,))
0.48.6 by Parth Malwankar
removed fixed_string condition for diff grep
307
                        display_revno = False
308
                    if display_file:
7143.15.2 by Jelmer Vernooij
Run autopep8.
309
                        writefileheader(
310
                            "  %s" % (file_header.decode(file_encoding, 'replace'),))
0.48.6 by Parth Malwankar
removed fixed_string condition for diff grep
311
                        display_file = False
0.48.11 by Parth Malwankar
unicode decode fix for diff grep.
312
                    line = line.decode(file_encoding, 'replace')
313
                    writeline("    %s" % (line,))
0.48.2 by Parth Malwankar
intermediate checkin. we now show diff with -p option.
314
315
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
316
def versioned_grep(opts):
0.40.131 by Parth Malwankar
bzr grep now allows grepping with -r even when no tree exists.
317
    wt, branch, relpath = \
6667.2.1 by Jelmer Vernooij
Some cleanup; s/BzrDir/ControlDir/, remove some unused imports.
318
        controldir.ControlDir.open_containing_tree_or_branch('.')
6754.8.4 by Jelmer Vernooij
Use new context stuff.
319
    with branch.lock_read():
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
320
        start_rev = opts.revision[0]
0.40.131 by Parth Malwankar
bzr grep now allows grepping with -r even when no tree exists.
321
        start_revid = start_rev.as_revision_id(branch)
6531.3.8 by Jelmer Vernooij
Move color feature into bzrlib.tests.features.
322
        if start_revid is None:
0.40.95 by Parth Malwankar
faster mainline rev grep
323
            start_rev = RevisionSpec_revno.from_string("revno:1")
0.40.131 by Parth Malwankar
bzr grep now allows grepping with -r even when no tree exists.
324
            start_revid = start_rev.as_revision_id(branch)
325
        srevno_tuple = branch.revision_id_to_dotted_revno(start_revid)
0.40.88 by Parth Malwankar
updated to avoid relocking.
326
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
327
        if len(opts.revision) == 2:
328
            end_rev = opts.revision[1]
0.40.131 by Parth Malwankar
bzr grep now allows grepping with -r even when no tree exists.
329
            end_revid = end_rev.as_revision_id(branch)
6531.3.8 by Jelmer Vernooij
Move color feature into bzrlib.tests.features.
330
            if end_revid is None:
0.40.131 by Parth Malwankar
bzr grep now allows grepping with -r even when no tree exists.
331
                end_revno, end_revid = branch.last_revision_info()
332
            erevno_tuple = branch.revision_id_to_dotted_revno(end_revid)
0.40.95 by Parth Malwankar
faster mainline rev grep
333
7143.15.2 by Jelmer Vernooij
Run autopep8.
334
            grep_mainline = (_rev_on_mainline(srevno_tuple)
335
                             and _rev_on_mainline(erevno_tuple))
0.40.106 by Parth Malwankar
fixed error in dotted rev reverse search.
336
337
            # ensure that we go in reverse order
338
            if srevno_tuple > erevno_tuple:
339
                srevno_tuple, erevno_tuple = erevno_tuple, srevno_tuple
340
                start_revid, end_revid = end_revid, start_revid
0.40.97 by Parth Malwankar
fixed caching bug for rev range.
341
0.40.95 by Parth Malwankar
faster mainline rev grep
342
            # Optimization: Traversing the mainline in reverse order is much
343
            # faster when we don't want to look at merged revs. We try this
344
            # with _linear_view_revisions. If all revs are to be grepped we
345
            # use the slower _graph_view_revisions
6531.3.9 by Jelmer Vernooij
Remove broken tests..
346
            if opts.levels == 1 and grep_mainline:
7143.15.2 by Jelmer Vernooij
Run autopep8.
347
                given_revs = _linear_view_revisions(
348
                    branch, start_revid, end_revid)
0.40.95 by Parth Malwankar
faster mainline rev grep
349
            else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
350
                given_revs = _graph_view_revisions(
351
                    branch, start_revid, end_revid)
0.40.88 by Parth Malwankar
updated to avoid relocking.
352
        else:
0.40.94 by Parth Malwankar
code cleanup. moved start_rev_tuple into if cond that uses it.
353
            # We do an optimization below. For grepping a specific revison
354
            # We don't need to call _graph_view_revisions which is slow.
355
            # We create the start_rev_tuple for only that specific revision.
356
            # _graph_view_revisions is used only for revision range.
357
            start_revno = '.'.join(map(str, srevno_tuple))
358
            start_rev_tuple = (start_revid, start_revno, 0)
0.40.88 by Parth Malwankar
updated to avoid relocking.
359
            given_revs = [start_rev_tuple]
360
0.46.7 by Martin
Move line writing function up the stack so it lasts the whole operation, and clean up some params
361
        # GZ 2010-06-02: Shouldn't be smuggling this on opts, but easy for now
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
362
        opts.outputter = _Outputter(opts, use_cache=True)
0.46.7 by Martin
Move line writing function up the stack so it lasts the whole operation, and clean up some params
363
0.40.88 by Parth Malwankar
updated to avoid relocking.
364
        for revid, revno, merge_depth in given_revs:
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
365
            if opts.levels == 1 and merge_depth != 0:
0.40.88 by Parth Malwankar
updated to avoid relocking.
366
                # with level=1 show only top level
367
                continue
368
7143.15.2 by Jelmer Vernooij
Run autopep8.
369
            rev = RevisionSpec_revid.from_string(
370
                "revid:" + revid.decode('utf-8'))
0.40.131 by Parth Malwankar
bzr grep now allows grepping with -r even when no tree exists.
371
            tree = rev.as_tree(branch)
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
372
            for path in opts.path_list:
6874.2.5 by Jelmer Vernooij
Fix grep.
373
                tree_path = osutils.pathjoin(relpath, path)
374
                if not tree.has_filename(tree_path):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
375
                    trace.warning("Skipped unknown file '%s'.", path)
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
376
                    continue
377
378
                if osutils.isdir(path):
379
                    path_prefix = path
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
380
                    dir_grep(tree, path, relpath, opts, revno, path_prefix)
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
381
                else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
382
                    versioned_file_grep(
383
                        tree, tree_path, '.', path, opts, revno)
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
384
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
385
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
386
def workingtree_grep(opts):
7143.15.2 by Jelmer Vernooij
Run autopep8.
387
    revno = opts.print_revno = None  # for working tree set revno to None
0.40.69 by Parth Malwankar
reduced lock/unlock
388
389
    tree, branch, relpath = \
6667.2.1 by Jelmer Vernooij
Some cleanup; s/BzrDir/ControlDir/, remove some unused imports.
390
        controldir.ControlDir.open_containing_tree_or_branch('.')
0.40.130 by Parth Malwankar
grep in a branch with no tree does not throw stack trace (#572658)
391
    if not tree:
0.40.131 by Parth Malwankar
bzr grep now allows grepping with -r even when no tree exists.
392
        msg = ('Cannot search working tree. Working tree not found.\n'
7143.15.2 by Jelmer Vernooij
Run autopep8.
393
               'To search for specific revision in history use the -r option.')
0.40.130 by Parth Malwankar
grep in a branch with no tree does not throw stack trace (#572658)
394
        raise errors.BzrCommandError(msg)
395
0.46.7 by Martin
Move line writing function up the stack so it lasts the whole operation, and clean up some params
396
    # GZ 2010-06-02: Shouldn't be smuggling this on opts, but easy for now
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
397
    opts.outputter = _Outputter(opts)
0.46.7 by Martin
Move line writing function up the stack so it lasts the whole operation, and clean up some params
398
6754.8.4 by Jelmer Vernooij
Use new context stuff.
399
    with tree.lock_read():
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
400
        for path in opts.path_list:
0.40.69 by Parth Malwankar
reduced lock/unlock
401
            if osutils.isdir(path):
402
                path_prefix = path
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
403
                dir_grep(tree, path, relpath, opts, revno, path_prefix)
0.40.69 by Parth Malwankar
reduced lock/unlock
404
            else:
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
405
                with open(path, 'rb') as f:
406
                    _file_grep(f.read(), path, opts, revno)
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
407
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
408
0.40.74 by Parth Malwankar
optimization. --include/exclude are checked before reading the file.
409
def _skip_file(include, exclude, path):
410
    if include and not _path_in_glob_list(path, include):
411
        return True
412
    if exclude and _path_in_glob_list(path, exclude):
413
        return True
414
    return False
415
416
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
417
def dir_grep(tree, path, relpath, opts, revno, path_prefix):
0.40.60 by Parth Malwankar
'binary file skipped' warning is only shown with --verbose flag
418
    # setup relpath to open files relative to cwd
419
    rpath = relpath
420
    if relpath:
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
421
        rpath = osutils.pathjoin('..', relpath)
0.40.60 by Parth Malwankar
'binary file skipped' warning is only shown with --verbose flag
422
423
    from_dir = osutils.pathjoin(relpath, path)
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
424
    if opts.from_root:
0.40.60 by Parth Malwankar
'binary file skipped' warning is only shown with --verbose flag
425
        # start searching recursively from root
6874.2.1 by Jelmer Vernooij
Make Tree.iter_files_bytes() take paths rather than file_ids.
426
        from_dir = None
427
        recursive = True
0.40.60 by Parth Malwankar
'binary file skipped' warning is only shown with --verbose flag
428
0.40.85 by Parth Malwankar
optimized versioned grep to use iter_files_bytes.
429
    to_grep = []
0.40.92 by Parth Malwankar
performance tweaks to core cached result print loop.
430
    to_grep_append = to_grep.append
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
431
    # GZ 2010-06-05: The cache dict used to be recycled every call to dir_grep
432
    #                and hits manually refilled. Could do this again if it was
433
    #                for a good reason, otherwise cache might want purging.
434
    outputter = opts.outputter
0.40.69 by Parth Malwankar
reduced lock/unlock
435
    for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
7143.15.2 by Jelmer Vernooij
Run autopep8.
436
                                                     from_dir=from_dir, recursive=opts.recursive):
0.40.69 by Parth Malwankar
reduced lock/unlock
437
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
438
        if _skip_file(opts.include, opts.exclude, fp):
0.40.74 by Parth Malwankar
optimization. --include/exclude are checked before reading the file.
439
            continue
440
0.40.69 by Parth Malwankar
reduced lock/unlock
441
        if fc == 'V' and fkind == 'file':
6928.1.1 by Jelmer Vernooij
Pass in correct paths in grep.
442
            tree_path = osutils.pathjoin(from_dir if from_dir else '', fp)
443
            if revno is not None:
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
444
                # If old result is valid, print results immediately.
445
                # Otherwise, add file info to to_grep so that the
446
                # loop later will get chunks and grep them
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
447
                cache_id = tree.get_file_revision(tree_path)
0.46.11 by Martin
Add method to outputter for writing cached lines
448
                if cache_id in outputter.cache:
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
449
                    # GZ 2010-06-05: Not really sure caching and re-outputting
450
                    #                the old path is really the right thing,
451
                    #                but it's what the old code seemed to do
0.46.11 by Martin
Add method to outputter for writing cached lines
452
                    outputter.write_cached_lines(cache_id, revno)
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
453
                else:
6928.1.1 by Jelmer Vernooij
Pass in correct paths in grep.
454
                    to_grep_append((tree_path, (fp, tree_path)))
0.40.69 by Parth Malwankar
reduced lock/unlock
455
            else:
456
                # we are grepping working tree.
6531.3.8 by Jelmer Vernooij
Move color feature into bzrlib.tests.features.
457
                if from_dir is None:
0.40.69 by Parth Malwankar
reduced lock/unlock
458
                    from_dir = '.'
459
460
                path_for_file = osutils.pathjoin(tree.basedir, from_dir, fp)
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
461
                if opts.files_with_matches or opts.files_without_match:
0.40.116 by Parth Malwankar
optimization for wtree list-only grep to avoid full file read.
462
                    # Optimize for wtree list-only as we don't need to read the
463
                    # entire file
7027.9.1 by Jelmer Vernooij
Fix all but one remaining grep tests.
464
                    with open(path_for_file, 'rb', buffering=4096) as file:
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
465
                        _file_grep_list_only_wtree(file, fp, opts, path_prefix)
0.40.121 by Parth Malwankar
initial implementation of -L/--files-without-matches. no tests.
466
                else:
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
467
                    with open(path_for_file, 'rb') as f:
468
                        _file_grep(f.read(), fp, opts, revno, path_prefix)
0.40.43 by Parth Malwankar
moved cmd_grep._grep_dir to grep.dir_grep
469
7143.15.2 by Jelmer Vernooij
Run autopep8.
470
    if revno is not None:  # grep versioned files
6928.1.1 by Jelmer Vernooij
Pass in correct paths in grep.
471
        for (path, tree_path), chunks in tree.iter_files_bytes(to_grep):
0.40.85 by Parth Malwankar
optimized versioned grep to use iter_files_bytes.
472
            path = _make_display_path(relpath, path)
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
473
            _file_grep(b''.join(chunks), path, opts, revno, path_prefix,
7143.15.2 by Jelmer Vernooij
Run autopep8.
474
                       tree.get_file_revision(tree_path))
0.40.43 by Parth Malwankar
moved cmd_grep._grep_dir to grep.dir_grep
475
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
476
0.41.8 by Parth Malwankar
code cleanup.
477
def _make_display_path(relpath, path):
478
    """Return path string relative to user cwd.
0.40.42 by Parth Malwankar
fix to make grep paths relative to cwd
479
0.41.8 by Parth Malwankar
code cleanup.
480
    Take tree's 'relpath' and user supplied 'path', and return path
481
    that can be displayed to the user.
482
    """
0.40.15 by Parth Malwankar
some fixes and test updates
483
    if relpath:
0.40.52 by Parth Malwankar
code cleanup and documentation
484
        # update path so to display it w.r.t cwd
485
        # handle windows slash separator
0.40.20 by Parth Malwankar
used path functions from bzrlib.osutils
486
        path = osutils.normpath(osutils.pathjoin(relpath, path))
0.40.22 by Parth Malwankar
fixed display path formatting on windows
487
        path = path.replace('\\', '/')
488
        path = path.replace(relpath + '/', '', 1)
0.41.8 by Parth Malwankar
code cleanup.
489
    return path
490
491
7143.15.2 by Jelmer Vernooij
Run autopep8.
492
def versioned_file_grep(tree, tree_path, relpath, path, opts, revno, path_prefix=None):
0.41.10 by Parth Malwankar
code cleanup. added comments. path adjustment is now done
493
    """Create a file object for the specified id and pass it on to _file_grep.
494
    """
495
496
    path = _make_display_path(relpath, path)
6874.2.5 by Jelmer Vernooij
Fix grep.
497
    file_text = tree.get_file_text(tree_path)
0.46.7 by Martin
Move line writing function up the stack so it lasts the whole operation, and clean up some params
498
    _file_grep(file_text, path, opts, revno, path_prefix)
0.41.21 by Parth Malwankar
include/exclude working now. tests not added.
499
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
500
0.41.21 by Parth Malwankar
include/exclude working now. tests not added.
501
def _path_in_glob_list(path, glob_list):
502
    for glob in glob_list:
503
        if fnmatch(path, glob):
0.46.19 by Martin
Minor pokes, fixes a bug with working tree optimisation and binary files
504
            return True
505
    return False
0.41.12 by Parth Malwankar
initial support for working tree grep (no test cases yet!)
506
0.40.117 by Parth Malwankar
cosmetic fix. added two lines between top level functions.
507
0.46.7 by Martin
Move line writing function up the stack so it lasts the whole operation, and clean up some params
508
def _file_grep_list_only_wtree(file, path, opts, path_prefix=None):
0.40.116 by Parth Malwankar
optimization for wtree list-only grep to avoid full file read.
509
    # test and skip binary files
7027.9.1 by Jelmer Vernooij
Fix all but one remaining grep tests.
510
    if b'\x00' in file.read(1024):
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
511
        if opts.verbose:
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
512
            trace.warning("Binary file '%s' skipped.", path)
0.46.19 by Martin
Minor pokes, fixes a bug with working tree optimisation and binary files
513
        return
0.40.118 by Parth Malwankar
further optimization of _file_grep_list_only_wtree.
514
7143.15.2 by Jelmer Vernooij
Run autopep8.
515
    file.seek(0)  # search from beginning
0.40.118 by Parth Malwankar
further optimization of _file_grep_list_only_wtree.
516
517
    found = False
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
518
    if opts.fixed_string:
519
        pattern = opts.pattern.encode(_user_encoding, 'replace')
0.46.1 by Martin
Make -Fi use regexps for re.IGNORECASE rather than double str.lower
520
        for line in file:
521
            if pattern in line:
522
                found = True
523
                break
7143.15.2 by Jelmer Vernooij
Run autopep8.
524
    else:  # not fixed_string
0.40.116 by Parth Malwankar
optimization for wtree list-only grep to avoid full file read.
525
        for line in file:
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
526
            if opts.patternc.search(line):
0.40.118 by Parth Malwankar
further optimization of _file_grep_list_only_wtree.
527
                found = True
0.40.116 by Parth Malwankar
optimization for wtree list-only grep to avoid full file read.
528
                break
529
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
530
    if (opts.files_with_matches and found) or \
7143.15.2 by Jelmer Vernooij
Run autopep8.
531
            (opts.files_without_match and not found):
0.40.118 by Parth Malwankar
further optimization of _file_grep_list_only_wtree.
532
        if path_prefix and path_prefix != '.':
533
            # user has passed a dir arg, show that as result prefix
534
            path = osutils.pathjoin(path_prefix, path)
0.46.18 by Martin
Fix another, previously existing issue with colour and match-only
535
        opts.outputter.get_writer(path, None, None)()
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
536
537
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
538
class _Outputter(object):
539
    """Precalculate formatting based on options given
540
541
    The idea here is to do this work only once per run, and finally return a
542
    function that will do the minimum amount possible for each match.
0.46.3 by Martin
Start moving formatting setup out of _file_grep, only for files_with_matches so far
543
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
544
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
545
    def __init__(self, opts, use_cache=False):
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
546
        self.outf = opts.outf
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
547
        if use_cache:
548
            # self.cache is used to cache results for dir grep based on fid.
549
            # If the fid is does not change between results, it means that
550
            # the result will be the same apart from revno. In such a case
551
            # we avoid getting file chunks from repo and grepping. The result
552
            # is just printed by replacing old revno with new one.
553
            self.cache = {}
554
        else:
555
            self.cache = None
0.46.17 by Martin
Fix previously untested issue with colour and match-only, and test a related issue
556
        no_line = opts.files_with_matches or opts.files_without_match
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
557
558
        if opts.show_color:
0.46.17 by Martin
Fix previously untested issue with colour and match-only, and test a related issue
559
            if no_line:
560
                self.get_writer = self._get_writer_plain
561
            elif opts.fixed_string:
7027.9.1 by Jelmer Vernooij
Fix all but one remaining grep tests.
562
                self._old = opts.pattern
563
                self._new = color_string(opts.pattern, FG.BOLD_RED)
0.46.17 by Martin
Fix previously untested issue with colour and match-only, and test a related issue
564
                self.get_writer = self._get_writer_fixed_highlighted
565
            else:
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
566
                flags = opts.patternc.flags
7143.15.2 by Jelmer Vernooij
Run autopep8.
567
                self._sub = re.compile(
568
                    opts.pattern.join(("((?:", ")+)")), flags).sub
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
569
                self._highlight = color_string("\\1", FG.BOLD_RED)
570
                self.get_writer = self._get_writer_regexp_highlighted
571
            path_start = FG.MAGENTA
0.46.17 by Martin
Fix previously untested issue with colour and match-only, and test a related issue
572
            path_end = FG.NONE
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
573
            sep = color_string(':', FG.BOLD_CYAN)
574
            rev_sep = color_string('~', FG.BOLD_YELLOW)
575
        else:
576
            self.get_writer = self._get_writer_plain
0.46.17 by Martin
Fix previously untested issue with colour and match-only, and test a related issue
577
            path_start = path_end = ""
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
578
            sep = ":"
579
            rev_sep = "~"
580
581
        parts = [path_start, "%(path)s"]
0.46.3 by Martin
Start moving formatting setup out of _file_grep, only for files_with_matches so far
582
        if opts.print_revno:
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
583
            parts.extend([rev_sep, "%(revno)s"])
0.46.13 by Martin
Split format string into two parts for non-cached operations too
584
        self._format_initial = "".join(parts)
585
        parts = []
0.46.17 by Martin
Fix previously untested issue with colour and match-only, and test a related issue
586
        if no_line:
587
            if not opts.print_revno:
588
                parts.append(path_end)
589
        else:
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
590
            if opts.line_number:
0.46.13 by Martin
Split format string into two parts for non-cached operations too
591
                parts.extend([sep, "%(lineno)s"])
592
            parts.extend([sep, "%(line)s"])
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
593
        parts.append(opts.eol_marker)
0.46.19 by Martin
Minor pokes, fixes a bug with working tree optimisation and binary files
594
        self._format_perline = "".join(parts)
0.46.7 by Martin
Move line writing function up the stack so it lasts the whole operation, and clean up some params
595
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
596
    def _get_writer_plain(self, path, revno, cache_id):
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
597
        """Get function for writing uncoloured output"""
0.46.13 by Martin
Split format string into two parts for non-cached operations too
598
        per_line = self._format_perline
7143.15.2 by Jelmer Vernooij
Run autopep8.
599
        start = self._format_initial % {"path": path, "revno": revno}
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
600
        write = self.outf.write
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
601
        if self.cache is not None and cache_id is not None:
602
            result_list = []
603
            self.cache[cache_id] = path, result_list
604
            add_to_cache = result_list.append
7143.15.2 by Jelmer Vernooij
Run autopep8.
605
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
606
            def _line_cache_and_writer(**kwargs):
607
                """Write formatted line and cache arguments"""
0.46.12 by Martin
Split format string for cache to only store a string, not a dict
608
                end = per_line % kwargs
609
                add_to_cache(end)
610
                write(start + end)
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
611
            return _line_cache_and_writer
7143.15.2 by Jelmer Vernooij
Run autopep8.
612
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
613
        def _line_writer(**kwargs):
614
            """Write formatted line from arguments given by underlying opts"""
0.46.13 by Martin
Split format string into two parts for non-cached operations too
615
            write(start + per_line % kwargs)
0.46.8 by Martin
Move pattern highlighting out of _file_grep and into the line writing code
616
        return _line_writer
617
0.46.11 by Martin
Add method to outputter for writing cached lines
618
    def write_cached_lines(self, cache_id, revno):
619
        """Write cached results out again for new revision"""
620
        cached_path, cached_matches = self.cache[cache_id]
7143.15.2 by Jelmer Vernooij
Run autopep8.
621
        start = self._format_initial % {"path": cached_path, "revno": revno}
0.46.11 by Martin
Add method to outputter for writing cached lines
622
        write = self.outf.write
0.46.12 by Martin
Split format string for cache to only store a string, not a dict
623
        for end in cached_matches:
624
            write(start + end)
0.46.11 by Martin
Add method to outputter for writing cached lines
625
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
626
    def _get_writer_regexp_highlighted(self, path, revno, cache_id):
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
627
        """Get function for writing output with regexp match highlighted"""
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
628
        _line_writer = self._get_writer_plain(path, revno, cache_id)
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
629
        sub, highlight = self._sub, self._highlight
7143.15.2 by Jelmer Vernooij
Run autopep8.
630
0.46.8 by Martin
Move pattern highlighting out of _file_grep and into the line writing code
631
        def _line_writer_regexp_highlighted(line, **kwargs):
632
            """Write formatted line with matched pattern highlighted"""
633
            return _line_writer(line=sub(highlight, line), **kwargs)
634
        return _line_writer_regexp_highlighted
635
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
636
    def _get_writer_fixed_highlighted(self, path, revno, cache_id):
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
637
        """Get function for writing output with search string highlighted"""
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
638
        _line_writer = self._get_writer_plain(path, revno, cache_id)
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
639
        old, new = self._old, self._new
7143.15.2 by Jelmer Vernooij
Run autopep8.
640
0.46.9 by Martin
Give in and make formatter a class so path and revno only need to be passed once per file
641
        def _line_writer_fixed_highlighted(line, **kwargs):
642
            """Write formatted line with string searched for highlighted"""
643
            return _line_writer(line=line.replace(old, new), **kwargs)
644
        return _line_writer_fixed_highlighted
0.46.3 by Martin
Start moving formatting setup out of _file_grep, only for files_with_matches so far
645
646
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
647
def _file_grep(file_text, path, opts, revno, path_prefix=None, cache_id=None):
0.41.9 by Parth Malwankar
refactored code towards support for working tree grep.
648
    # test and skip binary files
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
649
    if b'\x00' in file_text[:1024]:
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
650
        if opts.verbose:
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
651
            trace.warning("Binary file '%s' skipped.", path)
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
652
        return
0.41.9 by Parth Malwankar
refactored code towards support for working tree grep.
653
0.40.52 by Parth Malwankar
code cleanup and documentation
654
    if path_prefix and path_prefix != '.':
655
        # user has passed a dir arg, show that as result prefix
656
        path = osutils.pathjoin(path_prefix, path)
657
0.46.21 by Martin
Fix and test bytes/unicode issue but there's more to do in this area
658
    # GZ 2010-06-07: There's no actual guarentee the file contents will be in
659
    #                the user encoding, but we have to guess something and it
660
    #                is a reasonable default without a better mechanism.
661
    file_encoding = _user_encoding
0.46.19 by Martin
Minor pokes, fixes a bug with working tree optimisation and binary files
662
    pattern = opts.pattern.encode(_user_encoding, 'replace')
0.43.8 by Parth Malwankar
added color for regex pattern.
663
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
664
    writeline = opts.outputter.get_writer(path, revno, cache_id)
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
665
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
666
    if opts.files_with_matches or opts.files_without_match:
0.46.2 by Martin
Remove redundant code on files_with_matches path in _file_grep
667
        if opts.fixed_string:
6691.1.5 by Jelmer Vernooij
Drop support for Python <= 2.5.
668
            found = pattern in file_text
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
669
        else:
0.46.16 by Martin
Save an attribute lookup on regexp object in inner loops
670
            search = opts.patternc.search
7027.9.1 by Jelmer Vernooij
Fix all but one remaining grep tests.
671
            if b"$" not in pattern:
0.47.2 by Martin
Use whole text search for match only cases where possible as well
672
                found = search(file_text) is not None
673
            else:
674
                for line in file_text.splitlines():
675
                    if search(line):
676
                        found = True
677
                        break
678
                else:
679
                    found = False
0.43.1 by Parth Malwankar
added GrepOptions object for easy parameter passing
680
        if (opts.files_with_matches and found) or \
681
                (opts.files_without_match and not found):
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
682
            writeline()
0.46.19 by Martin
Minor pokes, fixes a bug with working tree optimisation and binary files
683
    elif opts.fixed_string:
0.47.1 by Martin
Implement whole text search for fast failure on no match
684
        # Fast path for no match, search through the entire file at once rather
6619.3.25 by Jelmer Vernooij
Drop some old dependency checks.
685
        # than a line at a time. <http://effbot.org/zone/stringlib.htm>
686
        i = file_text.find(pattern)
687
        if i == -1:
688
            return
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
689
        b = file_text.rfind(b"\n", 0, i) + 1
6619.3.25 by Jelmer Vernooij
Drop some old dependency checks.
690
        if opts.line_number:
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
691
            start = file_text.count(b"\n", 0, b) + 1
6619.3.25 by Jelmer Vernooij
Drop some old dependency checks.
692
        file_text = file_text[b:]
0.46.15 by Martin
Swap fixed_string/line_number branches in _file_grep
693
        if opts.line_number:
0.46.5 by Martin
Delete now redundant duplicated loops in _file_grep
694
            for index, line in enumerate(file_text.splitlines()):
695
                if pattern in line:
0.40.137 by Parth Malwankar
(Martin [gz]) Add seperate output formatter
696
                    line = line.decode(file_encoding, 'replace')
7143.15.2 by Jelmer Vernooij
Run autopep8.
697
                    writeline(lineno=index + start, line=line)
0.46.5 by Martin
Delete now redundant duplicated loops in _file_grep
698
        else:
0.46.15 by Martin
Swap fixed_string/line_number branches in _file_grep
699
            for line in file_text.splitlines():
700
                if pattern in line:
0.40.137 by Parth Malwankar
(Martin [gz]) Add seperate output formatter
701
                    line = line.decode(file_encoding, 'replace')
0.46.15 by Martin
Swap fixed_string/line_number branches in _file_grep
702
                    writeline(line=line)
0.40.63 by Parth Malwankar
performance: moved conditionals out of core loop.
703
    else:
0.47.1 by Martin
Implement whole text search for fast failure on no match
704
        # Fast path on no match, the re module avoids bad behaviour in most
705
        # standard cases, but perhaps could try and detect backtracking
706
        # patterns here and avoid whole text search in those cases
0.46.16 by Martin
Save an attribute lookup on regexp object in inner loops
707
        search = opts.patternc.search
7027.9.1 by Jelmer Vernooij
Fix all but one remaining grep tests.
708
        if b"$" not in pattern:
0.47.1 by Martin
Implement whole text search for fast failure on no match
709
            # GZ 2010-06-05: Grr, re.MULTILINE can't save us when searching
710
            #                through revisions as bazaar returns binary mode
711
            #                and trailing \r breaks $ as line ending match
712
            m = search(file_text)
713
            if m is None:
714
                return
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
715
            b = file_text.rfind(b"\n", 0, m.start()) + 1
0.47.1 by Martin
Implement whole text search for fast failure on no match
716
            if opts.line_number:
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
717
                start = file_text.count(b"\n", 0, b) + 1
0.47.4 by Martin
Scale back no-match fast path to avoid some behaviour changes with line endings
718
            file_text = file_text[b:]
0.47.3 by Martin
Fix previously untested bug with regexp and line numbers introduced by optimisation
719
        else:
720
            start = 1
0.46.15 by Martin
Swap fixed_string/line_number branches in _file_grep
721
        if opts.line_number:
722
            for index, line in enumerate(file_text.splitlines()):
0.46.16 by Martin
Save an attribute lookup on regexp object in inner loops
723
                if search(line):
0.40.137 by Parth Malwankar
(Martin [gz]) Add seperate output formatter
724
                    line = line.decode(file_encoding, 'replace')
7143.15.2 by Jelmer Vernooij
Run autopep8.
725
                    writeline(lineno=index + start, line=line)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
726
        else:
727
            for line in file_text.splitlines():
0.46.16 by Martin
Save an attribute lookup on regexp object in inner loops
728
                if search(line):
0.40.137 by Parth Malwankar
(Martin [gz]) Add seperate output formatter
729
                    line = line.decode(file_encoding, 'replace')
0.46.10 by Martin
Move caching mechanism onto outputter rather than passing around dicts and lists
730
                    writeline(line=line)