def test_not_recursive_with_matches():
    global tmpdir
    tmpdir2 = tempfile.mkdtemp(dir=tmpdir)
    tmpfile = tempfile.NamedTemporaryFile(dir=tmpdir2)

    pattern = r'(\d[.-])?\d{3,}[.-]\d{3,}[.-]\d{4,}'
    s = b"""
    never call the number 1-800-666-1337.
    instead, you sould call the number 333-3737-13
    but actually, that number sucks, so call "9-373-185-7242"
    or really just hit me up at777.777.7777
    """

    tmpfile.seek(0)
    tmpfile.write(s)
    os.fsync(tmpfile.fileno())
    tmpfile.seek(0)

    matches = list(find_pattern_in_directory(pattern=pattern, directory=tmpdir2, recursive=False, file_patterns=['*']))
    assert len(matches) == 3
    for m in matches:
        assert m['match'].re.pattern == pattern
        if sys.version_info.major > 2:
            assert m['match'].re.flags == re.UNICODE
        else:
            assert m['match'].re.flags == 0
    assert matches[0]['match'].group() == '1-800-666-1337'
    assert matches[1]['match'].group() == '9-373-185-7242'
    assert matches[2]['match'].group() == '777.777.7777'
Example #2
0
def execute(parsed_args=None, cfg=None, logger=None, interactive=False, find_settings=load_settings(),
        *args, **kwargs):
    """ Executes the edit command. """

    if not cfg: return False

    # Load settings from config file
    editor = cfg.get('edit', 'EDITOR')
    line_num_option = cfg.get('edit', 'EDITOR_LINE_NUM_OPTION')

    # Aggregate all the matches into a generator
    matches = iter(())
    for d in find_settings['dirs']:
        matches = itertools.chain(matches, find_pattern_in_directory(pattern=find_settings['pattern'],
            directory=d, recursive=find_settings['recursive'], file_patterns=find_settings['file_patterns']))

    # Select the match with the match number that matches the supplied argument
    match_idx = parsed_args.number - 1
    try:
        match = list(itertools.islice(matches, match_idx, match_idx + 1))[0]
    except (IndexError, ValueError):
        print('Invalid match number: {num}'.format(num=parsed_args.number))
        return False

    # Open the match file in the editor
    return subprocess.call([editor, '{option}{num}'.format(option=line_num_option, num=match['line']),
        match['filename']]) == 0
Example #3
0
def execute(parsed_args=None, cfg=None, logger=None, interactive=False, find_settings=load_settings(),
        *args, **kwargs):
    """ Executes the edit command. """

    if not cfg: return False

    # Aggregate all the matches into a generator
    matches = iter(())
    for d in find_settings['dirs']:
        matches = itertools.chain(matches, find_pattern_in_directory(pattern=find_settings['pattern'],
            directory=d, recursive=find_settings['recursive'], file_patterns=find_settings['file_patterns']))

    # If match numbers were specified, print the matches
    if parsed_args.numbers:
        match_numbers = set()
        for number in parsed_args.numbers:
            if _number_regex.match(number):
                match_numbers.add(int(number, 0))
            else:
                m = _range_regex.match(number)
                if m:
                    match_numbers.update([n for n in range(int(m.group('start'), 0), int(m.group('end'), 0) + 1)])
                else:
                    print('Invalid syntax: {numbers}\nValid syntax:\n\t<number>\n\t<start>-<end>\n\t<start>:<end>'.format(numbers=' '.join(parsed_args.numbers)))
                    return False

        numbers = sorted(match_numbers)
        for idx, match in enumerate(matches):
            if idx + 1 not in numbers: continue
            print_match(match, idx + 1, cfg=cfg, interactive=interactive)
            numbers.remove(idx + 1)
        if len(numbers) > 0:
            print('Invalid match number(s): {numbers}'.format(numbers=', '.join([str(n) for n in numbers])))
            return False
    else:
        # Otherwise, print all the matches
        try:
            for idx, match in enumerate(matches):
                print_match(match, idx + 1, cfg=cfg, interactive=interactive)
        except KeyboardInterrupt:
            pass

    return True
def test_recursive_no_file_patterns():
    global tmpdir
    tmpdir2 = tempfile.mkdtemp(dir=tmpdir)
    tmpfile = tempfile.NamedTemporaryFile(dir=tmpdir2)

    pattern = r'(\d[.-])?\d{3,}[.-]\d{3,}[.-]\d{4,}'
    s = b"""
    never call the number 1-800-666-1337.
    instead, you sould call the number 333-3737-13
    but actually, that number sucks, so call "9-373-185-7242"
    or really just hit me up at777.777.7777
    """

    tmpfile.seek(0)
    tmpfile.write(s)
    os.fsync(tmpfile.fileno())
    tmpfile.seek(0)

    assert list(find_pattern_in_directory(pattern=pattern, directory=tmpdir, recursive=True, file_patterns=[])) == []
def test_file_patterns_only():
    global tmpfile
    assert list(find_pattern_in_directory(file_patterns=[tmpfile.name])) == []
def test_recursive_only():
    assert list(find_pattern_in_directory(recursive=True)) == []
def test_directory_only():
    assert list(find_pattern_in_directory(directory=os.path.dirname(__file__))) == []
def test_flags_only():
    assert list(find_pattern_in_directory(flags=re.I)) == []
def test_pattern_only():
    assert list(find_pattern_in_directory(pattern='test')) == []
def test_no_arguments():
    assert list(find_pattern_in_directory()) == []