Created
February 22, 2019 11:10
-
-
Save Teemu/42b84bcc9492aa990f56db79d1d0fd66 to your computer and use it in GitHub Desktop.
Refactor projects since IDE support is too much to ask
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 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment