/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
17
from bzrlib.lazy_import import lazy_import
18
lazy_import(globals(), """
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
19
import codecs
20
import cStringIO
21
from fnmatch import fnmatch
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
22
import os
23
import re
24
0.41.12 by Parth Malwankar
initial support for working tree grep (no test cases yet!)
25
from bzrlib import bzrdir
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
26
from bzrlib.workingtree import WorkingTree
0.40.95 by Parth Malwankar
faster mainline rev grep
27
from bzrlib.revisionspec import RevisionSpec, RevisionSpec_revid, RevisionSpec_revno
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
28
from bzrlib import (
29
    errors,
30
    lazy_regex,
0.40.47 by Parth Malwankar
fixes bug #531336. binary files are now skipped.
31
    osutils,
32
    textfile,
33
    trace,
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
34
    )
35
""")
36
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
37
_terminal_encoding = osutils.get_terminal_encoding()
38
_user_encoding = osutils.get_user_encoding()
39
0.40.95 by Parth Malwankar
faster mainline rev grep
40
class _RevisionNotLinear(Exception):
41
    """Raised when a revision is not on left-hand history."""
42
43
def _rev_on_mainline(rev_tuple):
44
    """returns True is rev tuple is on mainline"""
45
    if len(rev_tuple) == 1:
46
        return True
47
    return rev_tuple[1] == 0 and rev_tuple[2] == 0
48
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
49
# NOTE: _linear_view_revisions is basided on
50
# bzrlib.log._linear_view_revisions.
51
# This should probably be a common public API
0.40.95 by Parth Malwankar
faster mainline rev grep
52
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
0.40.106 by Parth Malwankar
fixed error in dotted rev reverse search.
53
    # requires that start is older than end
0.40.95 by Parth Malwankar
faster mainline rev grep
54
    repo = branch.repository
55
    for revision_id in repo.iter_reverse_revision_history(end_rev_id):
56
        revno = branch.revision_id_to_dotted_revno(revision_id)
57
        revno_str = '.'.join(str(n) for n in revno)
58
        if revision_id == start_rev_id:
59
            yield revision_id, revno_str, 0
60
            break
61
        yield revision_id, revno_str, 0
62
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
63
# NOTE: _graph_view_revisions is copied from
64
# bzrlib.log._graph_view_revisions.
65
# This should probably be a common public API
66
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
67
                          rebase_initial_depths=True):
68
    """Calculate revisions to view including merges, newest to oldest.
69
70
    :param branch: the branch
71
    :param start_rev_id: the lower revision-id
72
    :param end_rev_id: the upper revision-id
73
    :param rebase_initial_depth: should depths be rebased until a mainline
74
      revision is found?
75
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
76
    """
0.40.106 by Parth Malwankar
fixed error in dotted rev reverse search.
77
    # requires that start is older than end
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
78
    view_revisions = branch.iter_merge_sorted_revisions(
79
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
80
        stop_rule="with-merges")
81
    if not rebase_initial_depths:
82
        for (rev_id, merge_depth, revno, end_of_merge
83
             ) in view_revisions:
84
            yield rev_id, '.'.join(map(str, revno)), merge_depth
85
    else:
86
        # We're following a development line starting at a merged revision.
87
        # We need to adjust depths down by the initial depth until we find
88
        # a depth less than it. Then we use that depth as the adjustment.
89
        # If and when we reach the mainline, depth adjustment ends.
90
        depth_adjustment = None
91
        for (rev_id, merge_depth, revno, end_of_merge
92
             ) in view_revisions:
93
            if depth_adjustment is None:
94
                depth_adjustment = merge_depth
95
            if depth_adjustment:
96
                if merge_depth < depth_adjustment:
97
                    # From now on we reduce the depth adjustement, this can be
98
                    # surprising for users. The alternative requires two passes
99
                    # which breaks the fast display of the first revision
100
                    # though.
101
                    depth_adjustment = merge_depth
102
                merge_depth -= depth_adjustment
103
            yield rev_id, '.'.join(map(str, revno)), merge_depth
104
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
105
def compile_pattern(pattern, flags=0):
106
    patternc = None
107
    try:
108
        # use python's re.compile as we need to catch re.error in case of bad pattern
109
        lazy_regex.reset_compile()
110
        patternc = re.compile(pattern, flags)
111
    except re.error, e:
112
        raise errors.BzrError("Invalid pattern: '%s'" % pattern)
113
    return patternc
114
0.40.86 by Parth Malwankar
the check for implicit fixed_string now allows for spaces.
115
def is_fixed_string(s):
0.40.101 by Parth Malwankar
added underscore to --fixed-string whitelist
116
    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.
117
        return True
118
    return False
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
119
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
120
def versioned_grep(revision, pattern, compiled_pattern, path_list, recursive,
0.41.21 by Parth Malwankar
include/exclude working now. tests not added.
121
        line_number, from_root, eol_marker, print_revno, levels,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
122
        include, exclude, verbose, fixed_string, ignore_case, files_with_matches,
123
        outf):
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
124
125
    wt, relpath = WorkingTree.open_containing('.')
0.40.88 by Parth Malwankar
updated to avoid relocking.
126
    wt.lock_read()
127
    try:
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
128
        # res_cache is used to cache results for dir grep based on fid.
129
        # If the fid is does not change between results, it means that
130
        # the result will be the same apart from revno. In such a case
131
        # we avoid getting file chunks from repo and grepping. The result
132
        # is just printed by replacing old revno with new one.
133
        res_cache = {}
0.40.88 by Parth Malwankar
updated to avoid relocking.
134
135
        start_rev = revision[0]
136
        start_revid = start_rev.as_revision_id(wt.branch)
0.40.95 by Parth Malwankar
faster mainline rev grep
137
        if start_revid == None:
138
            start_rev = RevisionSpec_revno.from_string("revno:1")
139
            start_revid = start_rev.as_revision_id(wt.branch)
140
        srevno_tuple = wt.branch.revision_id_to_dotted_revno(start_revid)
0.40.88 by Parth Malwankar
updated to avoid relocking.
141
142
        if len(revision) == 2:
143
            end_rev = revision[1]
0.40.95 by Parth Malwankar
faster mainline rev grep
144
            end_revid = end_rev.as_revision_id(wt.branch)
145
            if end_revid == None:
146
                end_revno, end_revid = wt.branch.last_revision_info()
147
            erevno_tuple = wt.branch.revision_id_to_dotted_revno(end_revid)
148
0.40.106 by Parth Malwankar
fixed error in dotted rev reverse search.
149
            grep_mainline = (_rev_on_mainline(srevno_tuple) and
150
                _rev_on_mainline(erevno_tuple))
151
152
            # ensure that we go in reverse order
153
            if srevno_tuple > erevno_tuple:
154
                srevno_tuple, erevno_tuple = erevno_tuple, srevno_tuple
155
                start_revid, end_revid = end_revid, start_revid
0.40.97 by Parth Malwankar
fixed caching bug for rev range.
156
0.40.95 by Parth Malwankar
faster mainline rev grep
157
            # Optimization: Traversing the mainline in reverse order is much
158
            # faster when we don't want to look at merged revs. We try this
159
            # with _linear_view_revisions. If all revs are to be grepped we
160
            # use the slower _graph_view_revisions
0.40.106 by Parth Malwankar
fixed error in dotted rev reverse search.
161
            if levels==1 and grep_mainline:
0.40.95 by Parth Malwankar
faster mainline rev grep
162
                given_revs = _linear_view_revisions(wt.branch, start_revid, end_revid)
163
            else:
0.40.100 by Parth Malwankar
removed dependency on log._graph_view_revisions
164
                given_revs = _graph_view_revisions(wt.branch, start_revid, end_revid)
0.40.88 by Parth Malwankar
updated to avoid relocking.
165
        else:
0.40.94 by Parth Malwankar
code cleanup. moved start_rev_tuple into if cond that uses it.
166
            # We do an optimization below. For grepping a specific revison
167
            # We don't need to call _graph_view_revisions which is slow.
168
            # We create the start_rev_tuple for only that specific revision.
169
            # _graph_view_revisions is used only for revision range.
170
            start_revno = '.'.join(map(str, srevno_tuple))
171
            start_rev_tuple = (start_revid, start_revno, 0)
0.40.88 by Parth Malwankar
updated to avoid relocking.
172
            given_revs = [start_rev_tuple]
173
174
        for revid, revno, merge_depth in given_revs:
175
            if levels == 1 and merge_depth != 0:
176
                # with level=1 show only top level
177
                continue
178
179
            rev = RevisionSpec_revid.from_string("revid:"+revid)
0.40.89 by Parth Malwankar
moved tree get call outside loop
180
            tree = rev.as_tree(wt.branch)
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
181
            for path in path_list:
182
                path_for_id = osutils.pathjoin(relpath, path)
183
                id = tree.path2id(path_for_id)
184
                if not id:
0.41.22 by Parth Malwankar
added basic --exclude/include tests
185
                    trace.warning("Skipped unknown file '%s'." % path)
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
186
                    continue
187
188
                if osutils.isdir(path):
189
                    path_prefix = path
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
190
                    res_cache = dir_grep(tree, path, relpath, recursive,
191
                        line_number, pattern, compiled_pattern,
192
                        from_root, eol_marker, revno, print_revno,
193
                        include, exclude, verbose, fixed_string,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
194
                        ignore_case, files_with_matches,
195
                        outf, path_prefix, res_cache)
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
196
                else:
0.40.69 by Parth Malwankar
reduced lock/unlock
197
                    versioned_file_grep(tree, id, '.', path,
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
198
                        pattern, compiled_pattern, eol_marker, line_number,
199
                        revno, print_revno, include, exclude, verbose,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
200
                        fixed_string, ignore_case, files_with_matches,
201
                        outf)
0.40.88 by Parth Malwankar
updated to avoid relocking.
202
    finally:
203
        wt.unlock()
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
204
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
205
def workingtree_grep(pattern, compiled_pattern, path_list, recursive,
206
        line_number, from_root, eol_marker, include, exclude, verbose,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
207
        fixed_string, ignore_case, files_with_matches, outf):
0.41.12 by Parth Malwankar
initial support for working tree grep (no test cases yet!)
208
    revno = print_revno = None # for working tree set revno to None
0.40.69 by Parth Malwankar
reduced lock/unlock
209
210
    tree, branch, relpath = \
211
        bzrdir.BzrDir.open_containing_tree_or_branch('.')
212
    tree.lock_read()
213
    try:
214
        for path in path_list:
215
            if osutils.isdir(path):
216
                path_prefix = path
217
                dir_grep(tree, path, relpath, recursive, line_number,
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
218
                    pattern, compiled_pattern, from_root, eol_marker, revno,
219
                    print_revno, include, exclude, verbose, fixed_string,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
220
                    ignore_case, files_with_matches, outf, path_prefix)
0.40.69 by Parth Malwankar
reduced lock/unlock
221
            else:
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
222
                _file_grep(open(path).read(), '.', path, pattern,
223
                    compiled_pattern, eol_marker, line_number, revno,
224
                    print_revno, include, exclude, verbose,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
225
                    fixed_string, ignore_case, files_with_matches, outf)
0.40.69 by Parth Malwankar
reduced lock/unlock
226
    finally:
227
        tree.unlock()
0.41.11 by Parth Malwankar
moved top level grep code to versioned_grep.
228
0.40.74 by Parth Malwankar
optimization. --include/exclude are checked before reading the file.
229
def _skip_file(include, exclude, path):
230
    if include and not _path_in_glob_list(path, include):
231
        return True
232
    if exclude and _path_in_glob_list(path, exclude):
233
        return True
234
    return False
235
236
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
237
def dir_grep(tree, path, relpath, recursive, line_number, pattern,
238
        compiled_pattern, from_root, eol_marker, revno, print_revno,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
239
        include, exclude, verbose, fixed_string, ignore_case,
240
        files_with_matches, outf, path_prefix, res_cache={}):
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
241
    _revno_pattern = re.compile("\~[0-9.]+:")
242
    dir_res = {}
243
0.40.60 by Parth Malwankar
'binary file skipped' warning is only shown with --verbose flag
244
    # setup relpath to open files relative to cwd
