Created
October 11, 2019 16:24
-
-
Save anapaulagomes/1f2012080ac4e9558a4bd730743b8aa8 to your computer and use it in GitHub Desktop.
Helping people moving from model_mommy to model_bakery
This file contains hidden or 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
""" | |
Migrate from model_mommy to model_bakery. | |
``python from_mommy_to_bakery.py --dry-run`` | |
""" | |
import argparse | |
import os | |
import re | |
PACKAGE_NAME = r'\bmodel_mommy\b' | |
PACKAGE_NAME_PATTERN = re.compile(PACKAGE_NAME) | |
PACKAGE_RECIPES = r'\bmommy_recipes\b' | |
PACKAGE_RECIPES_PATTERN = re.compile(PACKAGE_RECIPES) | |
PACKAGE_LEGACY_MODULE = r'\bmommy\b' | |
PACKAGE_LEGACY_MODULE_PATTERN = re.compile(PACKAGE_LEGACY_MODULE) | |
legacy_and_new = [ | |
{'old': PACKAGE_NAME_PATTERN, 'new': r'model_bakery'}, | |
{'old': PACKAGE_RECIPES_PATTERN, 'new': r'baker_recipes'}, | |
{'old': PACKAGE_LEGACY_MODULE_PATTERN, 'new': r'baker'}, | |
] | |
def _find_changes(content, pattern, new_value): | |
new_content, substitutions = re.subn(pattern, new_value, content) | |
return new_content, substitutions > 0 | |
def check_files(dry_run): | |
exclude = ['node_modules', 'venv', '.git', 'sql', 'docs'] | |
excluded_by_gitignore = [ | |
folder_or_file.strip() | |
for folder_or_file in open('.gitignore').readlines() | |
] | |
exclude.extend(excluded_by_gitignore) | |
for root, dirs, files in os.walk('.', topdown=True): | |
dirs[:] = [ | |
directory | |
for directory in dirs | |
if directory not in exclude | |
] | |
for file_ in files: | |
if file_.endswith('.py') is False or file_ == 'from_mommy_to_bakery.py': | |
continue | |
file_path = f'{root}/{file_}' | |
if file_ == 'mommy_recipes.py': | |
pass | |
# TODO rename it to baker_recipes.py | |
content = open(file_path, 'r').read() | |
changed = [] | |
for patterns in legacy_and_new: | |
content, has_changed = _find_changes(content, patterns['old'], patterns['new']) | |
changed.append(has_changed) | |
if any(changed): | |
if dry_run is False: | |
open(file_path, 'w').write(content) | |
else: | |
print(file_path) | |
if __name__ == '__main__': | |
description = 'Help you to migrate from model_mommy to model_bakery.' | |
parser = argparse.ArgumentParser(description=description) | |
parser.add_argument( | |
'--dry-run', dest='dry_run', action='store_true', | |
help='See which files will be changed.' | |
) | |
args = parser.parse_args() | |
check_files(args.dry_run) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment