Last active
August 23, 2018 21:41
-
-
Save mvargeson/1752bea74599b435d9b7b78e5c38af0f to your computer and use it in GitHub Desktop.
Find orphaned source files by looking at list of children and checking all possible parents
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
#!/usr/bin/env python3 | |
from argparse import ArgumentParser | |
from glob import glob | |
from os.path import join, split, splitext, realpath | |
from re import compile, search | |
def main(): | |
parser = ArgumentParser(description="Find orphaned source files by looking at list of children and checking all possible parents.") | |
parser.add_argument( | |
"src", | |
default=".", | |
help="The path to the source directory" | |
) | |
parser.add_argument( | |
"--ext", | |
required=False, | |
help="Used to limit the children extension type (e.g. 'cjsx')" | |
) | |
args = parser.parse_args() | |
src = realpath(args.src) | |
child_file_paths = get_paths(src, args.ext) | |
parent_file_paths = get_paths(src) | |
for child_file_path in child_file_paths: | |
if not is_child_in_any_parent(child_file_path, parent_file_paths): | |
print(child_file_path) | |
def is_child_in_any_parent(child_file_path, parent_file_paths): | |
filename = split(child_file_path)[1] | |
filename = splitext(filename)[0] | |
pattern = compile(f"([\"']+)(.*){filename}(.*)([\"']+)") | |
for parent_file_path in parent_file_paths: | |
if parent_file_path == child_file_path: | |
continue | |
with open(realpath(parent_file_path)) as parent_file: | |
for line in parent_file.readlines(): | |
if search(pattern, line) is not None: | |
return True | |
return False | |
def get_extensions(extensions): | |
if isinstance(extensions, str): | |
return [extensions] | |
if isinstance(extensions, list): | |
return extensions | |
return ["js", "jsx", "cjsx", "coffee"] | |
def get_paths(src = "", extensions = None): | |
paths = [] | |
for extension in get_extensions(extensions): | |
paths.extend( | |
glob( | |
join(src, f"**/*.{extension}"), | |
recursive=True | |
) | |
) | |
return paths | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment