Migrate post-generation hook to pathlib

This commit is contained in:
Bruno Alla 2025-01-17 20:09:26 +00:00
parent b72e5b2c2a
commit 4b67c72ad4

View File

@ -1,9 +1,9 @@
# ruff: noqa: PLR0133 # ruff: noqa: PLR0133
import json import json
import os
import random import random
import shutil import shutil
import string import string
from pathlib import Path
try: try:
# Inspired by # Inspired by
@ -25,40 +25,28 @@ DEBUG_VALUE = "debug"
def remove_open_source_files(): def remove_open_source_files():
file_names = ["CONTRIBUTORS.txt", "LICENSE"] file_names = ["CONTRIBUTORS.txt", "LICENSE"]
for file_name in file_names: for file_name in file_names:
os.remove(file_name) # noqa: PTH107 Path(file_name).unlink()
def remove_gplv3_files(): def remove_gplv3_files():
file_names = ["COPYING"] file_names = ["COPYING"]
for file_name in file_names: for file_name in file_names:
os.remove(file_name) # noqa: PTH107 Path(file_name).unlink()
def remove_custom_user_manager_files(): def remove_custom_user_manager_files():
os.remove( # noqa: PTH107 users_path = Path("{{cookiecutter.project_slug}}", "users")
os.path.join( # noqa: PTH118 (users_path / "managers.py").unlink()
"{{cookiecutter.project_slug}}", (users_path / "tests" / "test_managers.py").unlink()
"users",
"managers.py",
),
)
os.remove( # noqa: PTH107
os.path.join( # noqa: PTH118
"{{cookiecutter.project_slug}}",
"users",
"tests",
"test_managers.py",
),
)
def remove_pycharm_files(): def remove_pycharm_files():
idea_dir_path = ".idea" idea_dir_path = Path(".idea")
if os.path.exists(idea_dir_path): # noqa: PTH110 if idea_dir_path.exists():
shutil.rmtree(idea_dir_path) shutil.rmtree(idea_dir_path)
docs_dir_path = os.path.join("docs", "pycharm") # noqa: PTH118 docs_dir_path = Path("docs", "pycharm")
if os.path.exists(docs_dir_path): # noqa: PTH110 if docs_dir_path.exists():
shutil.rmtree(docs_dir_path) shutil.rmtree(docs_dir_path)
@ -73,15 +61,15 @@ def remove_docker_files():
"justfile", "justfile",
] ]
for file_name in file_names: for file_name in file_names:
os.remove(file_name) # noqa: PTH107 Path(file_name).unlink()
if "{{ cookiecutter.editor }}" == "PyCharm": if "{{ cookiecutter.editor }}" == "PyCharm":
file_names = ["docker_compose_up_django.xml", "docker_compose_up_docs.xml"] file_names = ["docker_compose_up_django.xml", "docker_compose_up_docs.xml"]
for file_name in file_names: for file_name in file_names:
os.remove(os.path.join(".idea", "runConfigurations", file_name)) # noqa: PTH107, PTH118 Path(".idea", "runConfiguration", file_name).unlink()
def remove_nginx_docker_files(): def remove_nginx_docker_files():
shutil.rmtree(os.path.join("compose", "production", "nginx")) # noqa: PTH118 Path("compose/local/nginx").unlink()
def remove_utility_files(): def remove_utility_files():
@ -94,18 +82,18 @@ def remove_heroku_files():
if file_name == "requirements.txt" and "{{ cookiecutter.ci_tool }}".lower() == "travis": if file_name == "requirements.txt" and "{{ cookiecutter.ci_tool }}".lower() == "travis":
# don't remove the file if we are using travisci but not using heroku # don't remove the file if we are using travisci but not using heroku
continue continue
os.remove(file_name) # noqa: PTH107 Path(file_name).unlink()
shutil.rmtree("bin") shutil.rmtree("bin")
def remove_sass_files(): def remove_sass_files():
shutil.rmtree(os.path.join("{{cookiecutter.project_slug}}", "static", "sass")) # noqa: PTH118 shutil.rmtree(Path("{{cookiecutter.project_slug}}", "static", "sass"))
def remove_gulp_files(): def remove_gulp_files():
file_names = ["gulpfile.mjs"] file_names = ["gulpfile.mjs"]
for file_name in file_names: for file_name in file_names:
os.remove(file_name) # noqa: PTH107 Path(file_name).unlink()
def remove_webpack_files(): def remove_webpack_files():
@ -114,36 +102,30 @@ def remove_webpack_files():
def remove_vendors_js(): def remove_vendors_js():
vendors_js_path = os.path.join( # noqa: PTH118 vendors_js_path = Path("{{ cookiecutter.project_slug }}", "static", "js", "vendors.js")
"{{ cookiecutter.project_slug }}", if vendors_js_path.exists():
"static", vendors_js_path.unlink()
"js",
"vendors.js",
)
if os.path.exists(vendors_js_path): # noqa: PTH110
os.remove(vendors_js_path) # noqa: PTH107
def remove_packagejson_file(): def remove_packagejson_file():
file_names = ["package.json"] file_names = ["package.json"]
for file_name in file_names: for file_name in file_names:
os.remove(file_name) # noqa: PTH107 Path(file_name).unlink()
def update_package_json(remove_dev_deps=None, remove_keys=None, scripts=None): def update_package_json(remove_dev_deps=None, remove_keys=None, scripts=None):
remove_dev_deps = remove_dev_deps or [] remove_dev_deps = remove_dev_deps or []
remove_keys = remove_keys or [] remove_keys = remove_keys or []
scripts = scripts or {} scripts = scripts or {}
with open("package.json") as fd: # noqa: PTH123 package_json = Path("package.json")
content = json.load(fd) content = json.loads(package_json.read_text())
for package_name in remove_dev_deps: for package_name in remove_dev_deps:
content["devDependencies"].pop(package_name) content["devDependencies"].pop(package_name)
for key in remove_keys: for key in remove_keys:
content.pop(key) content.pop(key)
content["scripts"].update(scripts) content["scripts"].update(scripts)
with open("package.json", mode="w") as fd: # noqa: PTH123 updated_content = json.dumps(content, ensure_ascii=False, indent=2) + "\n"
json.dump(content, fd, ensure_ascii=False, indent=2) package_json.write_text(updated_content)
fd.write("\n")
def handle_js_runner(choice, use_docker, use_async): def handle_js_runner(choice, use_docker, use_async):
@ -207,8 +189,8 @@ def handle_js_runner(choice, use_docker, use_async):
def remove_prettier_pre_commit(): def remove_prettier_pre_commit():
with open(".pre-commit-config.yaml") as fd: # noqa: PTH123 pre_commit_yaml = Path(".pre-commit-config.yaml")
content = fd.readlines() content = pre_commit_yaml.read_text().splitlines()
removing = False removing = False
new_lines = [] new_lines = []
@ -220,35 +202,34 @@ def remove_prettier_pre_commit():
if not removing: if not removing:
new_lines.append(line) new_lines.append(line)
with open(".pre-commit-config.yaml", "w") as fd: # noqa: PTH123 pre_commit_yaml.write_text("\n".join(new_lines))
fd.writelines(new_lines)
def remove_celery_files(): def remove_celery_files():
file_names = [ file_paths = [
os.path.join("config", "celery_app.py"), # noqa: PTH118 Path("config", "celery_app.py"),
os.path.join("{{ cookiecutter.project_slug }}", "users", "tasks.py"), # noqa: PTH118 Path("{{ cookiecutter.project_slug }}", "users", "tasks.py"),
os.path.join("{{ cookiecutter.project_slug }}", "users", "tests", "test_tasks.py"), # noqa: PTH118 Path("{{ cookiecutter.project_slug }}", "users", "tests", "test_tasks.py"),
] ]
for file_name in file_names: for file_path in file_paths:
os.remove(file_name) # noqa: PTH107 file_path.unlink()
def remove_async_files(): def remove_async_files():
file_names = [ file_paths = [
os.path.join("config", "asgi.py"), # noqa: PTH118 Path("config", "asgi.py"),
os.path.join("config", "websocket.py"), # noqa: PTH118 Path("config", "websocket.py"),
] ]
for file_name in file_names: for file_path in file_paths:
os.remove(file_name) # noqa: PTH107 file_path.unlink()
def remove_dottravisyml_file(): def remove_dottravisyml_file():
os.remove(".travis.yml") # noqa: PTH107 Path(".travis.yml").unlink()
def remove_dotgitlabciyml_file(): def remove_dotgitlabciyml_file():
os.remove(".gitlab-ci.yml") # noqa: PTH107 Path(".gitlab-ci.yml").unlink()
def remove_dotgithub_folder(): def remove_dotgithub_folder():
@ -256,7 +237,7 @@ def remove_dotgithub_folder():
def remove_dotdrone_file(): def remove_dotdrone_file():
os.remove(".drone.yml") # noqa: PTH107 Path(".drone.yml").unlink()
def generate_random_string(length, using_digits=False, using_ascii_letters=False, using_punctuation=False): # noqa: FBT002 def generate_random_string(length, using_digits=False, using_ascii_letters=False, using_punctuation=False): # noqa: FBT002
@ -282,7 +263,7 @@ def generate_random_string(length, using_digits=False, using_ascii_letters=False
return "".join([random.choice(symbols) for _ in range(length)]) return "".join([random.choice(symbols) for _ in range(length)])
def set_flag(file_path, flag, value=None, formatted=None, *args, **kwargs): def set_flag(file_path: Path, flag, value=None, formatted=None, *args, **kwargs):
if value is None: if value is None:
random_string = generate_random_string(*args, **kwargs) random_string = generate_random_string(*args, **kwargs)
if random_string is None: if random_string is None:
@ -295,7 +276,7 @@ def set_flag(file_path, flag, value=None, formatted=None, *args, **kwargs):
random_string = formatted.format(random_string) random_string = formatted.format(random_string)
value = random_string value = random_string
with open(file_path, "r+") as f: # noqa: PTH123 with file_path.open("r+") as f:
file_contents = f.read().replace(flag, value) file_contents = f.read().replace(flag, value)
f.seek(0) f.seek(0)
f.write(file_contents) f.write(file_contents)
@ -304,7 +285,7 @@ def set_flag(file_path, flag, value=None, formatted=None, *args, **kwargs):
return value return value
def set_django_secret_key(file_path): def set_django_secret_key(file_path: Path):
return set_flag( return set_flag(
file_path, file_path,
"!!!SET DJANGO_SECRET_KEY!!!", "!!!SET DJANGO_SECRET_KEY!!!",
@ -314,7 +295,7 @@ def set_django_secret_key(file_path):
) )
def set_django_admin_url(file_path): def set_django_admin_url(file_path: Path):
return set_flag( return set_flag(
file_path, file_path,
"!!!SET DJANGO_ADMIN_URL!!!", "!!!SET DJANGO_ADMIN_URL!!!",
@ -364,16 +345,16 @@ def set_celery_flower_password(file_path, value=None):
def append_to_gitignore_file(ignored_line): def append_to_gitignore_file(ignored_line):
with open(".gitignore", "a") as gitignore_file: # noqa: PTH123 with Path(".gitignore").open("a") as gitignore_file:
gitignore_file.write(ignored_line) gitignore_file.write(ignored_line)
gitignore_file.write("\n") gitignore_file.write("\n")
def set_flags_in_envs(postgres_user, celery_flower_user, debug=False): # noqa: FBT002 def set_flags_in_envs(postgres_user, celery_flower_user, debug=False): # noqa: FBT002
local_django_envs_path = os.path.join(".envs", ".local", ".django") # noqa: PTH118 local_django_envs_path = Path(".envs", ".local", ".django")
production_django_envs_path = os.path.join(".envs", ".production", ".django") # noqa: PTH118 production_django_envs_path = Path(".envs", ".production", ".django")
local_postgres_envs_path = os.path.join(".envs", ".local", ".postgres") # noqa: PTH118 local_postgres_envs_path = Path(".envs", ".local", ".postgres")
production_postgres_envs_path = os.path.join(".envs", ".production", ".postgres") # noqa: PTH118 production_postgres_envs_path = Path(".envs", ".production", ".postgres")
set_django_secret_key(production_django_envs_path) set_django_secret_key(production_django_envs_path)
set_django_admin_url(production_django_envs_path) set_django_admin_url(production_django_envs_path)
@ -390,35 +371,35 @@ def set_flags_in_envs(postgres_user, celery_flower_user, debug=False): # noqa:
def set_flags_in_settings_files(): def set_flags_in_settings_files():
set_django_secret_key(os.path.join("config", "settings", "local.py")) # noqa: PTH118 set_django_secret_key(Path("config", "settings", "local.py"))
set_django_secret_key(os.path.join("config", "settings", "test.py")) # noqa: PTH118 set_django_secret_key(Path("config", "settings", "test.py"))
def remove_envs_and_associated_files(): def remove_envs_and_associated_files():
shutil.rmtree(".envs") shutil.rmtree(".envs")
os.remove("merge_production_dotenvs_in_dotenv.py") # noqa: PTH107 Path("merge_production_dotenvs_in_dotenv.py").unlink()
shutil.rmtree("tests") shutil.rmtree("tests")
def remove_celery_compose_dirs(): def remove_celery_compose_dirs():
shutil.rmtree(os.path.join("compose", "local", "django", "celery")) # noqa: PTH118 shutil.rmtree(Path("compose", "local", "django", "celery"))
shutil.rmtree(os.path.join("compose", "production", "django", "celery")) # noqa: PTH118 shutil.rmtree(Path("compose", "production", "django", "celery"))
def remove_node_dockerfile(): def remove_node_dockerfile():
shutil.rmtree(os.path.join("compose", "local", "node")) # noqa: PTH118 shutil.rmtree(Path("compose", "local", "node"))
def remove_aws_dockerfile(): def remove_aws_dockerfile():
shutil.rmtree(os.path.join("compose", "production", "aws")) # noqa: PTH118 shutil.rmtree(Path("compose", "production", "aws"))
def remove_drf_starter_files(): def remove_drf_starter_files():
os.remove(os.path.join("config", "api_router.py")) # noqa: PTH107, PTH118 Path("config", "api_router.py").unlink()
shutil.rmtree(os.path.join("{{cookiecutter.project_slug}}", "users", "api")) # noqa: PTH118 shutil.rmtree(Path("{{cookiecutter.project_slug}}", "users", "api"))
os.remove(os.path.join("{{cookiecutter.project_slug}}", "users", "tests", "test_drf_urls.py")) # noqa: PTH107, PTH118 Path("{{cookiecutter.project_slug}}", "users", "tests", "test_drf_urls.py").unlink()
os.remove(os.path.join("{{cookiecutter.project_slug}}", "users", "tests", "test_drf_views.py")) # noqa: PTH107, PTH118 Path("{{cookiecutter.project_slug}}", "users", "tests", "test_drf_views.py").unlink()
os.remove(os.path.join("{{cookiecutter.project_slug}}", "users", "tests", "test_swagger.py")) # noqa: PTH107, PTH118 Path("{{cookiecutter.project_slug}}", "users", "tests", "test_swagger.py").unlink()
def main(): # noqa: C901, PLR0912, PLR0915 def main(): # noqa: C901, PLR0912, PLR0915