/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/plugins/grep/grep.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
from __future__ import absolute_import
18
18
 
19
 
import re
20
19
import sys
21
20
 
22
 
from ...lazy_import import lazy_import
 
21
from bzrlib.lazy_import import lazy_import
23
22
lazy_import(globals(), """
24
23
from fnmatch import fnmatch
25
 
 
26
 
from breezy._termcolor import color_string, FG
27
 
 
28
 
from breezy import (
29
 
    controldir,
 
24
import re
 
25
from cStringIO import StringIO
 
26
 
 
27
from bzrlib._termcolor import color_string, re_color_string, FG
 
28
 
 
29
from bzrlib.revisionspec import (
 
30
    RevisionSpec,
 
31
    RevisionSpec_revid,
 
32
    RevisionSpec_revno,
 
33
    )
 
34
from bzrlib import (
 
35
    bzrdir,
30
36
    diff,
31
37
    errors,
32
38
    lazy_regex,
 
39
    osutils,
33
40
    revision as _mod_revision,
 
41
    trace,
34
42
    )
35
43
""")
36
 
from breezy import (
37
 
    osutils,
38
 
    trace,
39
 
    )
40
 
from breezy.revisionspec import (
41
 
    RevisionSpec,
42
 
    RevisionSpec_revid,
43
 
    RevisionSpec_revno,
44
 
    )
45
 
from breezy.sixish import (
46
 
    BytesIO,
47
 
    )
48
44
 
49
45
_user_encoding = osutils.get_user_encoding()
50
46
 
61
57
 
62
58
 
63
59
# NOTE: _linear_view_revisions is basided on
64
 
# breezy.log._linear_view_revisions.
 
60
# bzrlib.log._linear_view_revisions.
65
61
# This should probably be a common public API
66
62
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
67
63
    # requires that start is older than end
78
74
 
79
75
 
80
76
# NOTE: _graph_view_revisions is copied from
81
 
# breezy.log._graph_view_revisions.
 
77
# bzrlib.log._graph_view_revisions.
82
78
# This should probably be a common public API
83
79
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
84
80
                          rebase_initial_depths=True):
126
122
        # use python's re.compile as we need to catch re.error in case of bad pattern
127
123
        lazy_regex.reset_compile()
128
124
        patternc = re.compile(pattern, flags)
129
 
    except re.error as e:
 
125
    except re.error, e:
130
126
        raise errors.BzrError("Invalid pattern: '%s'" % pattern)
131
127
    return patternc
132
128
 
152
148
                self.get_writer = self._get_writer_fixed_highlighted
153
149
            else:
154
150
                flags = opts.patternc.flags
155
 
                self._sub = re.compile(pat.join(("((?:", ")+)")), flags).sub
 
151
                self._sub = re.compile(pat.join(("((?:",")+)")), flags).sub
156
152
                self._highlight = color_string("\\1", FG.BOLD_RED)
157
153
                self.get_writer = self._get_writer_regexp_highlighted
158
154
        else:
215
211
 
216
212
def grep_diff(opts):
217
213
    wt, branch, relpath = \
218
 
        controldir.ControlDir.open_containing_tree_or_branch('.')
219
 
    with branch.lock_read():
 
214
        bzrdir.BzrDir.open_containing_tree_or_branch('.')
 
215
    branch.lock_read()
 
216
    try:
220
217
        if opts.revision:
221
218
            start_rev = opts.revision[0]
222
219
        else:
280
277
            else:
281
278
                ancestor_id = new_rev.parent_ids[0]
282
279
            old_tree = repo.revision_tree(ancestor_id)
283
 
            s = BytesIO()
 
280
            s = StringIO()
284
281
            diff.show_diff_trees(old_tree, new_tree, s,
285
282
                old_label='', new_label='')
286
283
            display_revno = True
300
297
                        display_file = False
301
298
                    line = line.decode(file_encoding, 'replace')
302
299
                    writeline("    %s" % (line,))
 
300
    finally:
 
301
        branch.unlock()
303
302
 
304
303
 
305
304
def versioned_grep(opts):
306
305
    wt, branch, relpath = \
307
 
        controldir.ControlDir.open_containing_tree_or_branch('.')
308
 
    with branch.lock_read():
 
306
        bzrdir.BzrDir.open_containing_tree_or_branch('.')
 
307
    branch.lock_read()
 
308
    try:
309
309
        start_rev = opts.revision[0]
310
310
        start_revid = start_rev.as_revision_id(branch)
311
311
        if start_revid is None:
356
356
            rev = RevisionSpec_revid.from_string("revid:"+revid)
357
357
            tree = rev.as_tree(branch)
358
358
            for path in opts.path_list:
359
 
                tree_path = osutils.pathjoin(relpath, path)
360
 
                if not tree.has_filename(tree_path):
 
359
                path_for_id = osutils.pathjoin(relpath, path)
 
360
                id = tree.path2id(path_for_id)
 
361
                if not id:
361
362
                    trace.warning("Skipped unknown file '%s'." % path)
362
363
                    continue
363
364
 
365
366
                    path_prefix = path
366
367
                    dir_grep(tree, path, relpath, opts, revno, path_prefix)
367
368
                else:
368
 
                    versioned_file_grep(tree, tree_path, '.', path, opts, revno)
 
369
                    versioned_file_grep(tree, id, '.', path, opts, revno)
 
370
    finally:
 
371
        branch.unlock()
369
372
 
370
373
 
371
374
def workingtree_grep(opts):
372
375
    revno = opts.print_revno = None # for working tree set revno to None
373
376
 
374
377
    tree, branch, relpath = \
375
 
        controldir.ControlDir.open_containing_tree_or_branch('.')
 
378
        bzrdir.BzrDir.open_containing_tree_or_branch('.')
376
379
    if not tree:
377
380
        msg = ('Cannot search working tree. Working tree not found.\n'
378
381
            'To search for specific revision in history use the -r option.')
381
384
    # GZ 2010-06-02: Shouldn't be smuggling this on opts, but easy for now
382
385
    opts.outputter = _Outputter(opts)
383
386
 
384
 
    with tree.lock_read():
 
387
    tree.lock_read()
 
388
    try:
385
389
        for path in opts.path_list:
386
390
            if osutils.isdir(path):
387
391
                path_prefix = path
388
392
                dir_grep(tree, path, relpath, opts, revno, path_prefix)
389
393
            else:
390
394
                _file_grep(open(path).read(), path, opts, revno)
 
395
    finally:
 
396
        tree.unlock()
391
397
 
392
398
 
393
399
def _skip_file(include, exclude, path):
402
408
    # setup relpath to open files relative to cwd
403
409
    rpath = relpath
404
410
    if relpath:
405
 
        rpath = osutils.pathjoin('..', relpath)
 
411
        rpath = osutils.pathjoin('..',relpath)
406
412
 
407
413
    from_dir = osutils.pathjoin(relpath, path)
408
414
    if opts.from_root:
409
415
        # start searching recursively from root
410
 
        from_dir = None
411
 
        recursive = True
 
416
        from_dir=None
 
417
        recursive=True
412
418
 
413
419
    to_grep = []
414
420
    to_grep_append = to_grep.append
423
429
            continue
424
430
 
425
431
        if fc == 'V' and fkind == 'file':
426
 
            tree_path = osutils.pathjoin(from_dir if from_dir else '', fp)
427
 
            if revno is not None:
 
432
            if revno != None:
428
433
                # If old result is valid, print results immediately.
429
434
                # Otherwise, add file info to to_grep so that the
430
435
                # loop later will get chunks and grep them
431
 
                cache_id = tree.get_file_revision(tree_path, fid)
 
436
                cache_id = tree.get_file_revision(fid)
432
437
                if cache_id in outputter.cache:
433
438
                    # GZ 2010-06-05: Not really sure caching and re-outputting
434
439
                    #                the old path is really the right thing,
435
440
                    #                but it's what the old code seemed to do
436
441
                    outputter.write_cached_lines(cache_id, revno)
437
442
                else:
438
 
                    to_grep_append((tree_path, (fp, tree_path)))
 
443
                    to_grep_append((fid, (fp, fid)))
439
444
            else:
440
445
                # we are grepping working tree.
441
446
                if from_dir is None:
451
456
                    file_text = open(path_for_file, 'r').read()
452
457
                    _file_grep(file_text, fp, opts, revno, path_prefix)
453
458
 
454
 
    if revno is not None: # grep versioned files
455
 
        for (path, tree_path), chunks in tree.iter_files_bytes(to_grep):
 
459
    if revno != None: # grep versioned files
 
460
        for (path, fid), chunks in tree.iter_files_bytes(to_grep):
456
461
            path = _make_display_path(relpath, path)
457
 
            _file_grep(''.join(chunks), path, opts, revno, path_prefix,
458
 
                tree.get_file_revision(tree_path))
 
462
            _file_grep(chunks[0], path, opts, revno, path_prefix,
 
463
                tree.get_file_revision(fid, path))
459
464
 
460
465
 
461
466
def _make_display_path(relpath, path):
473
478
    return path
474
479
 
475
480
 
476
 
def versioned_file_grep(tree, tree_path, relpath, path, opts, revno, path_prefix = None):
 
481
def versioned_file_grep(tree, id, relpath, path, opts, revno, path_prefix = None):
477
482
    """Create a file object for the specified id and pass it on to _file_grep.
478
483
    """
479
484
 
480
485
    path = _make_display_path(relpath, path)
481
 
    file_text = tree.get_file_text(tree_path)
 
486
    file_text = tree.get_file_text(id)
482
487
    _file_grep(file_text, path, opts, revno, path_prefix)
483
488
 
484
489
 
548
553
                self.get_writer = self._get_writer_fixed_highlighted
549
554
            else:
550
555
                flags = opts.patternc.flags
551
 
                self._sub = re.compile(pat.join(("((?:", ")+)")), flags).sub
 
556
                self._sub = re.compile(pat.join(("((?:",")+)")), flags).sub
552
557
                self._highlight = color_string("\\1", FG.BOLD_RED)
553
558
                self.get_writer = self._get_writer_regexp_highlighted
554
559
            path_start = FG.MAGENTA
644
649
 
645
650
    if opts.files_with_matches or opts.files_without_match:
646
651
        if opts.fixed_string:
647
 
            found = pattern in file_text
 
652
            if sys.platform > (2, 5):
 
653
                found = pattern in file_text
 
654
            else:
 
655
                for line in file_text.splitlines():
 
656
                    if pattern in line:
 
657
                        found = True
 
658
                        break
 
659
                else:
 
660
                    found = False
648
661
        else:
649
662
            search = opts.patternc.search
650
663
            if "$" not in pattern:
661
674
            writeline()
662
675
    elif opts.fixed_string:
663
676
        # Fast path for no match, search through the entire file at once rather
664
 
        # than a line at a time. <http://effbot.org/zone/stringlib.htm>
665
 
        i = file_text.find(pattern)
666
 
        if i == -1:
667
 
            return
668
 
        b = file_text.rfind("\n", 0, i) + 1
669
 
        if opts.line_number:
670
 
            start = file_text.count("\n", 0, b) + 1
671
 
        file_text = file_text[b:]
 
677
        # than a line at a time. However, we don't want this without Python 2.5
 
678
        # as the quick string search algorithm wasn't implemented till then:
 
679
        # <http://effbot.org/zone/stringlib.htm>
 
680
        if sys.version_info > (2, 5):
 
681
            i = file_text.find(pattern)
 
682
            if i == -1:
 
683
                return
 
684
            b = file_text.rfind("\n", 0, i) + 1
 
685
            if opts.line_number:
 
686
                start = file_text.count("\n", 0, b) + 1
 
687
            file_text = file_text[b:]
 
688
        else:
 
689
            start = 1
672
690
        if opts.line_number:
673
691
            for index, line in enumerate(file_text.splitlines()):
674
692
                if pattern in line: