diff --git a/djinit/cli.py b/djinit/cli.py index bf648fe..f17d3a3 100644 --- a/djinit/cli.py +++ b/djinit/cli.py @@ -6,13 +6,10 @@ Coordinates between different managers to create a complete Django project. import os from typing import Callable, List, Tuple -from djinit.scripts.cicd_config_generator import CICDConfigGenerator from djinit.scripts.console_ui import UIFormatter -from djinit.scripts.deployment_files_generator import DeploymentConfigGenerator from djinit.scripts.files import FileManager from djinit.scripts.project import ProjectManager from djinit.scripts.secretkey_generator import generate_secret_command -from djinit.scripts.settings import SettingsManager class Cli: @@ -22,39 +19,24 @@ class Cli: self.primary_app = primary_app self.app_names = app_names self.metadata = metadata - # Handle '.' for current directory - if project_dir == ".": + if project_dir == ".": # handle '.' for current directory self.project_root = os.getcwd() else: self.project_root = os.path.join(os.getcwd(), project_dir) - # Initialize managers self.project_manager = ProjectManager(project_dir, project_name, app_names, metadata) - self.settings_manager = SettingsManager(self.project_root, project_name, app_names, metadata) self.file_manager = FileManager(self.project_root, project_name, app_names, metadata) - self.deployment_manager = DeploymentConfigGenerator(self.project_root, project_name) - self.cicd_manager = CICDConfigGenerator(self.project_root, project_name) def run_setup(self) -> bool: steps: List[Tuple[str, Callable[[], bool]]] = [ ("Creating Django project", self.project_manager.create_project), ("Creating Django apps", self.project_manager.create_apps), + ("Creating project URLs", self.file_manager.create_project_urls), ("Validating project structure", self.project_manager.validate_project_structure), - ("Setting up project structure", self.settings_manager.create_settings_structure), - ("Configuring base settings", self.settings_manager.update_base_settings), - ("Configuring development settings", self.settings_manager.update_development_settings), - ("Configuring production settings", self.settings_manager.update_production_settings), ("Creating utility files", self._create_utility_files), - ("Setting up app URLs", self.file_manager.create_app_urls), - ("Creating app serializers", self.file_manager.create_app_serializers), - ("Creating app routes", self.file_manager.create_app_routes), - ("Configuring comprehensive URLs", self.file_manager.update_project_urls), - ("Updating WSGI configuration", self.file_manager.update_wsgi_file), - ("Updating ASGI configuration", self.file_manager.update_asgi_file), - ("Updating manage.py", self.file_manager.update_manage_py), - ("Creating Justfile", self.deployment_manager.create_justfile), - ("Creating Procfile", self.deployment_manager.create_procfile), - ("Creating runtime.txt", lambda: self.deployment_manager.create_runtime_txt("3.13")), + ("Creating Procfile", self.file_manager.create_procfile), + ("Creating Justfile", self.file_manager.create_justfile), + ("Creating runtime.txt", self.file_manager.create_runtime_txt), ("Creating CI/CD pipelines", self._create_cicd_pipelines), ] @@ -97,12 +79,12 @@ class Cli: def _create_cicd_pipelines(self) -> bool: if self.metadata.get("use_github_actions", True): - result = self.cicd_manager.create_github_actions() + result = self.file_manager.create_github_actions() if not result: return False if self.metadata.get("use_gitlab_ci", True): - result = self.cicd_manager.create_gitlab_ci() + result = self.file_manager.create_gitlab_ci() if not result: return False diff --git a/djinit/generator.py b/djinit/generator.py index 2c97a5b..2a6691d 100644 --- a/djinit/generator.py +++ b/djinit/generator.py @@ -25,7 +25,6 @@ def clear_screen() -> None: def main() -> None: - # Parse command line arguments args = parse_arguments() # Handle secret command @@ -39,7 +38,6 @@ def main() -> None: return # Default to setup command - # Clear screen clear_screen() # Display welcome screen @@ -47,15 +45,12 @@ def main() -> None: console.print(UIFormatter.create_welcome_panel()) console.print() - # Get user input project_dir, project_name, primary_app, app_names, metadata = get_user_input() - # Confirm setup if not confirm_setup(project_dir, project_name, app_names, metadata): UIFormatter.print_info("Setup cancelled by user.") return - # Run setup console.print() UIFormatter.print_info("Starting Django project setup...") console.print() @@ -63,10 +58,7 @@ def main() -> None: django_cli = Cli(project_dir, project_name, primary_app, app_names, metadata) success = django_cli.run_setup() - # Display completion summary UIFormatter.create_summary_panel(project_dir, project_name, app_names, True) - - # Exit with appropriate code sys.exit(0 if success else 1) diff --git a/djinit/scripts/app_generator.py b/djinit/scripts/app_generator.py index 02b69a2..5ed1037 100644 --- a/djinit/scripts/app_generator.py +++ b/djinit/scripts/app_generator.py @@ -4,13 +4,19 @@ Handles creation of Django apps and updating settings. """ import os -import subprocess -import sys from typing import Optional from djinit.scripts.console_ui import UIFormatter -from djinit.scripts.template_engine import template_engine -from djinit.utils import change_cwd, create_file_with_content +from djinit.scripts.django_helper import DjangoHelper +from djinit.utils import ( + calculate_app_module_path, + detect_nested_structure_from_settings, + extract_existing_apps, + find_project_dir, + find_settings_path, + insert_apps_into_user_defined_apps, + is_django_project, +) class AppManager: @@ -36,43 +42,36 @@ class AppManager: if not self._add_to_installed_apps(): return False - if not self._create_additional_files(): - return False - UIFormatter.print_success(f"Django app '{self.app_name}' created and configured successfully!") return True def _is_django_project(self) -> bool: - return os.path.exists(self.manage_py_path) + return is_django_project(self.current_dir) def _app_exists(self) -> bool: - # Detect project structure to check in correct location is_nested, nested_dir, apps_base_dir = self._detect_project_structure() app_path = os.path.join(apps_base_dir, self.app_name) return os.path.exists(app_path) def _create_django_app(self) -> bool: - # Detect project structure + # Find where to create the app (flat or nested structure) is_nested, nested_dir, apps_base_dir = self._detect_project_structure() - # manage.py is always in the project root (current_dir), not in the project directory + # Verify manage.py exists in project root manage_py_path = os.path.join(self.current_dir, "manage.py") if not os.path.exists(manage_py_path): UIFormatter.print_error("Could not find manage.py file in project root") return False - # Create app in the correct location - # Use 'python -m django' instead of 'django-admin' for better compatibility - with change_cwd(apps_base_dir): - subprocess.run( - [sys.executable, "-m", "django", "startapp", self.app_name], capture_output=True, text=True, check=True - ) - - UIFormatter.print_success(f"Created Django app '{self.app_name}' in {apps_base_dir}") - return True + success = DjangoHelper.startapp(self.app_name, apps_base_dir) + if success: + UIFormatter.print_success(f"Created Django app '{self.app_name}' in {apps_base_dir}") + else: + UIFormatter.print_error(f"Failed to create Django app '{self.app_name}'") + return success def _add_to_installed_apps(self) -> bool: - settings_path = self._find_settings_path() + settings_path = find_settings_path(self.current_dir) if not settings_path: UIFormatter.print_error("Could not find Django settings directory") return False @@ -85,30 +84,13 @@ class AppManager: with open(base_settings_path) as f: content = f.read() - # Detect project structure to determine the correct app module path + # Get the app's module path (e.g., "apps.users" or just "users") is_nested, nested_dir, apps_base_dir = self._detect_project_structure() + app_module_path = calculate_app_module_path(self.app_name, is_nested, nested_dir) - # Determine the correct module path for the app - if is_nested and nested_dir: - app_module_path = f"{nested_dir}.{self.app_name}" - else: - app_module_path = self.app_name - - # Check if app is already in USER_DEFINED_APPS section specifically - lines = content.split("\n") - in_user_apps = False - app_already_exists = False - - for line in lines: - if "USER_DEFINED_APPS" in line and "=" in line: - in_user_apps = True - elif in_user_apps and line.strip() == "]": - in_user_apps = False - elif in_user_apps and (f'"{app_module_path}"' in line or f"'{app_module_path}'" in line): - app_already_exists = True - break - - if app_already_exists: + # Check if app is already in USER_DEFINED_APPS + existing_apps = extract_existing_apps(content) + if app_module_path in existing_apps: UIFormatter.print_success(f"App '{app_module_path}' already configured in USER_DEFINED_APPS") return True @@ -116,143 +98,23 @@ class AppManager: UIFormatter.print_error("Could not find USER_DEFINED_APPS section in base.py") return False - lines = content.split("\n") - new_lines = [] - in_user_apps = False - apps_added = False - - for line in lines: - if "USER_DEFINED_APPS" in line and "=" in line: - in_user_apps = True - new_lines.append(line) - elif in_user_apps and line.strip() == "]": - new_lines.append(f' "{app_module_path}",') - new_lines.append(line) - in_user_apps = False - apps_added = True - else: - new_lines.append(line) - - if not apps_added: - UIFormatter.print_error("Could not find USER_DEFINED_APPS section in base.py") + # Add app to USER_DEFINED_APPS list in settings file + updated_content = insert_apps_into_user_defined_apps(content, [app_module_path]) + if not updated_content: return False with open(base_settings_path, "w") as f: - f.write("\n".join(new_lines)) + f.write(updated_content) UIFormatter.print_success(f"Added '{app_module_path}' to USER_DEFINED_APPS in base.py") return True - def _find_settings_path(self) -> Optional[str]: - # Look for project directories that contain settings - for item in os.listdir(self.current_dir): - if os.path.isdir(item) and not item.startswith(".") and item != "__pycache__": - # Check if this directory contains Django project files - project_path = os.path.join(self.current_dir, item) - settings_path = os.path.join(project_path, "settings") - - # Check if settings directory exists with base.py - if os.path.exists(settings_path) and os.path.exists(os.path.join(settings_path, "base.py")): - return settings_path - - # Fallback: look for settings in current directory - settings_path = os.path.join(self.current_dir, "settings") - if os.path.exists(settings_path) and os.path.exists(os.path.join(settings_path, "base.py")): - return settings_path - - return None - def _detect_project_structure(self) -> tuple[bool, Optional[str], str]: - # Step 1: find project directory containing settings/base.py - project_dir: Optional[str] = None - settings_base_path: Optional[str] = None - for item in os.listdir(self.current_dir): - if os.path.isdir(item) and not item.startswith(".") and item != "__pycache__": - candidate = os.path.join(self.current_dir, item) - base_py = os.path.join(candidate, "settings", "base.py") - if os.path.exists(base_py): - project_dir = candidate - settings_base_path = base_py - break - - # Fallback: current_dir/settings/base.py - if project_dir is None: - base_py = os.path.join(self.current_dir, "settings", "base.py") - if os.path.exists(base_py): - project_dir = self.current_dir - settings_base_path = base_py + # Find project directory with settings/base.py + project_dir, settings_base_path = find_project_dir(self.current_dir) if project_dir is None: - # Not a Django project structure return False, None, self.current_dir - # Step 2: try to infer nested_dir from USER_DEFINED_APPS in base.py - try: - if settings_base_path and os.path.exists(settings_base_path): - with open(settings_base_path) as f: - base_content = f.read() - # Find lines inside USER_DEFINED_APPS and extract first dotted app - in_user_apps = False - for line in base_content.splitlines(): - if "USER_DEFINED_APPS" in line and "=" in line: - in_user_apps = True - continue - if in_user_apps and "]" in line: - break - if in_user_apps: - line_stripped = line.strip().strip(",") - if line_stripped.startswith('"') or line_stripped.startswith("'"): - app_label = line_stripped.strip("\"'") - if "." in app_label: - prefix = app_label.split(".", 1)[0] - nested_path = os.path.join(self.current_dir, prefix) - if os.path.isdir(nested_path): - return True, prefix, nested_path - except Exception: - # Ignore parsing issues and continue with heuristics - pass - - # Step 3: look for existing package directories in project root - preferred = ["apps", "modules", "packages"] - for name in preferred: - nested_path = os.path.join(self.current_dir, name) - if os.path.isdir(nested_path) and os.path.exists(os.path.join(nested_path, "__init__.py")): - return True, name, nested_path - - # Any other directory with __init__.py qualifies as a package - for item in os.listdir(self.current_dir): - if item in ("__pycache__",) or item.startswith("."): - continue - nested_path = os.path.join(self.current_dir, item) - if os.path.isdir(nested_path) and os.path.exists(os.path.join(nested_path, "__init__.py")): - return True, item, nested_path - - # Step 4: fallback - return False, None, self.current_dir - - def _create_additional_files(self) -> bool: - """Create additional files for the app (serializers.py, routes.py).""" - # Detect project structure to get correct app path - is_nested, nested_dir, apps_base_dir = self._detect_project_structure() - app_path = os.path.join(apps_base_dir, self.app_name) - - # Create serializers.py - context = {"app_name": self.app_name} - serializers_content = template_engine.render_template("serializers.j2", context) - create_file_with_content( - os.path.join(app_path, "serializers.py"), - serializers_content, - f"Created {self.app_name}/serializers.py", - should_format=True, - ) - - # Create routes.py - routes_content = template_engine.render_template("routes.j2", context) - create_file_with_content( - os.path.join(app_path, "routes.py"), - routes_content, - f"Created {self.app_name}/routes.py", - should_format=True, - ) - - return True + # Detect nested structure from settings file + return detect_nested_structure_from_settings(settings_base_path, self.current_dir) diff --git a/djinit/scripts/cicd_config_generator.py b/djinit/scripts/cicd_config_generator.py deleted file mode 100644 index df5b7b9..0000000 --- a/djinit/scripts/cicd_config_generator.py +++ /dev/null @@ -1,41 +0,0 @@ -""" -CI/CD pipeline manager for djinit -Handles creation of Github Actions and GitLab CI onfigurations -""" - -import os - -from djinit.scripts.template_engine import template_engine -from djinit.utils import change_cwd, create_file_with_content - - -class CICDConfigGenerator: - def __init__(self, project_root: str, project_name: str): - self.project_root = project_root - self.project_name = project_name - - def create_github_actions(self) -> bool: - with change_cwd(self.project_root): - github_dir = os.path.join(self.project_root, ".github", "workflows") - os.makedirs(github_dir, exist_ok=True) - - context = {"project_name": self.project_name} - workflow_content = template_engine.render_template("github_actions_ci.j2", context) - workflow_file = os.path.join(github_dir, "ci.yml") - create_file_with_content( - workflow_file, - workflow_content, - "Created Github Actions workflow (ci.yml)", - ) - return True - - def create_gitlab_ci(self) -> bool: - with change_cwd(self.project_root): - context = {"project_name": self.project_name} - gitlab_ci_content = template_engine.render_template("gitlab_ci.j2", context) - create_file_with_content( - ".gitlab-ci.yml", - gitlab_ci_content, - "Created GitLab CI configuration (.gitlab-ci.yml)", - ) - return True diff --git a/djinit/scripts/command_handler.py b/djinit/scripts/command_handler.py index 9f2901a..06d0c56 100644 --- a/djinit/scripts/command_handler.py +++ b/djinit/scripts/command_handler.py @@ -6,8 +6,13 @@ Handles different commands like secret key generation and app creation. import argparse import sys +from rich.panel import Panel +from rich.text import Text + +from djinit.scripts.app_generator import AppManager from djinit.scripts.console_ui import UIColors, UIFormatter, console from djinit.scripts.name_validator import validate_app_name +from djinit.scripts.secretkey_generator import display_secret_keys, generate_multiple_keys def parse_arguments() -> argparse.Namespace: @@ -43,19 +48,10 @@ def parse_arguments() -> argparse.Namespace: def handle_secret_command(args: argparse.Namespace) -> None: - from djinit.scripts.secretkey_generator import display_secret_keys, generate_multiple_keys - - # Generate keys keys = generate_multiple_keys(args.count, args.length) - - # Display results UIFormatter.print_info("") display_secret_keys(keys) - # Show usage instructions - from rich.panel import Panel - from rich.text import Text - instructions = Text() instructions.append("📋 Usage Instructions:\n", style=UIColors.ACCENT) instructions.append("1. Copy the appropriate secret key for your environment\n") @@ -70,9 +66,6 @@ def handle_secret_command(args: argparse.Namespace) -> None: def handle_app_command(args: argparse.Namespace) -> None: - from djinit.scripts.app_generator import AppManager - - # Display welcome message UIFormatter.print_info("") UIFormatter.print_header("Django App Creation") UIFormatter.print_info("") @@ -103,7 +96,6 @@ def handle_app_command(args: argparse.Namespace) -> None: deduped_names.append(name) seen.add(name) - # Validate all names first for name in deduped_names: is_valid, error_msg = validate_app_name(name) if not is_valid: @@ -124,10 +116,6 @@ def handle_app_command(args: argparse.Namespace) -> None: if any_failure: sys.exit(1) - # Show next steps - from rich.panel import Panel - from rich.text import Text - instructions = Text() instructions.append("🚀 Next Steps:\n", style=UIColors.ACCENT) instructions.append("1. The app(s) have been added to INSTALLED_APPS in settings/base.py\n") diff --git a/djinit/scripts/deployment_files_generator.py b/djinit/scripts/deployment_files_generator.py deleted file mode 100644 index 5bf0d95..0000000 --- a/djinit/scripts/deployment_files_generator.py +++ /dev/null @@ -1,118 +0,0 @@ -""" -Deployment file generator for djinit. -Handles creation of Justfile, Procfile, and deployment-related files. -""" - -from djinit.scripts.template_engine import template_engine -from djinit.utils import change_cwd, create_file_with_content - - -class DeploymentConfigGenerator: - def __init__(self, project_root: str, project_name: str): - self.project_root = project_root - self.project_name = project_name - - def create_justfile(self) -> bool: - with change_cwd(self.project_root): - context = {"project_name": self.project_name} - justfile_content = template_engine.render_template("justfile.j2", context) - create_file_with_content( - "justfile", - justfile_content, - "Created justfile with Django development tasks", - ) - return True - - def create_procfile(self) -> bool: - with change_cwd(self.project_root): - context = {"project_name": self.project_name} - procfile_content = template_engine.render_template("procfile.j2", context) - create_file_with_content( - "Procfile", - procfile_content, - "Created Procfile with Gunicorn configuration", - ) - return True - - def create_gunicorn_config(self) -> bool: - with change_cwd(self.project_root): - gunicorn_config_content = f"""# Gunicorn configuration file for {self.project_name} -# Usage: gunicorn -c gunicorn_config.py {self.project_name}.wsgi:application - -import multiprocessing - -# Server socket -bind = "0.0.0.0:8000" -backlog = 2048 - -# Worker processes -workers = multiprocessing.cpu_count() * 2 + 1 -worker_class = "sync" -worker_connections = 1000 -timeout = 120 -keepalive = 5 - -# Logging -accesslog = "-" -errorlog = "-" -loglevel = "info" -access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' - -# Process naming -proc_name = "{self.project_name}" - -# Server mechanics -daemon = False -pidfile = None -umask = 0 -user = None -group = None -tmp_upload_dir = None - -# SSL (uncomment and configure if needed) -# keyfile = "/path/to/key.pem" -# certfile = "/path/to/cert.pem" -""" - - create_file_with_content( - "gunicorn_config.py", - gunicorn_config_content, - "Created gunicorn_config.py with Gunicorn configuration", - ) - return True - - def create_runtime_txt(self, python_version: str = "3.13") -> bool: - with change_cwd(self.project_root): - context = {"python_version": python_version} - runtime_content = template_engine.render_template("runtime_txt.j2", context) - create_file_with_content( - "runtime.txt", - runtime_content, - "Created runtime.txt with Python version specification", - ) - return True - - def create_nixpacks_toml(self) -> bool: - with change_cwd(self.project_root): - nixpacks_content = f"""# Nixpacks configuration for {self.project_name} -# Used by Railway, Render, and other platforms that support Nixpacks - -[phases.setup] -nixPkgs = ["python311"] - -[phases.install] -cmds = ["pip install --upgrade pip", "pip install -r requirements.txt"] - -[phases.build] -cmds = ["python manage.py collectstatic --noinput"] - -[start] -cmd = "gunicorn {self.project_name}.wsgi:application --bind 0.0.0.0:$PORT" -""" - - create_file_with_content( - "nixpacks.toml", - nixpacks_content, - "Created nixpacks.toml for Nixpacks deployment", - ) - return True diff --git a/djinit/scripts/django_helper.py b/djinit/scripts/django_helper.py new file mode 100644 index 0000000..c28d781 --- /dev/null +++ b/djinit/scripts/django_helper.py @@ -0,0 +1,123 @@ +""" +Django helper module that replicates Django's startproject and startapp functionality. + +This module provides functions to create Django projects and apps without requiring Django. +""" + +import os + +from djinit.scripts.console_ui import UIFormatter +from djinit.utils import create_file_from_template, create_init_file + + +class DjangoHelper: + # Django version to use in generated files (matches Django 5.2) + DJANGO_VERSION = "5.2" + + @staticmethod + def startproject(project_name: str, directory: str) -> bool: + try: + os.makedirs(directory, exist_ok=True) + + # Create manage.py + manage_py_path = os.path.join(directory, "manage.py") + create_file_from_template(manage_py_path, "project/manage_py.j2", {}, "Created manage.py") + os.chmod(manage_py_path, 0o755) + + # Create project config directory + project_config_dir = os.path.join(directory, project_name) + os.makedirs(project_config_dir, exist_ok=True) + create_init_file(project_config_dir, f"Created {project_name}/__init__.py") + + # Create settings directory and files + settings_dir = os.path.join(project_config_dir, "settings") + os.makedirs(settings_dir, exist_ok=True) + create_init_file(settings_dir, f"Created {project_name}/settings/__init__.py") + + base_context = {"project_name": project_name, "app_names": []} + create_file_from_template( + os.path.join(settings_dir, "base.py"), + "project/settings_base.j2", + base_context, + f"Created {project_name}/settings/base.py", + ) + create_file_from_template( + os.path.join(settings_dir, "development.py"), + "project/settings_development.j2", + {}, + f"Created {project_name}/settings/development.py", + ) + create_file_from_template( + os.path.join(settings_dir, "production.py"), + "project/settings_production.j2", + {}, + f"Created {project_name}/settings/production.py", + ) + + # Create project-level files + urls_context = {"project_name": project_name, "django_version": DjangoHelper.DJANGO_VERSION} + create_file_from_template( + os.path.join(project_config_dir, "urls.py"), + "project/urls.j2", + urls_context, + f"Created {project_name}/urls.py", + ) + create_file_from_template( + os.path.join(project_config_dir, "wsgi.py"), + "project/wsgi.j2", + {}, + f"Created {project_name}/wsgi.py", + ) + create_file_from_template( + os.path.join(project_config_dir, "asgi.py"), + "project/asgi.j2", + {}, + f"Created {project_name}/asgi.py", + ) + + return True + + except Exception as e: + UIFormatter.print_error(f"Error creating Django project: {e}") + return False + + @staticmethod + def startapp(app_name: str, directory: str) -> bool: + try: + app_dir = os.path.join(directory, app_name) + os.makedirs(app_dir, exist_ok=True) + + context = {"app_name": app_name, "django_version": DjangoHelper.DJANGO_VERSION} + + # Create app files + create_init_file(app_dir, f"Created {app_name}/__init__.py") + + app_files = [ + ("apps.py", "app/apps.j2"), + ("models.py", "app/models.j2"), + ("views.py", "app/views.j2"), + ("admin.py", "app/admin.j2"), + ("urls.py", "app/urls.j2"), + ("serializers.py", "app/serializers.j2"), + ("routes.py", "app/routes.j2"), + ("tests.py", "app/tests.j2"), + ] + + for filename, template_path in app_files: + create_file_from_template( + os.path.join(app_dir, filename), + template_path, + context, + f"Created {app_name}/{filename}", + ) + + # Create migrations directory and __init__.py + migrations_dir = os.path.join(app_dir, "migrations") + os.makedirs(migrations_dir, exist_ok=True) + create_init_file(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 diff --git a/djinit/scripts/files.py b/djinit/scripts/files.py index ca00806..8c0dda4 100644 --- a/djinit/scripts/files.py +++ b/djinit/scripts/files.py @@ -6,7 +6,11 @@ Handles creation and modification of project files. import os from djinit.scripts.template_engine import template_engine -from djinit.utils import change_cwd, create_file_with_content +from djinit.utils import ( + calculate_app_module_paths, + change_cwd, + create_file_with_content, +) class FileManager: @@ -21,7 +25,7 @@ class FileManager: def create_gitignore(self) -> bool: with change_cwd(self.project_root): - gitignore_content = template_engine.render_template("gitignore.j2", {}) + gitignore_content = template_engine.render_template("shared/gitignore.j2", {}) return create_file_with_content( ".gitignore", gitignore_content, @@ -31,7 +35,7 @@ class FileManager: def create_requirements(self) -> bool: with change_cwd(self.project_root): context = {"use_database_url": self.metadata.get("use_database_url", True)} - requirements_content = template_engine.render_template("requirements.j2", context) + requirements_content = template_engine.render_template("shared/requirements.j2", context) return create_file_with_content( "requirements.txt", requirements_content, @@ -41,7 +45,7 @@ class FileManager: def create_readme(self) -> bool: with change_cwd(self.project_root): context = {"project_name": self.project_name, "app_names": self.app_names} - readme_content = template_engine.render_template("readme.j2", context) + readme_content = template_engine.render_template("shared/readme.j2", context) return create_file_with_content( "README.md", readme_content, @@ -55,7 +59,7 @@ class FileManager: "project_name": self.project_name, "use_database_url": self.metadata.get("use_database_url", True), } - env_content = template_engine.render_template("env_sample.j2", context) + env_content = template_engine.render_template("shared/env_sample.j2", context) return create_file_with_content( ".env.sample", env_content, @@ -65,99 +69,85 @@ class FileManager: def create_pyproject_toml(self, metadata: dict) -> bool: with change_cwd(self.project_root): context = {"package_name": metadata["package_name"], "project_name": self.project_name} - pyproject_content = template_engine.render_template("pyproject_toml.j2", context) + pyproject_content = template_engine.render_template("shared/pyproject_toml.j2", context) return create_file_with_content( "pyproject.toml", pyproject_content, "Created pyproject.toml file for uv", ) - def _get_apps_base_dir(self) -> str: - """Get the base directory for apps based on project structure.""" - if self.metadata.get("nested_apps") and self.metadata.get("nested_dir"): - return os.path.join(self.project_root, self.metadata.get("nested_dir")) - return self.project_root - - def _create_app_file(self, apps_base_dir: str, app_name: str, template_name: str, filename: str) -> None: - """Helper method to create app files.""" - app_path = os.path.join(apps_base_dir, app_name) - with change_cwd(app_path): - context = {"app_name": app_name} - content = template_engine.render_template(template_name, context) - create_file_with_content( - filename, - content, - f"Created {app_name}/{filename}", - should_format=True, - ) - - def create_app_urls(self) -> bool: - apps_base_dir = self._get_apps_base_dir() - for app_name in self.app_names: - self._create_app_file(apps_base_dir, app_name, "app_urls.j2", "urls.py") - return True - - def create_app_serializers(self) -> bool: - """Create serializers.py file for each app.""" - apps_base_dir = self._get_apps_base_dir() - for app_name in self.app_names: - self._create_app_file(apps_base_dir, app_name, "serializers.j2", "serializers.py") - return True - - def create_app_routes(self) -> bool: - """Create routes.py file for each app.""" - apps_base_dir = self._get_apps_base_dir() - for app_name in self.app_names: - self._create_app_file(apps_base_dir, app_name, "routes.j2", "routes.py") - return True - - def update_project_urls(self) -> bool: + def create_project_urls(self) -> bool: + """Create project urls.py using project_urls.j2 template (replaces update_project_urls).""" with change_cwd(self.project_configs): - nested = bool(self.metadata.get("nested_apps")) - nested_dir = self.metadata.get("nested_dir") - effective_app_modules = [ - f"{nested_dir}.{name}" if nested and nested_dir else name for name in self.app_names - ] + effective_app_modules = calculate_app_module_paths(self.app_names, self.metadata) context = { "project_name": self.project_name, "app_names": effective_app_modules, } - urls_content = template_engine.render_template("project_urls.j2", context) + urls_content = template_engine.render_template("project/project_urls.j2", context) result = create_file_with_content( "urls.py", urls_content, - "Updated project urls.py with comprehensive URL configuration", + "Created project urls.py with comprehensive URL configuration", should_format=True, ) return result - def update_wsgi_file(self) -> bool: - with change_cwd(self.project_configs): - wsgi_content = template_engine.render_template("wsgi.j2", {}) - return create_file_with_content( - "wsgi.py", - wsgi_content, - "Updated wsgi.py with custom configuration", - should_format=True, - ) - - def update_asgi_file(self) -> bool: - with change_cwd(self.project_configs): - asgi_content = template_engine.render_template("asgi.j2", {}) - return create_file_with_content( - "asgi.py", - asgi_content, - "Updated asgi.py with custom configuration", - should_format=True, - ) - - def update_manage_py(self) -> bool: - """Update manage.py with custom configuration.""" + def create_justfile(self) -> bool: with change_cwd(self.project_root): - manage_content = template_engine.render_template("manage_py.j2", {}) - return create_file_with_content( - "manage.py", - manage_content, - "Updated manage.py with custom configuration", - should_format=True, + context = {"project_name": self.project_name} + justfile_content = template_engine.render_template("shared/justfile.j2", context) + create_file_with_content( + "justfile", + justfile_content, + "Created justfile with Django development tasks", ) + return True + + def create_procfile(self) -> bool: + with change_cwd(self.project_root): + context = {"project_name": self.project_name} + procfile_content = template_engine.render_template("shared/procfile.j2", context) + create_file_with_content( + "Procfile", + procfile_content, + "Created Procfile with Gunicorn configuration", + ) + return True + + def create_runtime_txt(self) -> bool: + with change_cwd(self.project_root): + context = {"python_version": "3.13"} + runtime_content = template_engine.render_template("shared/runtime_txt.j2", context) + create_file_with_content( + "runtime.txt", + runtime_content, + "Created runtime.txt with Python version specification", + ) + return True + + def create_github_actions(self) -> bool: + with change_cwd(self.project_root): + github_dir = os.path.join(self.project_root, ".github", "workflows") + os.makedirs(github_dir, exist_ok=True) + + context = {"project_name": self.project_name} + workflow_content = template_engine.render_template("shared/github_actions_ci.j2", context) + workflow_file = os.path.join(github_dir, "ci.yml") + create_file_with_content( + workflow_file, + workflow_content, + "Created Github Actions workflow (ci.yml)", + ) + return True + + def create_gitlab_ci(self) -> bool: + with change_cwd(self.project_root): + context = {"project_name": self.project_name} + gitlab_ci_content = template_engine.render_template("shared/gitlab_ci.j2", context) + create_file_with_content( + ".gitlab-ci.yml", + gitlab_ci_content, + "Created GitLab CI configuration (.gitlab-ci.yml)", + ) + return True diff --git a/djinit/scripts/input_handler.py b/djinit/scripts/input_handler.py index af035a2..85b8abc 100644 --- a/djinit/scripts/input_handler.py +++ b/djinit/scripts/input_handler.py @@ -36,7 +36,6 @@ class ProjectMetadata: use_database_url: bool = False def to_dict(self) -> dict: - """Convert to dictionary format.""" return { "package_name": self.package_name, "use_github_actions": self.use_github_actions, @@ -49,8 +48,6 @@ class ProjectMetadata: @dataclass class ProjectSetup: - """Complete project setup configuration.""" - project_dir: str project_name: str primary_app: str @@ -58,13 +55,10 @@ class ProjectSetup: metadata: ProjectMetadata def to_tuple(self) -> Tuple[str, str, str, list, dict]: - """Convert to legacy tuple format for backward compatibility.""" return (self.project_dir, self.project_name, self.primary_app, self.app_names, self.metadata.to_dict()) class InputCollector: - """Handles collection of user inputs with validation.""" - MAX_ATTEMPTS = 3 def __init__(self): @@ -107,41 +101,42 @@ class InputCollector: UIFormatter.print_error(f"Maximum attempts reached for {input_type}. Exiting.") sys.exit(1) - def _show_retry_message(self, attempt: int) -> None: - if attempt < self.MAX_ATTEMPTS: - console.print(f"[{UIColors.MUTED}]Please try again ({attempt}/{self.MAX_ATTEMPTS}).[/{UIColors.MUTED}]") + def _show_retry_message(self, attempt: int, max_attempts: int = None) -> None: + max_attempts = max_attempts or self.MAX_ATTEMPTS + if attempt < max_attempts: + console.print(f"[{UIColors.MUTED}]Please try again ({attempt}/{max_attempts}).[/{UIColors.MUTED}]") def get_app_names(self) -> list[str]: console.print(f"[{UIColors.HIGHLIGHT}]App Names[/{UIColors.HIGHLIGHT}]") - console.print( - f"[{UIColors.MUTED}]Enter app names separated by commas (no interactive prompts)[/{UIColors.MUTED}]" - ) + console.print(f"[{UIColors.MUTED}]Enter app names separated by commas[/{UIColors.MUTED}]") console.print(f"[{UIColors.MUTED}]Example: users, products, orders[/{UIColors.MUTED}]") user_input = console.input( f"[{UIColors.HIGHLIGHT}]Enter app names (comma-separated or single):[/{UIColors.HIGHLIGHT}] " ) - # Empty input - re-prompt (no interactive flow) if not user_input.strip(): UIFormatter.print_error("At least one app name is required") return self.get_app_names() - # Comma-separated input if "," in user_input: return self._parse_comma_separated_apps(user_input) - # Single app (no additional prompts) return self._get_apps_starting_with(user_input.strip()) def _parse_comma_separated_apps(self, user_input: str) -> list[str]: - app_list = [app.strip() for app in user_input.split(",")] - app_list = [app for app in app_list if app] # Remove empty strings + app_list = [app.strip() for app in user_input.split(",") if app.strip()] if not app_list: UIFormatter.print_error("At least one app name is required") return self.get_app_names() + return self._validate_app_list(app_list) + + def _get_apps_starting_with(self, first_app: str) -> list[str]: + return self._validate_app_list([first_app]) + + def _validate_app_list(self, app_list: list[str]) -> list[str]: invalid_apps = [] for app in app_list: is_valid, error_msg = validate_app_name(app) @@ -155,22 +150,43 @@ class InputCollector: return app_list - def _get_apps_starting_with(self, first_app: str) -> list[str]: - is_valid, error_msg = validate_app_name(first_app) - if not is_valid: - UIFormatter.print_error(error_msg) - return self.get_app_names() + def _get_project_directory(self) -> str | None: + attempt = 0 - return [first_app] + while attempt < self.MAX_ATTEMPTS: + try: + user_input = console.input( + f"[{UIColors.HIGHLIGHT}]Enter project directory name:[/{UIColors.HIGHLIGHT}] " + ).strip() - def _get_apps_interactive(self) -> list[str]: - """Deprecated: interactive flow disabled. Kept for compatibility.""" - UIFormatter.print_warning("Interactive app addition is disabled. Please enter names comma-separated.") - return self.get_app_names() + # Handle empty input or '.' - use current directory + if not user_input or user_input == ".": + UIFormatter.print_info(f"Creating project in current directory: {os.getcwd()}") + return "." - def _prompt_for_additional_apps(self) -> list[str]: - """Deprecated: interactive flow disabled. Always returns empty list.""" - return [] + is_valid, error_msg = validate_project_name(user_input) + if not is_valid: + UIFormatter.print_error(error_msg) + attempt += 1 + self._show_retry_message(attempt) + continue + + if os.path.exists(user_input): + UIFormatter.print_error(f"Directory '{user_input}' already exists.") + UIFormatter.print_info( + "Please choose a different project directory name (or press Enter for current directory)." + ) + attempt += 1 + self._show_retry_message(attempt) + continue + + return user_input + + except KeyboardInterrupt: + UIFormatter.print_info("\nSetup cancelled by user.") + sys.exit(0) + + return None def get_cicd_choice(self) -> Tuple[bool, bool]: UIFormatter.print_separator() @@ -178,12 +194,10 @@ class InputCollector: console.print(f"[{UIColors.MUTED}]Choose CI/CD pipeline for your project[/{UIColors.MUTED}]") console.print() - # Show options for option in CICDOption: console.print(f" [{UIColors.SUCCESS}]{option.key}[/{UIColors.SUCCESS}] {option.description}") console.print() - # Get valid keys from CICDOption enum valid_keys = [option.key for option in CICDOption] choice = CharReader.get_cicd_choice( @@ -192,31 +206,25 @@ class InputCollector: default=CICDOption.NONE.key, ) - # Parse choice - if choice == CICDOption.BOTH.key: - return True, True - elif choice == CICDOption.GITHUB.key: - return True, False - elif choice == CICDOption.GITLAB.key: - return False, True - else: # Default to none (should not happen due to validation, but kept as fallback) - return False, False + choice_map = { + CICDOption.BOTH.key: (True, True), + CICDOption.GITHUB.key: (True, False), + CICDOption.GITLAB.key: (False, True), + } + return choice_map.get(choice, (False, False)) def get_nested_apps_config(self) -> Tuple[bool, str | None]: - """Ask whether to create nested Django apps and get directory name if yes.""" UIFormatter.print_separator() console.print(f"\n[{UIColors.INFO}]Apps Layout[/{UIColors.INFO}]\n") console.print( - f"[{UIColors.MUTED}]Do you want to place apps inside a package directory (e.g., 'apps/')?[/{UIColors.MUTED}]" + f"[{UIColors.MUTED}]Do you want to place apps inside a package directory (e.g., 'src/')?[/{UIColors.MUTED}]" ) console.print( f"[{UIColors.MUTED}]If yes, we'll create that directory as a Python package and generate apps inside it.[/{UIColors.MUTED}]" ) console.print() - choice = CharReader.get_yes_no( - f"[{UIColors.HIGHLIGHT}]Nested Django apps? (y/N):[/{UIColors.HIGHLIGHT}]", default="n" - ) + choice = CharReader.get_yes_no(f"[{UIColors.HIGHLIGHT}]Nested Django apps? (y/N):[/{UIColors.HIGHLIGHT}]") if choice != "y": return False, None @@ -230,7 +238,6 @@ class InputCollector: return True, dir_name def get_database_config_choice(self) -> bool: - """Ask user for database configuration preference.""" UIFormatter.print_separator() console.print(f"\n[{UIColors.INFO}]Database Configuration[/{UIColors.INFO}]\n") console.print(f"[{UIColors.MUTED}]Choose how to configure your database in production:[/{UIColors.MUTED}]") @@ -242,16 +249,11 @@ class InputCollector: console.print(f"[{UIColors.MUTED}]postgres://user:password@host:port/database[/{UIColors.MUTED}]") console.print() - choice = CharReader.get_yes_no( - f"[{UIColors.HIGHLIGHT}]Use DATABASE_URL? (Y/n):[/{UIColors.HIGHLIGHT}]", default="y" - ) - - # Return True if choice is 'y', False if 'n' - return choice == "y" + return CharReader.get_yes_no(f"[{UIColors.HIGHLIGHT}]Use DATABASE_URL? (Y/n):[/{UIColors.HIGHLIGHT}]") == "y" class CharReader: - """Handles single character input across platforms.""" + MAX_ATTEMPTS = 3 @staticmethod def get_char() -> str: @@ -260,45 +262,59 @@ class CharReader: return CharReader._get_char_unix() @staticmethod - def get_yes_no(prompt: str, default: str = "n") -> str: - max_attempts = 3 + def _is_enter_key(response: str) -> bool: + """Check if response represents Enter key or control character.""" + return not response or response in ("\r", "\n") or ord(response) < 32 + + @staticmethod + def _get_char_input(prompt: str) -> str: + console.print(f"{prompt} ", end="") + sys.stdout.flush() + return CharReader().get_char() + + @staticmethod + def _handle_default(default: str) -> str: + console.print(default.upper()) + return default.lower() + + @staticmethod + def _get_validated_char_input( + prompt: str, + valid_keys: list[str], + default: str, + error_message: str, + ) -> str: attempt = 0 + valid_keys_lower = [k.lower() for k in valid_keys] - while attempt < max_attempts: + while attempt < CharReader.MAX_ATTEMPTS: try: - console.print(f"{prompt} ", end="") - sys.stdout.flush() + response = CharReader._get_char_input(prompt) - reader = CharReader() - response = reader.get_char() - - # Handle Enter key (default) - in raw mode, Enter is '\r' (carriage return) - # Also handle empty string or other control characters as Enter - if not response or response == "\r" or response == "\n" or ord(response) < 32: - console.print(default.upper()) - return default.lower() + # Handle Enter key (default) + if CharReader._is_enter_key(response): + return CharReader._handle_default(default) response = response.lower() # Validate response - if response in ("y", "n"): + if response in valid_keys_lower: console.print(response.upper()) return response - # Invalid input - show error (only show if it's a printable character) + # Invalid input - show error console.print() if response.isprintable(): - UIFormatter.print_error(f"Invalid input '{response}'. Please enter 'y' or 'n'.") + UIFormatter.print_error(error_message.format(response=response)) attempt += 1 - if attempt < max_attempts: + if attempt < CharReader.MAX_ATTEMPTS: console.print( - f"[{UIColors.MUTED}]Please try again ({attempt}/{max_attempts}).[/{UIColors.MUTED}]" + f"[{UIColors.MUTED}]Please try again ({attempt}/{CharReader.MAX_ATTEMPTS}).[/{UIColors.MUTED}]" ) console.print() else: # Control character entered, treat as Enter - console.print(default.upper()) - return default.lower() + return CharReader._handle_default(default) except KeyboardInterrupt: console.print() @@ -310,69 +326,34 @@ class CharReader: UIFormatter.print_warning(f"Maximum attempts reached. Using default: '{default.upper()}'.") return default.lower() + @staticmethod + def get_yes_no(prompt: str, default: str = None) -> str: + # Auto-detect default from prompt format (capital letter indicates default) + if default is None: + if "(Y/n)" in prompt or "(Y/N)" in prompt: + default = "y" + elif "(y/N)" in prompt: + default = "n" + else: + # Default to 'y' for yes/no prompts + default = "y" + + return CharReader._get_validated_char_input( + prompt=prompt, + valid_keys=["y", "n"], + default=default, + error_message="Invalid input '{response}'. Please enter 'y' or 'n'.", + ) + @staticmethod def get_cicd_choice(prompt: str, valid_keys: list[str], default: str = "n") -> str: - """ - Get CI/CD choice input with validation and retries. - - Args: - prompt: The prompt message to display - valid_keys: List of valid key characters (e.g., ['g', 'l', 'b', 'n']) - default: Default value if Enter is pressed - - Returns: - Valid key (lowercase) - """ - max_attempts = 3 - attempt = 0 - valid_keys_lower = [k.lower() for k in valid_keys] - - while attempt < max_attempts: - try: - console.print(f"{prompt} ", end="") - sys.stdout.flush() - - reader = CharReader() - response = reader.get_char() - - # Handle Enter key (default) - in raw mode, Enter is '\r' (carriage return) - # Also handle empty string or other control characters as Enter - if not response or response == "\r" or response == "\n" or ord(response) < 32: - console.print(default.upper()) - return default.lower() - - response = response.lower() - - # Validate response - if response in valid_keys_lower: - console.print(response.upper()) - return response - - # Invalid input - show error (only show if it's a printable character) - console.print() - if response.isprintable(): - valid_keys_str = ", ".join(f"'{k}'" for k in valid_keys) - UIFormatter.print_error(f"Invalid input '{response}'. Please enter one of: {valid_keys_str}.") - attempt += 1 - if attempt < max_attempts: - console.print( - f"[{UIColors.MUTED}]Please try again ({attempt}/{max_attempts}).[/{UIColors.MUTED}]" - ) - console.print() - else: - # Control character entered, treat as Enter - console.print(default.upper()) - return default.lower() - - except KeyboardInterrupt: - console.print() - UIFormatter.print_info("\nOperation cancelled by user.") - raise - - # Max attempts reached - use default - console.print() - UIFormatter.print_warning(f"Maximum attempts reached. Using default: '{default.upper()}'.") - return default.lower() + valid_keys_str = ", ".join(f"'{k}'" for k in valid_keys) + return CharReader._get_validated_char_input( + prompt=prompt, + valid_keys=valid_keys, + default=default, + error_message=f"Invalid input '{{response}}'. Please enter one of: {valid_keys_str}.", + ) @staticmethod def _get_char_windows() -> str: @@ -418,45 +399,7 @@ def get_user_input() -> Tuple[str, str, str, list, dict]: console.print(f"[{UIColors.MUTED}]Press Enter or enter '.' to create in current directory[/{UIColors.MUTED}]") # Get project directory with special handling for '.' and empty input - attempt = 0 - project_dir = None - - while attempt < collector.MAX_ATTEMPTS and project_dir is None: - try: - user_input = console.input( - f"[{UIColors.HIGHLIGHT}]Enter project directory name:[/{UIColors.HIGHLIGHT}] " - ).strip() - - # Handle empty input or '.' - use current directory - if not user_input or user_input == ".": - project_dir = "." - UIFormatter.print_info(f"Creating project in current directory: {os.getcwd()}") - break - - # Validate the input - is_valid, error_msg = validate_project_name(user_input) - if not is_valid: - UIFormatter.print_error(error_msg) - attempt += 1 - collector._show_retry_message(attempt) - continue - - # Check if directory exists and ask for alternative - if os.path.exists(user_input): - UIFormatter.print_error(f"Directory '{user_input}' already exists.") - UIFormatter.print_info( - "Please choose a different project directory name (or press Enter for current directory)." - ) - attempt += 1 - collector._show_retry_message(attempt) - continue - - project_dir = user_input - break - - except KeyboardInterrupt: - UIFormatter.print_info("\nSetup cancelled by user.") - sys.exit(0) + project_dir = collector._get_project_directory() if project_dir is None: UIFormatter.print_error("Maximum attempts reached for project directory name. Exiting.") @@ -509,17 +452,14 @@ def confirm_setup(project_dir: str, project_name: str, app_names: list, metadata console.print(f"[{UIColors.INFO}]Setup Summary[/{UIColors.INFO}]") console.print() - # Display configuration console.print(f"[{UIColors.HIGHLIGHT}]Project Directory:[/{UIColors.HIGHLIGHT}] {project_dir}") console.print(f"[{UIColors.HIGHLIGHT}]Django Project:[/{UIColors.HIGHLIGHT}] {project_name}") console.print(f"[{UIColors.HIGHLIGHT}]Apps:[/{UIColors.HIGHLIGHT}] {', '.join(app_names)}") console.print(f"[{UIColors.HIGHLIGHT}]Package:[/{UIColors.HIGHLIGHT}] {metadata['package_name']}") - # Show CI/CD choices cicd_choices = _get_cicd_display(metadata) console.print(f"[{UIColors.HIGHLIGHT}]CI/CD:[/{UIColors.HIGHLIGHT}] {cicd_choices}") - # Show database configuration db_config = "DATABASE_URL" if metadata.get("use_database_url", True) else "Individual parameters" console.print(f"[{UIColors.HIGHLIGHT}]Database Config:[/{UIColors.HIGHLIGHT}] {db_config}") @@ -527,11 +467,8 @@ def confirm_setup(project_dir: str, project_name: str, app_names: list, metadata UIFormatter.print_separator() console.print() - # Get confirmation try: - response = CharReader.get_yes_no( - f"[{UIColors.WARNING}]Proceed with setup? (y/N):[/{UIColors.WARNING}]", default="n" - ) + response = CharReader.get_yes_no(f"[{UIColors.WARNING}]Proceed with setup? (y/N):[/{UIColors.WARNING}]") return response == "y" except KeyboardInterrupt: @@ -540,14 +477,12 @@ def confirm_setup(project_dir: str, project_name: str, app_names: list, metadata def _get_cicd_display(metadata: dict) -> str: - cicd_choices = [] - + choices = [] if metadata.get("use_github_actions", False): - cicd_choices.append("GitHub Actions") + choices.append("GitHub Actions") if metadata.get("use_gitlab_ci", False): - cicd_choices.append("GitLab CI") - - return ", ".join(cicd_choices) if cicd_choices else "None" + choices.append("GitLab CI") + return ", ".join(choices) if choices else "None" get_char = CharReader.get_char diff --git a/djinit/scripts/project.py b/djinit/scripts/project.py index a02e301..d963c12 100644 --- a/djinit/scripts/project.py +++ b/djinit/scripts/project.py @@ -3,13 +3,17 @@ Project management for djinit. Handles creation of Django projects and apps. """ -import importlib.util import os -import subprocess -import sys from djinit.scripts.console_ui import UIFormatter -from djinit.utils import change_cwd +from djinit.scripts.django_helper import DjangoHelper +from djinit.utils import ( + calculate_app_module_paths, + extract_existing_apps, + get_base_settings_path, + insert_apps_into_user_defined_apps, + read_base_settings, +) class ProjectManager: @@ -18,30 +22,19 @@ class ProjectManager: self.project_name = project_name self.app_names = app_names self.metadata = metadata - # Handle '.' for current directory - if project_dir == ".": - self.project_root = os.getcwd() - else: - self.project_root = os.path.join(os.getcwd(), project_dir) + self.project_root = os.getcwd() if project_dir == "." else os.path.join(os.getcwd(), project_dir) def create_project(self) -> bool: - self._ensure_django_installed() - - # Create the project directory first os.makedirs(self.project_root, exist_ok=True) - # Create Django project inside the directory - # Use 'python -m django' instead of 'django-admin' for better compatibility - subprocess.run( - [sys.executable, "-m", "django", "startproject", self.project_name, self.project_root], - check=True, - ) - - UIFormatter.print_success(f"Django project '{self.project_name}' created successfully!") - return True + success = DjangoHelper.startproject(self.project_name, self.project_root) + 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 def create_apps(self) -> bool: - # Determine base directory for apps apps_base_dir = self.project_root nested = bool(self.metadata.get("nested_apps")) nested_dir_name = self.metadata.get("nested_dir") if nested else None @@ -49,47 +42,69 @@ class ProjectManager: if nested and nested_dir_name: apps_base_dir = os.path.join(self.project_root, nested_dir_name) os.makedirs(apps_base_dir, exist_ok=True) - # Make it a Python package init_file = os.path.join(apps_base_dir, "__init__.py") if not os.path.exists(init_file): open(init_file, "a").close() - with change_cwd(apps_base_dir): - # Create each app - for app_name in self.app_names: - subprocess.run( - [ - sys.executable, - os.path.join(self.project_root, "manage.py"), - "startapp", - app_name, - ], - check=True, - ) - UIFormatter.print_success(f"Django app '{app_name}' created successfully!") + 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 + UIFormatter.print_success(f"Django app '{app_name}' created successfully!") + + # Add all apps to USER_DEFINED_APPS in settings + if not self._add_apps_to_settings(): + return False return True - def _ensure_django_installed(self) -> None: - if importlib.util.find_spec("django") is None: - subprocess.run( - [sys.executable, "-m", "pip", "install", "--upgrade", "django", "-q"], - check=True, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) + def _add_apps_to_settings(self) -> bool: + """Add all apps to USER_DEFINED_APPS in base.py settings file.""" + base_settings_path = get_base_settings_path(self.project_root, self.project_name) + + if not os.path.exists(base_settings_path): + UIFormatter.print_error("Could not find base.py settings file") + return False + + content = read_base_settings(self.project_root, self.project_name) + if content is None: + UIFormatter.print_error("Could not read base.py settings file") + return False + + app_module_paths = calculate_app_module_paths(self.app_names, self.metadata) + + existing_apps = extract_existing_apps(content) + apps_to_add = [app for app in app_module_paths if app not in existing_apps] + + if not apps_to_add: + UIFormatter.print_success("All apps already configured in USER_DEFINED_APPS") + return True + + updated_content = insert_apps_into_user_defined_apps(content, apps_to_add) + if not updated_content: + return False + + 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: required_files = [ os.path.join(self.project_root, "manage.py"), os.path.join(self.project_root, self.project_name, "__init__.py"), - os.path.join(self.project_root, self.project_name, "settings.py"), + os.path.join(self.project_root, self.project_name, "settings", "__init__.py"), + os.path.join(self.project_root, self.project_name, "settings", "base.py"), + os.path.join(self.project_root, self.project_name, "settings", "development.py"), + os.path.join(self.project_root, self.project_name, "settings", "production.py"), os.path.join(self.project_root, self.project_name, "urls.py"), os.path.join(self.project_root, self.project_name, "wsgi.py"), os.path.join(self.project_root, self.project_name, "asgi.py"), ] - # Add required files for each app apps_base_dir = self.project_root if self.metadata.get("nested_apps") and self.metadata.get("nested_dir"): apps_base_dir = os.path.join(self.project_root, self.metadata.get("nested_dir")) @@ -100,11 +115,21 @@ class ProjectManager: os.path.join(apps_base_dir, app_name, "apps.py"), os.path.join(apps_base_dir, app_name, "models.py"), os.path.join(apps_base_dir, app_name, "views.py"), + os.path.join(apps_base_dir, app_name, "serializers.py"), + os.path.join(apps_base_dir, app_name, "routes.py"), + os.path.join(apps_base_dir, app_name, "tests.py"), + os.path.join(apps_base_dir, app_name, "migrations"), os.path.join(apps_base_dir, app_name, "admin.py"), ] required_files.extend(app_files) - missing_files = [file_path for file_path in required_files if not os.path.exists(file_path)] + missing_files = [] + for file_path in required_files: + if file_path.endswith("settings"): + if not os.path.isdir(file_path): + missing_files.append(file_path) + elif not os.path.exists(file_path): + missing_files.append(file_path) if not missing_files: UIFormatter.print_success("Project structure validation passed") diff --git a/djinit/scripts/settings.py b/djinit/scripts/settings.py deleted file mode 100644 index 96ce0de..0000000 --- a/djinit/scripts/settings.py +++ /dev/null @@ -1,86 +0,0 @@ -""" -Settings management for djinit. -Handles creation and configuration of Django settings files. -""" - -import os - -from djinit.scripts.console_ui import UIFormatter -from djinit.scripts.secretkey_generator import generate_secret_key -from djinit.scripts.template_engine import template_engine -from djinit.utils import change_cwd, create_file_with_content - - -class SettingsManager: - def __init__(self, project_root: str, project_name: str, app_names: list, metadata: dict): - self.project_root = project_root - self.project_name = project_name - self.app_names = app_names - self.metadata = metadata - self.project_configs = os.path.join(project_root, project_name) - self.settings_folder = os.path.join(self.project_configs, "settings") - self.settings_file = os.path.join(self.project_configs, "settings.py") - self.secret_key = generate_secret_key(50) - - def create_settings_structure(self) -> bool: - # Change to project configs directory - with change_cwd(self.project_configs): - # Create settings folder - os.makedirs("settings", exist_ok=True) - - # Move settings.py to settings/base.py - if os.path.exists(self.settings_file): - os.rename(self.settings_file, os.path.join(self.settings_folder, "base.py")) - - # Create __init__.py files - with change_cwd(self.settings_folder): - open("__init__.py", "a").close() - open("development.py", "a").close() - open("production.py", "a").close() - - UIFormatter.print_success("Created Django settings folder structure") - return True - - def update_base_settings(self) -> bool: - with change_cwd(self.settings_folder): - nested = bool(self.metadata.get("nested_apps")) - nested_dir = self.metadata.get("nested_dir") - effective_app_names = [f"{nested_dir}.{name}" if nested and nested_dir else name for name in self.app_names] - context = { - "project_name": self.project_name, - "app_names": effective_app_names, - } - base_content = template_engine.render_template("settings_base.j2", context) - create_file_with_content( - "base.py", - base_content, - "Updated settings/base.py with comprehensive configuration", - should_format=True, - ) - return True - - def update_development_settings(self) -> bool: - """Update development.py with development-specific settings.""" - with change_cwd(self.settings_folder): - context = {"secret_key": self.secret_key} - dev_content = template_engine.render_template("settings_development.j2", context) - create_file_with_content( - "development.py", - dev_content, - "Updated settings/development.py", - should_format=True, - ) - return True - - def update_production_settings(self) -> bool: - """Update production.py with production-specific settings.""" - with change_cwd(self.settings_folder): - context = {"use_database_url": self.metadata.get("use_database_url", True)} - prod_content = template_engine.render_template("settings_production.j2", context) - create_file_with_content( - "production.py", - prod_content, - "Updated settings/production.py", - should_format=True, - ) - return True diff --git a/djinit/scripts/template_engine.py b/djinit/scripts/template_engine.py index 629687d..30d71e4 100644 --- a/djinit/scripts/template_engine.py +++ b/djinit/scripts/template_engine.py @@ -76,5 +76,4 @@ class TemplateEngine: return os.path.exists(template_path) -# Global template engine instance template_engine = TemplateEngine() diff --git a/djinit/templates/app/admin.j2 b/djinit/templates/app/admin.j2 new file mode 100644 index 0000000..ec50db8 --- /dev/null +++ b/djinit/templates/app/admin.j2 @@ -0,0 +1,4 @@ +from django.contrib import admin + +# Register your models here. + diff --git a/djinit/templates/app/apps.j2 b/djinit/templates/app/apps.j2 new file mode 100644 index 0000000..70a33a1 --- /dev/null +++ b/djinit/templates/app/apps.j2 @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class {{ app_name|title }}Config(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = '{{ app_name }}' + diff --git a/djinit/templates/app/migrations_init.j2 b/djinit/templates/app/migrations_init.j2 new file mode 100644 index 0000000..e69de29 diff --git a/djinit/templates/app/models.j2 b/djinit/templates/app/models.j2 new file mode 100644 index 0000000..b096caa --- /dev/null +++ b/djinit/templates/app/models.j2 @@ -0,0 +1,4 @@ +from django.db import models + +# Create your models here. + diff --git a/djinit/templates/routes.j2 b/djinit/templates/app/routes.j2 similarity index 100% rename from djinit/templates/routes.j2 rename to djinit/templates/app/routes.j2 diff --git a/djinit/templates/serializers.j2 b/djinit/templates/app/serializers.j2 similarity index 100% rename from djinit/templates/serializers.j2 rename to djinit/templates/app/serializers.j2 diff --git a/djinit/templates/app/tests.j2 b/djinit/templates/app/tests.j2 new file mode 100644 index 0000000..0b4501e --- /dev/null +++ b/djinit/templates/app/tests.j2 @@ -0,0 +1,4 @@ +from django.test import TestCase + +# Create your tests here. + diff --git a/djinit/templates/app_urls.j2 b/djinit/templates/app/urls.j2 similarity index 100% rename from djinit/templates/app_urls.j2 rename to djinit/templates/app/urls.j2 diff --git a/djinit/templates/app/views.j2 b/djinit/templates/app/views.j2 new file mode 100644 index 0000000..27cdb63 --- /dev/null +++ b/djinit/templates/app/views.j2 @@ -0,0 +1,4 @@ +from django.shortcuts import render + +# Create your views here. + diff --git a/djinit/templates/asgi.j2 b/djinit/templates/project/asgi.j2 similarity index 100% rename from djinit/templates/asgi.j2 rename to djinit/templates/project/asgi.j2 diff --git a/djinit/templates/manage_py.j2 b/djinit/templates/project/manage_py.j2 similarity index 100% rename from djinit/templates/manage_py.j2 rename to djinit/templates/project/manage_py.j2 diff --git a/djinit/templates/project_urls.j2 b/djinit/templates/project/project_urls.j2 similarity index 100% rename from djinit/templates/project_urls.j2 rename to djinit/templates/project/project_urls.j2 diff --git a/djinit/templates/settings_base.j2 b/djinit/templates/project/settings_base.j2 similarity index 100% rename from djinit/templates/settings_base.j2 rename to djinit/templates/project/settings_base.j2 diff --git a/djinit/templates/settings_development.j2 b/djinit/templates/project/settings_development.j2 similarity index 100% rename from djinit/templates/settings_development.j2 rename to djinit/templates/project/settings_development.j2 diff --git a/djinit/templates/settings_production.j2 b/djinit/templates/project/settings_production.j2 similarity index 100% rename from djinit/templates/settings_production.j2 rename to djinit/templates/project/settings_production.j2 diff --git a/djinit/templates/project/urls.j2 b/djinit/templates/project/urls.j2 new file mode 100644 index 0000000..c99fb11 --- /dev/null +++ b/djinit/templates/project/urls.j2 @@ -0,0 +1,23 @@ +""" +URL configuration for {{ project_name }} project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/{{ django_version }}/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), +] + diff --git a/djinit/templates/wsgi.j2 b/djinit/templates/project/wsgi.j2 similarity index 100% rename from djinit/templates/wsgi.j2 rename to djinit/templates/project/wsgi.j2 diff --git a/djinit/templates/env_sample.j2 b/djinit/templates/shared/env_sample.j2 similarity index 100% rename from djinit/templates/env_sample.j2 rename to djinit/templates/shared/env_sample.j2 diff --git a/djinit/templates/github_actions_ci.j2 b/djinit/templates/shared/github_actions_ci.j2 similarity index 100% rename from djinit/templates/github_actions_ci.j2 rename to djinit/templates/shared/github_actions_ci.j2 diff --git a/djinit/templates/gitignore.j2 b/djinit/templates/shared/gitignore.j2 similarity index 100% rename from djinit/templates/gitignore.j2 rename to djinit/templates/shared/gitignore.j2 diff --git a/djinit/templates/gitlab_ci.j2 b/djinit/templates/shared/gitlab_ci.j2 similarity index 100% rename from djinit/templates/gitlab_ci.j2 rename to djinit/templates/shared/gitlab_ci.j2 diff --git a/djinit/templates/shared/init.j2 b/djinit/templates/shared/init.j2 new file mode 100644 index 0000000..e69de29 diff --git a/djinit/templates/justfile.j2 b/djinit/templates/shared/justfile.j2 similarity index 100% rename from djinit/templates/justfile.j2 rename to djinit/templates/shared/justfile.j2 diff --git a/djinit/templates/procfile.j2 b/djinit/templates/shared/procfile.j2 similarity index 100% rename from djinit/templates/procfile.j2 rename to djinit/templates/shared/procfile.j2 diff --git a/djinit/templates/pyproject_toml.j2 b/djinit/templates/shared/pyproject_toml.j2 similarity index 100% rename from djinit/templates/pyproject_toml.j2 rename to djinit/templates/shared/pyproject_toml.j2 diff --git a/djinit/templates/readme.j2 b/djinit/templates/shared/readme.j2 similarity index 100% rename from djinit/templates/readme.j2 rename to djinit/templates/shared/readme.j2 diff --git a/djinit/templates/requirements.j2 b/djinit/templates/shared/requirements.j2 similarity index 92% rename from djinit/templates/requirements.j2 rename to djinit/templates/shared/requirements.j2 index 365c06d..235b528 100644 --- a/djinit/templates/requirements.j2 +++ b/djinit/templates/shared/requirements.j2 @@ -1,6 +1,6 @@ Django python-dotenv -django-jazzmin> +django-jazzmin djangorestframework djangorestframework_simplejwt drf-spectacular diff --git a/djinit/templates/runtime_txt.j2 b/djinit/templates/shared/runtime_txt.j2 similarity index 100% rename from djinit/templates/runtime_txt.j2 rename to djinit/templates/shared/runtime_txt.j2 diff --git a/djinit/utils.py b/djinit/utils.py index dfbd7c9..77263d6 100644 --- a/djinit/utils.py +++ b/djinit/utils.py @@ -9,27 +9,16 @@ import sys from contextlib import contextmanager from djinit.scripts.console_ui import UIFormatter +from djinit.scripts.template_engine import template_engine def format_file(filename: str) -> None: """Format Python file using Ruff formatter.""" - # Use 'python -m ruff' instead of 'ruff' for better compatibility subprocess.run([sys.executable, "-m", "ruff", "format", filename], check=False, capture_output=True) +# create a file with content, optionally format it def create_file_with_content(filename: str, content: str, success_message: str, should_format: bool = False) -> bool: - """ - Create a file with content, optionally format it, and print success message. - - Args: - filename: Name of the file to create - content: Content to write to the file - success_message: Message to print on success - should_format: Whether to format the file with ruff - - Returns: - True if successful - """ with open(filename, "w") as file: file.write(content) @@ -40,15 +29,224 @@ def create_file_with_content(filename: str, content: str, success_message: str, return True +# create a file from a template +def create_file_from_template( + file_path: str, + template_path: str, + context: dict, + success_message: str, + should_format: bool = True, +) -> None: + content = template_engine.render_template(template_path, context) + create_file_with_content(file_path, content, success_message, should_format=should_format) + + +# create __init__.py +def create_init_file(directory: str, success_message: str) -> None: + init_path = os.path.join(directory, "__init__.py") + create_file_from_template(init_path, "shared/init.j2", {}, success_message, should_format=False) + + +# change the current working dir tempporary @contextmanager def change_cwd(path: str): - """Temporarily change the current working directory. - - Ensures the original directory is restored even if an exception occurs. - """ original_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(original_cwd) + + +# get app names from USER_DEFINED_APPS section in project_name/settings/base.py +def extract_existing_apps(content: str) -> set: + lines = content.split("\n") + existing_apps = set() + in_user_apps = False + + for line in lines: + if "USER_DEFINED_APPS" in line and "=" in line: + in_user_apps = True + elif in_user_apps and line.strip() == "]": + break + elif in_user_apps: + line_stripped = line.strip().strip(",").strip() + for quote in ('"', "'"): + if line_stripped.startswith(quote) and line_stripped.endswith(quote): + existing_apps.add(line_stripped.strip(quote)) + break + + return existing_apps + + +# format app names as list entries with proper indentation +def format_app_entries(apps: list) -> list: + return [f' "{app}",' for app in apps] + + +# check if line starts a new APP section +def is_app_section_start(line: str) -> bool: + return "=" in line and any(keyword in line for keyword in ("BUILT_IN_APPS", "THIRD_PARTY_APPS", "INSTALLED_APPS")) + + +# check if closing bracket belongs to USER_DEFINED_APPS by looking ahead +def is_user_apps_closing_bracket(lines: list, current_idx: int) -> bool: + for next_idx in range(current_idx + 1, min(current_idx + 3, len(lines))): + next_line = lines[next_idx].strip() + if next_line and "BUILT_IN_APPS" in next_line: + return True + return True # Default to True if we're inside USER_DEFINED_APPS + + +# split line with closing bracnket and insert apps +def split_bracket_line(line: str, apps_to_add: list) -> list: + bracket_pos = line.rfind("]") + before_bracket = line[:bracket_pos].rstrip() if bracket_pos > 0 else line.rstrip() + after_bracket = line[bracket_pos:] if bracket_pos > 0 else "]" + + result = [before_bracket] + result.extend(format_app_entries(apps_to_add)) + result.append(after_bracket) + return result + + +# insert apps into USER_DEFINED_APPS section before the closing bracket. +def insert_apps_into_user_defined_apps(content: str, apps_to_add: list) -> str: + lines = content.split("\n") + new_lines = [] + in_user_apps = False + apps_added = False + + for i, line in enumerate(lines): + # Entering USER_DEFINED_APPS section + if "USER_DEFINED_APPS" in line and "=" in line and not apps_added: + in_user_apps = True + + # Handle closing bracket on same line + if "]" in line: + new_lines.extend(split_bracket_line(line, apps_to_add)) + apps_added = True + in_user_apps = False + else: + new_lines.append(line) + + # Closing bracket on separate line + elif in_user_apps and line.strip() == "]" and not apps_added: + if is_user_apps_closing_bracket(lines, i): + new_lines.extend(format_app_entries(apps_to_add)) + new_lines.append(line) + apps_added = True + in_user_apps = False + else: + new_lines.append(line) + + # Safety: hit another APP section without closing bracket + elif in_user_apps and is_app_section_start(line) and not apps_added: + new_lines.extend(format_app_entries(apps_to_add)) + new_lines.append("]") + new_lines.append(line) + apps_added = True + in_user_apps = False + + else: + new_lines.append(line) + + if not apps_added: + UIFormatter.print_error("Could not find or update USER_DEFINED_APPS section in base.py") + return None + + return "\n".join(new_lines) + + +# calculate app module paths based on nested structure +def calculate_app_module_paths(app_names: list, metadata: dict) -> list: + nested = bool(metadata.get("nested_apps")) + nested_dir_name = metadata.get("nested_dir") if nested else None + return [f"{nested_dir_name}.{app_name}" if nested and nested_dir_name else app_name for app_name in app_names] + + +# calculate app module path for a single app +def calculate_app_module_path(app_name: str, nested: bool, nested_dir: str | None) -> str: + return f"{nested_dir}.{app_name}" if nested and nested_dir else app_name + + +# check if a dir is a Django project by looking for manage.py +def is_django_project(directory: str = None) -> bool: + if directory is None: + directory = os.getcwd() + manage_py_path = os.path.join(directory, "manage.py") + return os.path.exists(manage_py_path) + + +# search the project dir that contains settings/base.py +def find_project_dir(search_dir: str = None) -> tuple[str | None, str | None]: + if search_dir is None: + search_dir = os.getcwd() + + for item in os.listdir(search_dir): + if os.path.isdir(item) and not item.startswith(".") and item != "__pycache__": + candidate = os.path.join(search_dir, item) + base_py = os.path.join(candidate, "settings", "base.py") + if os.path.exists(base_py): + return candidate, base_py + return None, None + + +# search the project_name/settings dir path +def find_settings_path(search_dir: str = None) -> str | None: + project_dir, settings_base_path = find_project_dir(search_dir) + if settings_base_path: + return os.path.dirname(settings_base_path) + return None + + +# get the path to project_name/settings/base.py +def get_base_settings_path(project_root: str, project_name: str) -> str: + settings_dir = os.path.join(project_root, project_name, "settings") + return os.path.join(settings_dir, "base.py") + + +# read the content of project_name/settings/base.py +def read_base_settings(project_root: str, project_name: str) -> str | None: + base_settings_path = get_base_settings_path(project_root, project_name) + if not os.path.exists(base_settings_path): + return None + + with open(base_settings_path) as f: + return f.read() + + +# check for nested app structure(e.g: "apps.users" means nested) from project_name/settings/base.py +def detect_nested_structure_from_settings( + base_settings_path: str, search_dir: str = None +) -> tuple[bool, str | None, str]: + if search_dir is None: + search_dir = os.getcwd() + + if not os.path.exists(base_settings_path): + return False, None, search_dir + + try: + with open(base_settings_path) as f: + base_content = f.read() + + in_user_apps = False + for line in base_content.splitlines(): + if "USER_DEFINED_APPS" in line and "=" in line: + in_user_apps = True + continue + if in_user_apps and "]" in line: + break + if in_user_apps: + line_stripped = line.strip().strip(",") + if line_stripped.startswith('"') or line_stripped.startswith("'"): + app_label = line_stripped.strip("\"'") + if "." in app_label: + nested_dir_name = app_label.split(".", 1)[0] + nested_path = os.path.join(search_dir, nested_dir_name) + if os.path.isdir(nested_path): + return True, nested_dir_name, nested_path + except Exception: + pass + + return False, None, search_dir diff --git a/pyproject.toml b/pyproject.toml index 0c1fccc..b053ef7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +44,6 @@ dependencies = [ "rich>=14.2.0", "ruff>=0.14.2", "jinja2>=3.1.0", - "django>=4.2,<6.0", ] [project.urls]