245
    rpath = relpath
246
    if relpath:
247
        rpath = osutils.pathjoin('..',relpath)
248
249
    from_dir = osutils.pathjoin(relpath, path)
250
    if from_root:
251
        # start searching recursively from root
252
        from_dir=None
253
        recursive=True
254
0.40.85 by Parth Malwankar
optimized versioned grep to use iter_files_bytes.
255
    to_grep = []
0.40.92 by Parth Malwankar
performance tweaks to core cached result print loop.
256
    to_grep_append = to_grep.append
257
    outf_write = outf.write
0.40.69 by Parth Malwankar
reduced lock/unlock
258
    for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
259
        from_dir=from_dir, recursive=recursive):
260
0.40.74 by Parth Malwankar
optimization. --include/exclude are checked before reading the file.
261
        if _skip_file(include, exclude, fp):
262
            continue
263
0.40.69 by Parth Malwankar
reduced lock/unlock
264
        if fc == 'V' and fkind == 'file':
265
            if revno != None:
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
266
                # If old result is valid, print results immediately.
267
                # Otherwise, add file info to to_grep so that the
268
                # loop later will get chunks and grep them
0.40.97 by Parth Malwankar
fixed caching bug for rev range.
269
                file_rev = tree.inventory[fid].revision
270
                old_res = res_cache.get(file_rev)
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
271
                if old_res != None:
272
                    res = []
0.40.92 by Parth Malwankar
performance tweaks to core cached result print loop.
273
                    res_append = res.append
274
                    new_rev = ('~%s:' % (revno,))
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
275
                    for line in old_res:
0.40.92 by Parth Malwankar
performance tweaks to core cached result print loop.
276
                        s = _revno_pattern.sub(new_rev, line)
277
                        res_append(s)
278
                        outf_write(s)
0.40.97 by Parth Malwankar
fixed caching bug for rev range.
279
                    dir_res[file_rev] = res
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
280
                else:
0.40.92 by Parth Malwankar
performance tweaks to core cached result print loop.
281
                    to_grep_append((fid, (fp, fid)))
0.40.69 by Parth Malwankar
reduced lock/unlock
282
            else:
283
                # we are grepping working tree.
284
                if from_dir == None:
285
                    from_dir = '.'
286
287
                path_for_file = osutils.pathjoin(tree.basedir, from_dir, fp)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
288
                file_text = codecs.open(path_for_file, 'r').read()
289
                _file_grep(file_text, rpath, fp,
290
                    pattern, compiled_pattern, eol_marker, line_number, revno,
291
                    print_revno, include, exclude, verbose, fixed_string,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
292
                    ignore_case, files_with_matches, outf, path_prefix)
0.40.43 by Parth Malwankar
moved cmd_grep._grep_dir to grep.dir_grep
293
0.40.85 by Parth Malwankar
optimized versioned grep to use iter_files_bytes.
294
    if revno != None: # grep versioned files
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
295
        for (path, fid), chunks in tree.iter_files_bytes(to_grep):
0.40.85 by Parth Malwankar
optimized versioned grep to use iter_files_bytes.
296
            path = _make_display_path(relpath, path)
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
297
            res = _file_grep(chunks[0], rpath, path, pattern,
298
                compiled_pattern, eol_marker, line_number, revno,
299
                print_revno, include, exclude, verbose, fixed_string,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
300
                ignore_case, files_with_matches, outf, path_prefix)
0.40.97 by Parth Malwankar
fixed caching bug for rev range.
301
            file_rev = tree.inventory[fid].revision
302
            dir_res[file_rev] = res
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
303
    return dir_res
0.40.43 by Parth Malwankar
moved cmd_grep._grep_dir to grep.dir_grep
304
0.41.8 by Parth Malwankar
code cleanup.
305
def _make_display_path(relpath, path):
306
    """Return path string relative to user cwd.
0.40.42 by Parth Malwankar
fix to make grep paths relative to cwd
307
0.41.8 by Parth Malwankar
code cleanup.
308
    Take tree's 'relpath' and user supplied 'path', and return path
309
    that can be displayed to the user.
310
    """
0.40.15 by Parth Malwankar
some fixes and test updates
311
    if relpath:
0.40.52 by Parth Malwankar
code cleanup and documentation
312
        # update path so to display it w.r.t cwd
313
        # handle windows slash separator
0.40.20 by Parth Malwankar
used path functions from bzrlib.osutils
314
        path = osutils.normpath(osutils.pathjoin(relpath, path))
0.40.22 by Parth Malwankar
fixed display path formatting on windows
315
        path = path.replace('\\', '/')
316
        path = path.replace(relpath + '/', '', 1)
0.41.8 by Parth Malwankar
code cleanup.
317
    return path
318
319
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
320
def versioned_file_grep(tree, id, relpath, path, pattern, patternc,
321
        eol_marker, line_number, revno, print_revno, include, exclude,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
322
        verbose, fixed_string, ignore_case, files_with_matches,
323
        outf, path_prefix = None):
0.41.10 by Parth Malwankar
code cleanup. added comments. path adjustment is now done
324
    """Create a file object for the specified id and pass it on to _file_grep.
325
    """
326
327
    path = _make_display_path(relpath, path)
0.41.12 by Parth Malwankar
initial support for working tree grep (no test cases yet!)
328
    file_text = tree.get_file_text(id)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
329
    _file_grep(file_text, relpath, path, pattern, patternc, eol_marker,
0.40.60 by Parth Malwankar
'binary file skipped' warning is only shown with --verbose flag
330
        line_number, revno, print_revno, include, exclude, verbose,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
331
        fixed_string, ignore_case, files_with_matches, outf, path_prefix)
0.41.21 by Parth Malwankar
include/exclude working now. tests not added.
332
333
def _path_in_glob_list(path, glob_list):
334
    present = False
335
    for glob in glob_list:
336
        if fnmatch(path, glob):
337
            present = True
338
            break
339
    return present
0.41.12 by Parth Malwankar
initial support for working tree grep (no test cases yet!)
340
0.40.70 by Parth Malwankar
lines are decoded correctly before printing.
341
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
342
def _file_grep(file_text, relpath, path, pattern, patternc, eol_marker,
343
        line_number, revno, print_revno, include, exclude, verbose,
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
344
        fixed_string, ignore_case, files_with_matches, outf, path_prefix=None):
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
345
    res = []
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
346
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
347
    _te = _terminal_encoding
348
    _ue = _user_encoding
349
350
    pattern = pattern.encode(_ue, 'replace')
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
351
    if fixed_string and ignore_case:
352
        pattern = pattern.lower()
353
0.41.9 by Parth Malwankar
refactored code towards support for working tree grep.
354
    # test and skip binary files
0.40.62 by Parth Malwankar
performance optimization
355
    if '\x00' in file_text[:1024]:
0.40.60 by Parth Malwankar
'binary file skipped' warning is only shown with --verbose flag
356
        if verbose:
357
            trace.warning("Binary file '%s' skipped." % path)
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
358
        return res
0.41.9 by Parth Malwankar
refactored code towards support for working tree grep.
359
0.40.52 by Parth Malwankar
code cleanup and documentation
360
    if path_prefix and path_prefix != '.':
361
        # user has passed a dir arg, show that as result prefix
362
        path = osutils.pathjoin(path_prefix, path)
363
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
364
    path = path.encode(_te, 'replace')
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
365
0.40.64 by Parth Malwankar
cosmetic: improved comment
366
    # for better performance we moved formatting conditionals out
367
    # of the core loop. hence, the core loop is somewhat duplicated
368
    # for various combinations of formatting options.
369
0.40.112 by Parth Malwankar
support for -l, --files-with-matches. no tests yet.
370
    if files_with_matches:
371
        # While printing files with matches we only have two case
372
        # print file name or print file name with revno.
373
        if print_revno:
374
            pfmt = "~%s".encode(_te, 'replace')
375
            s = path + (pfmt % (revno,)) + eol_marker
376
            if fixed_string:
377
                for line in file_text.splitlines():
378
                    if ignore_case:
379
                        line = line.lower()
380
                    if pattern in line:
381
                        res.append(s)
382
                        outf.write(s)
383
                        break
384
            else:
385
                for line in file_text.splitlines():
386
                    if patternc.search(line):
387
                        res.append(s)
388
                        outf.write(s)
389
                        break
390
        else:
391
            s = path + eol_marker
392
            if fixed_string:
393
                for line in file_text.splitlines():
394
                    if ignore_case:
395
                        line = line.lower()
396
                    if pattern in line:
397
                        res.append(s)
398
                        outf.write(s)
399
                        break
400
            else:
401
                for line in file_text.splitlines():
402
                    if patternc.search(line):
403
                        res.append(s)
404
                        outf.write(s)
405
                        break
406
        return res
407
408
0.40.63 by Parth Malwankar
performance: moved conditionals out of core loop.
409
    if print_revno and line_number:
410
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
411
        pfmt = "~%s:%d:%s".encode(_te)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
412
        if fixed_string:
413
            for index, line in enumerate(file_text.splitlines()):
414
                if ignore_case:
415
                    line = line.lower()
416
                if pattern in line:
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
417
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
418
                    s = path + (pfmt % (revno, index+1, line)) + eol_marker
419
                    res.append(s)
420
                    outf.write(s)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
421
        else:
422
            for index, line in enumerate(file_text.splitlines()):
423
                if patternc.search(line):
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
424
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
425
                    s = path + (pfmt % (revno, index+1, line)) + eol_marker
426
                    res.append(s)
427
                    outf.write(s)
0.40.63 by Parth Malwankar
performance: moved conditionals out of core loop.
428
429
    elif print_revno and not line_number:
430
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
431
        pfmt = "~%s:%s".encode(_te, 'replace')
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
432
        if fixed_string:
433
            for line in file_text.splitlines():
434
                if ignore_case:
435
                    line = line.lower()
436
                if pattern in line:
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
437
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
438
                    s = path + (pfmt % (revno, line)) + eol_marker
439
                    res.append(s)
440
                    outf.write(s)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
441
        else:
442
            for line in file_text.splitlines():
443
                if patternc.search(line):
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
444
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
445
                    s = path + (pfmt % (revno, line)) + eol_marker
446
                    res.append(s)
447
                    outf.write(s)
0.40.63 by Parth Malwankar
performance: moved conditionals out of core loop.
448
449
    elif not print_revno and line_number:
450
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
451
        pfmt = ":%d:%s".encode(_te)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
452
        if fixed_string:
453
            for index, line in enumerate(file_text.splitlines()):
454
                if ignore_case:
455
                    line = line.lower()
456
                if pattern in line:
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
457
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
458
                    s = path + (pfmt % (index+1, line)) + eol_marker
459
                    res.append(s)
460
                    outf.write(s)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
461
        else:
462
            for index, line in enumerate(file_text.splitlines()):
463
                if patternc.search(line):
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
464
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
465
                    s = path + (pfmt % (index+1, line)) + eol_marker
466
                    res.append(s)
467
                    outf.write(s)
0.40.63 by Parth Malwankar
performance: moved conditionals out of core loop.
468
469
    else:
0.40.64 by Parth Malwankar
cosmetic: improved comment
470
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
471
        pfmt = ":%s".encode(_te)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
472
        if fixed_string:
473
            for line in file_text.splitlines():
474
                if ignore_case:
475
                    line = line.lower()
476
                if pattern in line:
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
477
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
478
                    s = path + (pfmt % (line,)) + eol_marker
479
                    res.append(s)
480
                    outf.write(s)
0.40.83 by Parth Malwankar
added support for -F/--fixed-string.
481
        else:
482
            for line in file_text.splitlines():
483
                if patternc.search(line):
0.40.91 by Parth Malwankar
made _terminal_encoding and _user_encoding local for performance.
484
                    line = line.decode(_te, 'replace')
0.40.90 by Parth Malwankar
significant speedup for revision range grep by caching old result.
485
                    s = path + (pfmt % (line,)) + eol_marker
486
                    res.append(s)
487
                    outf.write(s)
488
489
    return res
0.40.9 by Parth Malwankar
factored out grep related code to grep.py
490