Created
June 16, 2022 00:36
-
-
Save Bobbias/c1d80e2396e179aca58ff8462f3a5bf4 to your computer and use it in GitHub Desktop.
todo-finder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import glob | |
import re | |
# language/comment types supported | |
cpp = r'//' | |
python = r'#' | |
# keywords supported | |
todo = r'todo:' | |
hack = r'hack:' | |
fixme = r'fixme:' | |
# build a regex, using the above defined comment types and tags | |
comment_regex = r'({comment_chars}) *({tag})(.*)'.format( | |
comment_chars='|'.join( | |
[cpp, | |
python]), | |
tag='|'.join( | |
[todo, | |
hack, | |
fixme])) | |
script_description = '''Find todo and other tags in source code. | |
Expects input in the form of python compatible glob patterns. | |
See: https://docs.python.org/3/library/glob.html | |
''' | |
logo_text = f'''todo-thing v0.0.1 | |
{script_description} | |
''' | |
def search_file(path): | |
try: | |
with open(path, mode='r') as file: | |
for lnum, line in enumerate(file): | |
for match in re.finditer(comment_regex, line): | |
start = match.start() | |
print(f'{path}:{lnum + 1}:{start} => {match.group(2).strip()} - {match.group(3).strip()}') | |
except OSError as err: | |
print(f'Error: Opening file `{path}` failed with error: {err}') | |
# todo: test this | |
if __name__ == '__main__': | |
# arse command line arguments using argparse to make adding more complicated options in the future easier | |
parser = argparse.ArgumentParser(prog='todo-thing', description=script_description) | |
# input contains a list of glob patterns from the command line arguments | |
parser.add_argument('-verbose', '-v', action='store_true', help='enable verbose output (for debugging use)') | |
parser.add_argument('input', type=str, nargs='+', help='a list of one or more glob patterns', metavar='globs') | |
args_list = parser.parse_args() | |
if args_list.verbose: | |
print(logo_text) | |
if len(args_list.input) < 1: | |
print('Error: No globs provided.') | |
exit(1) | |
for pattern in args_list.input: | |
file_list = glob.glob(pattern, recursive=True) | |
if len(file_list) < 1: | |
print(f'Error: No files found for input `{pattern}`.') | |
# fall through to next input if any | |
continue | |
# if we have files to process, begin processing them | |
for filename in file_list: | |
if args_list.verbose: | |
print(f'searching {filename}') | |
search_file(filename) | |
if args_list.verbose: | |
print('Finished') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment