refactor(core): improve error handling and remove boolean returns from functions
This commit is contained in:
7 files changed
+127
-99
No files matched your search
+15
-23
@@ -50,7 +50,7 @@ class Cli:
|
||||
self.app_names = []
|
||||
self.project_manager.app_names = self.app_names
|
||||
|
||||
steps: List[Tuple[str, Callable[[], bool]]] = []
|
||||
steps: List[Tuple[str, Callable[[], None]]] = []
|
||||
|
||||
steps.append(("Creating Django project", self.project_manager.create_project))
|
||||
|
||||
@@ -76,24 +76,25 @@ class Cli:
|
||||
]
|
||||
)
|
||||
|
||||
total_steps = len(steps)
|
||||
total_steps = len(steps)
|
||||
success = True
|
||||
|
||||
progress, task = UIFormatter.create_live_progress(description="Setup Progress", total_steps=total_steps)
|
||||
|
||||
with progress:
|
||||
for step_number, (description, step_func) in enumerate(steps, 1):
|
||||
result = step_func()
|
||||
if not result:
|
||||
success = False
|
||||
UIFormatter.print_error(f"Step {step_number} failed: {description}")
|
||||
break
|
||||
try:
|
||||
with progress:
|
||||
for step_number, (description, step_func) in enumerate(steps, 1):
|
||||
step_func()
|
||||
progress.update(task, advance=1, description=f"Step {step_number}/{total_steps}")
|
||||
|
||||
progress.update(task, advance=1, description=f"Step {step_number}/{total_steps}")
|
||||
except Exception as e:
|
||||
success = False
|
||||
UIFormatter.handle_exception(e)
|
||||
|
||||
return success
|
||||
|
||||
def _create_utility_files(self) -> bool:
|
||||
def _create_utility_files(self) -> None:
|
||||
utility_steps = [
|
||||
self.file_manager.create_gitignore,
|
||||
self.file_manager.create_requirements,
|
||||
@@ -103,25 +104,16 @@ class Cli:
|
||||
]
|
||||
|
||||
for step_func in utility_steps:
|
||||
result = step_func()
|
||||
if not result:
|
||||
return False
|
||||
step_func()
|
||||
|
||||
UIFormatter.print_success("Created all utility files successfully!")
|
||||
return True
|
||||
|
||||
def _create_cicd_pipelines(self) -> bool:
|
||||
def _create_cicd_pipelines(self) -> None:
|
||||
if self.metadata.get("use_github_actions", True):
|
||||
result = self.file_manager.create_github_actions()
|
||||
if not result:
|
||||
return False
|
||||
self.file_manager.create_github_actions()
|
||||
|
||||
if self.metadata.get("use_gitlab_ci", True):
|
||||
result = self.file_manager.create_gitlab_ci()
|
||||
if not result:
|
||||
return False
|
||||
|
||||
return True
|
||||
self.file_manager.create_gitlab_ci()
|
||||
|
||||
def generate_secret_keys(self) -> bool:
|
||||
generate_secret_command()
|
||||
|
||||
+27
-33
@@ -35,12 +35,12 @@ class FileManager:
|
||||
message: str,
|
||||
base_dir: str = None,
|
||||
should_format: bool = False,
|
||||
) -> bool:
|
||||
) -> None:
|
||||
"""Helper to render template and create file."""
|
||||
target_dir = base_dir or self.project_root
|
||||
with change_cwd(target_dir):
|
||||
content = template_engine.render_template(template_path, context)
|
||||
return create_file_with_content(filepath, content, message, should_format=should_format)
|
||||
create_file_with_content(filepath, content, message, should_format=should_format)
|
||||
|
||||
def _create_files_from_specs(self, base_dir: str, folder_specs: dict, base_context: dict = None) -> None:
|
||||
"""Helper to create multiple folders and files from a specification dict."""
|
||||
@@ -66,22 +66,22 @@ class FileManager:
|
||||
message = f"Created {prefix}{subdir}/__init__.py" if prefix else f"Created {subdir}/__init__.py"
|
||||
create_directory_with_init(subdir_path, message)
|
||||
|
||||
def create_gitignore(self) -> bool:
|
||||
return self._render_and_create_file(".gitignore", "project/gitignore.j2", {}, "Created .gitignore file")
|
||||
def create_gitignore(self) -> None:
|
||||
self._render_and_create_file(".gitignore", "project/gitignore.j2", {}, "Created .gitignore file")
|
||||
|
||||
def create_requirements(self) -> bool:
|
||||
def create_requirements(self) -> None:
|
||||
context = {
|
||||
"use_database_url": self.metadata.get("use_database_url", True),
|
||||
"database_type": self.metadata.get("database_type", "postgresql"),
|
||||
}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
"requirements.txt",
|
||||
"project/requirements.j2",
|
||||
context,
|
||||
"Created requirements.txt with Django dependencies",
|
||||
)
|
||||
|
||||
def create_readme(self) -> bool:
|
||||
def create_readme(self) -> None:
|
||||
context = {
|
||||
"project_name": self.project_name,
|
||||
"app_names": self.app_names,
|
||||
@@ -89,41 +89,41 @@ class FileManager:
|
||||
"unified_structure": bool(self.metadata.get("unified_structure")),
|
||||
"module_name": self.module_name,
|
||||
}
|
||||
return self._render_and_create_file("README.md", "project/readme.j2", context, "Created README.md file")
|
||||
self._render_and_create_file("README.md", "project/readme.j2", context, "Created README.md file")
|
||||
|
||||
def create_env_file(self) -> bool:
|
||||
def create_env_file(self) -> None:
|
||||
"""Create .env.sample file with environment variables."""
|
||||
context = {
|
||||
"project_name": self.module_name,
|
||||
"use_database_url": self.metadata.get("use_database_url", True),
|
||||
"database_type": self.metadata.get("database_type", "postgresql"),
|
||||
}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
".env.sample",
|
||||
"project/env_sample.j2",
|
||||
context,
|
||||
"Created .env.sample file with generated secret key",
|
||||
)
|
||||
|
||||
def create_pyproject_toml(self, metadata: dict) -> bool:
|
||||
def create_pyproject_toml(self, metadata: dict) -> None:
|
||||
package_name = metadata.get("package_name", "backend")
|
||||
package_name = get_package_name(package_name)
|
||||
context = {"package_name": package_name, "project_name": self.project_name}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
"pyproject.toml",
|
||||
"project/pyproject_toml.j2",
|
||||
context,
|
||||
"Created pyproject.toml file for uv",
|
||||
)
|
||||
|
||||
def create_project_urls(self) -> bool:
|
||||
def create_project_urls(self) -> None:
|
||||
"""Create project urls.py using project_urls.j2 template (replaces update_project_urls)."""
|
||||
effective_app_modules = calculate_app_module_paths(self.app_names, self.metadata)
|
||||
context = {
|
||||
"project_name": self.project_name,
|
||||
"app_names": effective_app_modules,
|
||||
}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
"urls.py",
|
||||
"config/urls/with_apps.j2",
|
||||
context,
|
||||
@@ -132,16 +132,16 @@ class FileManager:
|
||||
should_format=True,
|
||||
)
|
||||
|
||||
def create_justfile(self) -> bool:
|
||||
def create_justfile(self) -> None:
|
||||
context = {"project_name": self.project_name}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
"justfile",
|
||||
"project/justfile.j2",
|
||||
context,
|
||||
"Created justfile with Django development tasks",
|
||||
)
|
||||
|
||||
def create_predefined_structure(self) -> bool:
|
||||
def create_predefined_structure(self) -> None:
|
||||
apps_dir = os.path.join(self.project_root, "apps")
|
||||
create_directory_with_init(apps_dir, "Created apps/__init__.py")
|
||||
|
||||
@@ -200,9 +200,7 @@ class FileManager:
|
||||
should_format=True,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def create_unified_structure(self) -> bool:
|
||||
def create_unified_structure(self) -> None:
|
||||
# 1. Create 'core' directory (Project Config)
|
||||
core_dir = os.path.join(self.project_root, "core")
|
||||
create_directory_with_init(core_dir, "Created core/__init__.py")
|
||||
@@ -282,9 +280,7 @@ class FileManager:
|
||||
should_format=True,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def create_single_structure(self) -> bool:
|
||||
def create_single_structure(self) -> None:
|
||||
project_dir = os.path.join(self.project_root, self.module_name)
|
||||
create_directory_with_init(project_dir, f"Created {self.module_name}/__init__.py")
|
||||
|
||||
@@ -360,32 +356,30 @@ class FileManager:
|
||||
f"Created {self.module_name}/models/README.md",
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def create_procfile(self) -> bool:
|
||||
def create_procfile(self) -> None:
|
||||
context = {"project_name": self.project_name}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
"Procfile",
|
||||
"project/procfile.j2",
|
||||
context,
|
||||
"Created Procfile with Gunicorn configuration",
|
||||
)
|
||||
|
||||
def create_runtime_txt(self) -> bool:
|
||||
def create_runtime_txt(self) -> None:
|
||||
context = {"python_version": "3.13"}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
"runtime.txt",
|
||||
"project/runtime_txt.j2",
|
||||
context,
|
||||
"Created runtime.txt with Python version specification",
|
||||
)
|
||||
|
||||
def create_github_actions(self) -> bool:
|
||||
def create_github_actions(self) -> None:
|
||||
github_dir = os.path.join(self.project_root, ".github", "workflows")
|
||||
os.makedirs(github_dir, exist_ok=True)
|
||||
context = {"project_name": self.project_name, "module_name": self.module_name}
|
||||
workflow_file = os.path.join(github_dir, "ci.yml")
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
workflow_file,
|
||||
"project/ci/github_actions.j2",
|
||||
context,
|
||||
@@ -393,9 +387,9 @@ class FileManager:
|
||||
base_dir=self.project_root,
|
||||
)
|
||||
|
||||
def create_gitlab_ci(self) -> bool:
|
||||
def create_gitlab_ci(self) -> None:
|
||||
context = {"project_name": self.project_name, "module_name": self.module_name}
|
||||
return self._render_and_create_file(
|
||||
self._render_and_create_file(
|
||||
".gitlab-ci.yml",
|
||||
"project/ci/gitlab_ci.j2",
|
||||
context,
|
||||
|
||||
+19
-27
@@ -26,16 +26,12 @@ class ProjectManager:
|
||||
self.project_root = os.getcwd() if project_dir == "." else os.path.join(os.getcwd(), project_dir)
|
||||
self.module_name = metadata.get("project_module_name") or self.project_name
|
||||
|
||||
def create_project(self) -> bool:
|
||||
def create_project(self) -> None:
|
||||
os.makedirs(self.project_root, exist_ok=True)
|
||||
|
||||
unified = self.metadata.get("unified_structure", False)
|
||||
success = DjangoHelper.startproject(self.module_name, self.project_root, unified=unified)
|
||||
if success:
|
||||
UIFormatter.print_success(f"Django project '{self.project_name}' created successfully!")
|
||||
else:
|
||||
UIFormatter.print_error(f"Failed to create Django project '{self.project_name}'")
|
||||
return success
|
||||
DjangoHelper.startproject(self.module_name, self.project_root, unified=unified)
|
||||
UIFormatter.print_success(f"Django project '{self.project_name}' created successfully!")
|
||||
|
||||
def _get_apps_base_dir(self) -> str:
|
||||
"""Get the base directory for apps, considering nested structure."""
|
||||
@@ -44,36 +40,30 @@ class ProjectManager:
|
||||
apps_base_dir = os.path.join(self.project_root, self.metadata.get("nested_dir"))
|
||||
return apps_base_dir
|
||||
|
||||
def create_apps(self) -> bool:
|
||||
def create_apps(self) -> None:
|
||||
apps_base_dir = self._get_apps_base_dir()
|
||||
|
||||
if apps_base_dir != self.project_root:
|
||||
create_directory_with_init(apps_base_dir, f"Created {os.path.basename(apps_base_dir)}/__init__.py")
|
||||
|
||||
for app_name in self.app_names:
|
||||
success = DjangoHelper.startapp(app_name, apps_base_dir)
|
||||
if not success:
|
||||
UIFormatter.print_error(f"Failed to create Django app '{app_name}'")
|
||||
return False
|
||||
DjangoHelper.startapp(app_name, apps_base_dir)
|
||||
UIFormatter.print_success(f"Django app '{app_name}' created successfully!")
|
||||
|
||||
if not self.add_apps_to_settings():
|
||||
return False
|
||||
self.add_apps_to_settings()
|
||||
|
||||
return True
|
||||
|
||||
def add_apps_to_settings(self) -> bool:
|
||||
def add_apps_to_settings(self) -> None:
|
||||
"""Add all apps to USER_DEFINED_APPS in base.py settings file."""
|
||||
base_settings_path = get_base_settings_path(self.project_root, self.module_name)
|
||||
|
||||
if not os.path.exists(base_settings_path):
|
||||
UIFormatter.print_error("Could not find base.py settings file")
|
||||
return False
|
||||
from djinit.utils.exceptions import ConfigError
|
||||
raise ConfigError("Could not find base.py settings file")
|
||||
|
||||
content = read_base_settings(self.project_root, self.module_name)
|
||||
if content is None:
|
||||
UIFormatter.print_error("Could not read base.py settings file")
|
||||
return False
|
||||
from djinit.utils.exceptions import ConfigError
|
||||
raise ConfigError("Could not read base.py settings file")
|
||||
|
||||
app_module_paths = calculate_app_module_paths(self.app_names, self.metadata)
|
||||
|
||||
@@ -82,20 +72,20 @@ class ProjectManager:
|
||||
|
||||
if not apps_to_add:
|
||||
UIFormatter.print_success("All apps already configured in USER_DEFINED_APPS")
|
||||
return True
|
||||
return
|
||||
|
||||
updated_content = insert_apps_into_user_defined_apps(content, apps_to_add)
|
||||
if not updated_content:
|
||||
return False
|
||||
from djinit.utils.exceptions import ConfigError
|
||||
raise ConfigError("Could not update USER_DEFINED_APPS in base.py")
|
||||
|
||||
with open(base_settings_path, "w") as f:
|
||||
f.write(updated_content)
|
||||
|
||||
added_apps_str = ", ".join(apps_to_add)
|
||||
UIFormatter.print_success(f"Added apps to USER_DEFINED_APPS: {added_apps_str}")
|
||||
return True
|
||||
|
||||
def validate_project_structure(self) -> bool:
|
||||
def validate_project_structure(self) -> None:
|
||||
required_files = [
|
||||
os.path.join(self.project_root, "manage.py"),
|
||||
os.path.join(self.project_root, self.module_name, "__init__.py"),
|
||||
@@ -154,9 +144,11 @@ class ProjectManager:
|
||||
|
||||
if not missing_files:
|
||||
UIFormatter.print_success("Project structure validation passed")
|
||||
return True
|
||||
return
|
||||
|
||||
UIFormatter.print_error("Project structure validation failed:")
|
||||
for file_path in missing_files:
|
||||
UIFormatter.print_error(f" Missing: {file_path}")
|
||||
return False
|
||||
|
||||
from djinit.utils.exceptions import ConfigError
|
||||
raise ConfigError("Project structure validation failed", details=f"Missing files: {missing_files}")
|
||||
@@ -178,3 +178,20 @@ class UIFormatter:
|
||||
message = f"{message} [{default}]"
|
||||
response = console.input(f"[bold cyan]?[/bold cyan] {message}: ").strip()
|
||||
return response or default or ""
|
||||
|
||||
@staticmethod
|
||||
def handle_exception(e: Exception):
|
||||
"""Handle and display exceptions gracefully"""
|
||||
from djinit.utils.exceptions import DjinitError
|
||||
|
||||
if isinstance(e, DjinitError):
|
||||
UIFormatter.print_error(e.message, details=e.details)
|
||||
else:
|
||||
console.print("\n")
|
||||
console.print(f"[bold red]{'═' * 70}[/bold red]")
|
||||
console.print(f"[bold red]{'💥 UNEXPECTED ERROR'.center(70)}[/bold red]")
|
||||
console.print(f"[bold red]{'═' * 70}[/bold red]\n")
|
||||
console.print(f"[red]An unexpected error occurred: {str(e)}[/red]")
|
||||
console.print("[dim]Please report this issue on GitHub.[/dim]\n")
|
||||
# Optionally print traceback for debugging if needed, or log it
|
||||
# console.print_exception()
|
||||
+15
-5
@@ -17,14 +17,19 @@ def format_file(filename: str) -> None:
|
||||
subprocess.run([sys.executable, "-m", "ruff", "format", filename], check=False, capture_output=True)
|
||||
|
||||
|
||||
def create_file_with_content(filename: str, content: str, success_message: str, should_format: bool = False) -> bool:
|
||||
with open(filename, "w") as file:
|
||||
file.write(content)
|
||||
def create_file_with_content(filename: str, content: str, success_message: str, should_format: bool = False) -> None:
|
||||
from djinit.utils.exceptions import FileError
|
||||
|
||||
try:
|
||||
with open(filename, "w") as file:
|
||||
file.write(content)
|
||||
except OSError as e:
|
||||
raise FileError(f"Failed to write file: {filename}", details=str(e))
|
||||
|
||||
if should_format:
|
||||
format_file(filename)
|
||||
|
||||
return True
|
||||
UIFormatter.print_success(success_message)
|
||||
|
||||
|
||||
def create_file_from_template(
|
||||
@@ -34,7 +39,12 @@ def create_file_from_template(
|
||||
success_message: str,
|
||||
should_format: bool = True,
|
||||
) -> None:
|
||||
content = template_engine.render_template(template_path, context)
|
||||
try:
|
||||
content = template_engine.render_template(template_path, context)
|
||||
except Exception as e:
|
||||
from djinit.utils.exceptions import TemplateError
|
||||
raise TemplateError(f"Failed to render template: {template_path}", details=str(e))
|
||||
|
||||
create_file_with_content(file_path, content, success_message, should_format=should_format)
|
||||
|
||||
|
||||
|
||||
+7
-11
@@ -20,7 +20,7 @@ class DjangoHelper:
|
||||
DJANGO_VERSION = DJANGO_VERSION
|
||||
|
||||
@staticmethod
|
||||
def startproject(project_name: str, directory: str, unified: bool = False) -> bool:
|
||||
def startproject(project_name: str, directory: str, unified: bool = False) -> None:
|
||||
try:
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
|
||||
@@ -29,7 +29,7 @@ class DjangoHelper:
|
||||
os.chmod(manage_py_path, 0o755)
|
||||
|
||||
if unified:
|
||||
return True
|
||||
return
|
||||
|
||||
project_config_dir = os.path.join(directory, project_name)
|
||||
create_directory_with_init(project_config_dir, f"Created {project_name}/__init__.py")
|
||||
@@ -53,14 +53,12 @@ class DjangoHelper:
|
||||
]
|
||||
create_files_from_templates(project_config_dir, project_files, f"{project_name}/")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
UIFormatter.print_error(f"Error creating Django project: {e}")
|
||||
return False
|
||||
from djinit.utils.exceptions import DjinitError
|
||||
raise DjinitError(f"Error creating Django project: {e}", details=str(e))
|
||||
|
||||
@staticmethod
|
||||
def startapp(app_name: str, directory: str) -> bool:
|
||||
def startapp(app_name: str, directory: str) -> None:
|
||||
try:
|
||||
app_dir = os.path.join(directory, app_name)
|
||||
os.makedirs(app_dir, exist_ok=True)
|
||||
@@ -85,8 +83,6 @@ class DjangoHelper:
|
||||
migrations_dir = os.path.join(app_dir, "migrations")
|
||||
create_directory_with_init(migrations_dir, f"Created {app_name}/migrations/__init__.py")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
UIFormatter.print_error(f"Error creating Django app: {e}")
|
||||
return False
|
||||
from djinit.utils.exceptions import DjinitError
|
||||
raise DjinitError(f"Error creating Django app: {e}", details=str(e))
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
Custom exceptions for djinit.
|
||||
"""
|
||||
|
||||
|
||||
class DjinitError(Exception):
|
||||
"""Base exception for all djinit errors."""
|
||||
|
||||
def __init__(self, message: str, details: str = None):
|
||||
self.message = message
|
||||
self.details = details
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class ConfigError(DjinitError):
|
||||
"""Raised when there is a configuration or metadata error."""
|
||||
pass
|
||||
|
||||
|
||||
class FileError(DjinitError):
|
||||
"""Raised when a file operation fails."""
|
||||
pass
|
||||
|
||||
|
||||
class TemplateError(DjinitError):
|
||||
"""Raised when template rendering fails."""
|
||||
pass
|
||||
Reference in new issue
Block a user