Support line numbers option

This commit is contained in:
Nicolo P 2022-02-15 18:34:27 +01:00
parent a4441c227b
commit 70ef839972

View File

@ -6,24 +6,24 @@ import sty
# TODO Avoid extra fname argument?? # TODO Avoid extra fname argument??
def find_lines(lines: list, pattern: str, fname: str, is_regexp=False) -> list: def find_line(line: str, pattern: str, is_regexp=False) -> bool:
""" """
Distinguish between regexp or not (default is False) Distinguish between regexp or not (default is False)
""" """
found_lines = []
for line in lines: found = False
if is_regexp:
matches = re.findall(pattern, line)
FIND_COND = len(matches) > 0
else:
FIND_COND = line.find(pattern) != -1
if FIND_COND: if is_regexp:
line = line.strip() matches = re.findall(pattern, line)
found_lines.append(fname + line) FIND_COND = len(matches) > 0
else:
FIND_COND = line.find(pattern) != -1
return found_lines if FIND_COND:
line = line.strip()
found = True
return found
def print_usage(): def print_usage():
@ -86,15 +86,14 @@ def parse_args(args: list) -> dict:
] ]
args_tree = dict() args_tree = dict()
options = [] # Filter short options
# Get options options = [arg[1:] for arg in args if arg[0] == '-']
for arg in args:
# Parse short options
if arg[0] == '-':
if arg[1:] not in OPTS:
raise exceptions.InvalidOption(arg[1:])
options.append(arg[1:]) # Remove invalid options and throw exception
# TODO does it make sense?
for opt in options:
if opt not in OPTS:
raise exceptions.InvalidOption(opt[1:])
args_tree["options"] = options args_tree["options"] = options
@ -111,10 +110,6 @@ def parse_args(args: list) -> dict:
args_tree["pattern"] = rf"{pattern}" args_tree["pattern"] = rf"{pattern}"
args_tree["files"] = remaining_args[1:] args_tree["files"] = remaining_args[1:]
"""
print(args_tree)
sys.exit(1)
"""
return args_tree return args_tree
@ -142,17 +137,26 @@ def process_grep(args_tree: dict) -> list:
f = f + ':' if len(files) > 1 else '' f = f + ':' if len(files) > 1 else ''
n = 0
# Check if case insensitive # Check if case insensitive
if 'i' in options: if 'i' in options:
pattern = pattern.lower() pattern = pattern.lower()
# Check if regexp flag for line in lines:
if 'E' in options: n = n + 1
# pattern is regexp # Check if regexp flag
if not check_pattern(pattern): if 'E' in options:
raise exceptions.InvalidPattern(pattern) # pattern is regexp
found_lines.extend(find_lines(lines, pattern, f, True)) if not check_pattern(pattern):
else: raise exceptions.InvalidPattern(pattern)
found_lines.extend(find_lines(lines, pattern, f)) found = find_line(line, pattern, True)
else:
found = find_line(line, pattern)
lnum = str(n) + ':' if 'n' in options else ''
if found:
found_lines.append(f + lnum + line.strip())
except FileNotFoundError as e: except FileNotFoundError as e:
print(e) print(e)