import click import os import glob @click.command() @click.option('--dry/--no-dry', default=False) @click.argument('root_path', type=click.Path()) @click.argument('replace_strings', nargs=-1) def replace_all(dry, root_path, replace_strings): replace_strings = [x.split('=') for x in replace_strings] print('Configuration:') for match, replace in replace_strings: print(f'- String "{match}" is replaced with "{replace}"') assert match, "Match should be defined" # Directories paths = ( glob.glob(os.path.join(root_path, '**'), recursive=True) ) for path in paths: if os.path.isdir(path): for match, replace in replace_strings: if match in path: new_path = path.replace(match, replace) print(f'Renaming directory "{path}" with "{new_path}"') if not dry: os.renames(path, new_path) # Files paths = ( glob.glob(os.path.join(root_path, '**'), recursive=True) ) for path in paths: if os.path.isfile(path): for match, replace in replace_strings: if match in path: new_path = path.replace(match, replace) print(f'Renaming file "{path}" with "{new_path}"') if not dry: os.renames(path, new_path) # Contents paths = ( glob.glob(os.path.join(root_path, '**'), recursive=True) ) for path in paths: if os.path.isfile(path) and path.split('.')[-1] in ( ['ts', 'js', 'html', 'scss', 'css'] ): with open(path) as fp: data = fp.read() found_matches = False for match, replace in replace_strings: if match in data: print(f'Replacing "{match}" with "{replace}" in {path}') found_matches = True data = data.replace(match, replace) if not dry and found_matches: with open(path, 'w') as fp: fp.write(data) replace_all()