feat: add pre-commit support to project generation

This commit is contained in:
sankalp committed 2025-11-26 23:53:06 +05:45
1 parent a2cf00d637
commit ac2b586c0d
13 files changed
+126 -172

No files matched your search

+1 -20
View File
@@ -19,7 +19,7 @@ class Cli:
self.primary_app = primary_app
self.app_names = app_names
self.metadata = metadata
if project_dir == ".": # handle '.' for current directory
if project_dir == ".":
self.project_root = os.getcwd()
else:
self.project_root = os.path.join(os.getcwd(), project_dir)
@@ -28,36 +28,23 @@ class Cli:
self.file_manager = FileManager(self.project_root, project_name, app_names, metadata)
def run_setup(self) -> bool:
# If predefined structure is enabled, adjust metadata defaults
if self.metadata.get("predefined_structure"):
# Default module name to 'config' for conventional layout
self.metadata.setdefault("project_module_name", "config")
# Ensure nested apps live under 'apps'
self.metadata.setdefault("nested_apps", True)
self.metadata.setdefault("nested_dir", "apps")
# Default apps for predefined structure
if not self.app_names:
self.app_names = ["users", "core"]
# propagate to managers
self.project_manager.app_names = self.app_names
# If unified structure is enabled, adjust metadata defaults
if self.metadata.get("unified_structure"):
# For unified structure, module name is 'core'
self.metadata.setdefault("project_module_name", "core")
# Ensure nested apps live under 'apps'
self.metadata.setdefault("nested_apps", True)
self.metadata.setdefault("nested_dir", "apps")
# Default apps for unified structure (empty, apps/core and apps/api are created by default)
if not self.app_names:
self.app_names = []
# propagate to managers
self.project_manager.app_names = self.app_names
# If single structure is enabled, adjust metadata defaults
if self.metadata.get("single_structure"):
# Module name is already set in input_handler
# No nested apps
self.metadata.setdefault("nested_apps", False)
if not self.app_names:
self.app_names = []
@@ -68,13 +55,10 @@ class Cli:
steps.append(("Creating Django project", self.project_manager.create_project))
if self.metadata.get("unified_structure"):
# Build unified structure
steps.append(("Creating unified structure", self.file_manager.create_unified_structure))
elif self.metadata.get("single_structure"):
# Build single folder structure
steps.append(("Creating single folder structure", self.file_manager.create_single_structure))
elif self.metadata.get("predefined_structure"):
# Build custom tree and then inject apps into settings
steps.append(("Creating predefined structure", self.file_manager.create_predefined_structure))
steps.append(("Adding apps to settings", self.project_manager.add_apps_to_settings))
else:
@@ -95,11 +79,9 @@ class Cli:
total_steps = len(steps)
success = True
# Create live progress display
progress, task = UIFormatter.create_live_progress(description="Setup Progress", total_steps=total_steps)
with progress:
# Execute each step with progress tracking
for step_number, (description, step_func) in enumerate(steps, 1):
result = step_func()
if not result:
@@ -107,7 +89,6 @@ class Cli:
UIFormatter.print_error(f"Step {step_number} failed: {description}")
break
# Update the same progress bar
progress.update(task, advance=1, description=f"Step {step_number}/{total_steps}")
return success
+2 -7
View File
@@ -16,31 +16,26 @@ from djinit.scripts.input_handler import confirm_setup, get_user_input
def clear_screen() -> None:
try:
if os.name == "nt":
subprocess.run("cls", shell=True, check=True) # Windows
subprocess.run("cls", shell=True, check=True)
else:
subprocess.run("clear", shell=True, check=True) # Linux/MacOS
subprocess.run("clear", shell=True, check=True)
except subprocess.CalledProcessError:
# If clearing fails, just print some newlines
console.print("\n" * 50)
def main() -> None:
args = parse_arguments()
# Handle secret command
if args.command == "secret":
handle_secret_command(args)
return
# Handle app command
if args.command == "app":
handle_app_command(args)
return
# Default to setup command
clear_screen()
# Display welcome screen
console.print()
console.print(UIFormatter.create_welcome_panel())
console.print()
-22
View File
@@ -69,16 +69,13 @@ class AppManager:
return os.path.exists(app_path)
def _create_django_app(self) -> bool:
# Verify manage.py exists in project root
if not os.path.exists(self.manage_py_path):
UIFormatter.print_error("Could not find manage.py file in project root")
return False
# If predefined structure detected (apps/ exists), scaffold nested layout using custom templates
if self._is_predefined_structure():
return self._create_predefined_app(os.path.join(self.current_dir, "apps"))
# Otherwise, use standard flat app generation
_, _, apps_base_dir = self._get_project_structure()
success = DjangoHelper.startapp(self.app_name, apps_base_dir)
if success:
@@ -101,15 +98,12 @@ class AppManager:
with open(base_settings_path) as f:
content = f.read()
# Get the app's module path (e.g., "apps.users" or just "users")
# For predefined structure, use "apps" as nested_dir
if self._is_predefined_structure():
app_module_path = f"apps.{self.app_name}"
else:
is_nested, nested_dir, _ = self._get_project_structure()
app_module_path = calculate_app_module_path(self.app_name, is_nested, nested_dir)
# 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")
@@ -119,7 +113,6 @@ class AppManager:
UIFormatter.print_error("Could not find USER_DEFINED_APPS section in base.py")
return False
# 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
@@ -133,33 +126,27 @@ class AppManager:
def _get_project_structure(self) -> tuple[bool, Optional[str], str]:
"""Get project structure with caching to avoid repeated detection."""
if self._project_structure_cache is None:
# Find project directory with settings/base.py
project_dir, settings_base_path = find_project_dir(self.current_dir)
if project_dir is None:
self._project_structure_cache = (False, None, self.current_dir)
else:
# Detect nested structure from settings file
self._project_structure_cache = detect_nested_structure_from_settings(
settings_base_path, self.current_dir
)
return self._project_structure_cache
def _is_predefined_structure(self) -> bool:
# Heuristic: presence of 'apps' directory at project root (where manage.py lives) and 'api' dir
apps_dir = os.path.join(self.current_dir, "apps")
api_dir = os.path.join(self.current_dir, "api")
return os.path.isdir(apps_dir) and os.path.isdir(api_dir)
def _is_restricted_structure(self) -> bool:
"""Check if the project structure is Unified or Single Folder."""
# Check for Unified Structure: apps/api exists
apps_api_dir = os.path.join(self.current_dir, "apps", "api")
if os.path.isdir(apps_api_dir):
return True
# Check for Single Folder Structure
# No apps/ directory, but project dir has models/ and api/
apps_dir = os.path.join(self.current_dir, "apps")
if os.path.isdir(apps_dir):
return False
@@ -179,12 +166,10 @@ class AppManager:
os.makedirs(app_dir, exist_ok=True)
create_init_file(app_dir, f"Created apps/{self.app_name}/__init__.py")
# Compute names for generic templates
model_class_name = "".join([part.capitalize() for part in self.app_name.split("_")])
app_module = f"apps.{self.app_name}"
base_context = {"app_name": self.app_name, "app_module": app_module, "model_class_name": model_class_name}
# Create apps.py
create_file_from_template(
os.path.join(app_dir, "apps.py"),
"components/apps.j2",
@@ -192,7 +177,6 @@ class AppManager:
f"Created apps/{self.app_name}/apps.py",
)
# Subfolders
subfolders = {
"models": [(f"{self.app_name}.py", "presets/predefined/apps/generic/models.j2")],
"serializers": [(f"{self.app_name}_serializer.py", "presets/predefined/apps/generic/serializers.j2")],
@@ -209,7 +193,6 @@ class AppManager:
file_path, template, base_context, f"Created apps/{self.app_name}/{folder}/{filename}"
)
# urls.py at app root
create_file_from_template(
os.path.join(app_dir, "urls.py"),
"presets/predefined/apps/generic/urls.j2",
@@ -217,7 +200,6 @@ class AppManager:
f"Created apps/{self.app_name}/urls.py",
)
# Add route include to api/v1/urls.py if present
self._add_to_api_v1_urls(self.app_name)
UIFormatter.print_success(f"Created Django app '{self.app_name}' with predefined structure in {apps_dir}")
@@ -238,10 +220,8 @@ class AppManager:
include_stmt = f'path("{app_name}/", include("apps.{app_name}.urls")),'
if include_stmt in content:
# already present
return
# Insert into urlpatterns list before closing ]
if "urlpatterns = [" in content:
parts = content.split("urlpatterns = [", 1)
before = parts[0]
@@ -249,7 +229,6 @@ class AppManager:
if "]" in rest:
idx = rest.rfind("]")
new_rest = rest[:idx]
# ensure newline and indentation
if not new_rest.endswith("\n"):
new_rest += "\n"
new_rest += f" {include_stmt}\n" + rest[idx:]
@@ -258,5 +237,4 @@ class AppManager:
with open(api_v1_urls, "w", encoding="utf-8") as f:
f.write(content)
except Exception:
# Non-fatal; leave API routes unchanged if edit fails
return
-8
View File
@@ -20,17 +20,14 @@ def parse_arguments() -> argparse.Namespace:
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Setup command (default)
setup_parser = subparsers.add_parser("setup", help="Create a new Django project")
setup_parser.add_argument("--project", help="Django project name")
setup_parser.add_argument("--app", help="Django app name")
# Secret command
secret_parser = subparsers.add_parser("secret", help="Generate Django secret keys")
secret_parser.add_argument("--count", type=int, default=3, help="Number of keys to generate")
secret_parser.add_argument("--length", type=int, default=50, help="Length of each secret key")
# App command
app_parser = subparsers.add_parser("app", help="Create one or more Django apps (comma or space separated)")
app_parser.add_argument(
"app_name",
@@ -70,8 +67,6 @@ def handle_app_command(args: argparse.Namespace) -> None:
UIFormatter.print_header("Django App Creation")
UIFormatter.print_info("")
# Parse comma-separated names and validate
# args.app_name is a list due to nargs="+"; split each token by comma
tokens = args.app_name if isinstance(args.app_name, list) else [args.app_name]
pieces = []
for token in tokens:
@@ -83,12 +78,10 @@ def handle_app_command(args: argparse.Namespace) -> None:
pieces.append(part)
app_names = pieces
# If no comma, keep single name behavior
if not app_names:
UIFormatter.print_error("App name cannot be empty")
sys.exit(1)
# Deduplicate while preserving order
seen = set()
deduped_names = []
for name in app_names:
@@ -102,7 +95,6 @@ def handle_app_command(args: argparse.Namespace) -> None:
UIFormatter.print_error(f"Invalid app name '{name}': {error_msg}")
sys.exit(1)
# Create apps sequentially
any_failure = False
for name in deduped_names:
app_manager = AppManager(name)
-20
View File
@@ -45,10 +45,6 @@ class Icons:
class UIFormatter:
"""Utility class for consistent UI formatting"""
# ============================================================================
# Basic Output Methods
# ============================================================================
@staticmethod
def print_success(message: str, icon: str = Icons.SUCCESS):
"""Print success message"""
@@ -74,10 +70,6 @@ class UIFormatter:
else:
console.print(f"[{UIColors.INFO}]{message}[/{UIColors.INFO}]")
# ============================================================================
# Progress & Headers
# ============================================================================
@staticmethod
def create_live_progress(description: str = "Setup Progress", total_steps: int = 100):
"""Create a live progress display"""
@@ -104,10 +96,6 @@ class UIFormatter:
"""Print a visual separator"""
console.print(f"[{style}]{char * width}[/{style}]")
# ============================================================================
# Panels & Tables
# ============================================================================
@staticmethod
def print_panel(content: str, title: str = "", border_style: str = "blue"):
"""Print content in a styled panel"""
@@ -130,10 +118,6 @@ class UIFormatter:
console.print(table)
# ============================================================================
# Welcome & Summary
# ============================================================================
@staticmethod
def create_welcome_panel():
"""Create a minimal welcome panel"""
@@ -171,10 +155,6 @@ class UIFormatter:
console.print("[red]Setup encountered an error. Check messages above.[/red]\n")
console.print(f"[bold red]{'═' * 70}[/bold red]\n")
# ============================================================================
# User Input
# ============================================================================
@staticmethod
@contextmanager
def status(message: str, spinner: str = "dots"):
-10
View File
@@ -16,7 +16,6 @@ from djinit.utils import (
class DjangoHelper:
# Django version to use in generated files (matches Django 5.2)
DJANGO_VERSION = "5.2"
@staticmethod
@@ -24,22 +23,16 @@ class DjangoHelper:
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)
# For unified structure, the project config is "core", not project_name
# The unified structure is created separately by create_unified_structure
if unified:
# Just create manage.py for unified, structure is created by create_unified_structure
return True
# Create project config directory
project_config_dir = os.path.join(directory, project_name)
create_directory_with_init(project_config_dir, f"Created {project_name}/__init__.py")
# Create settings directory and files
settings_dir = os.path.join(project_config_dir, "settings")
create_directory_with_init(settings_dir, f"Created {project_name}/settings/__init__.py")
@@ -51,7 +44,6 @@ class DjangoHelper:
]
create_files_from_templates(settings_dir, settings_files, f"{project_name}/settings/")
# Create project-level files
urls_context = {"project_name": project_name, "django_version": DjangoHelper.DJANGO_VERSION}
project_files = [
("urls.py", "config/urls/base.j2", urls_context),
@@ -74,7 +66,6 @@ class DjangoHelper:
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 = [
@@ -90,7 +81,6 @@ class DjangoHelper:
create_files_from_templates(app_dir, app_files, f"{app_name}/")
# Create migrations directory and __init__.py
migrations_dir = os.path.join(app_dir, "migrations")
create_directory_with_init(migrations_dir, f"Created {app_name}/migrations/__init__.py")
-41
View File
@@ -23,8 +23,6 @@ class FileManager:
self.project_name = project_name
self.app_names = app_names
self.metadata = metadata
# Use module name (e.g., 'config') for Django package paths if provided
# Fall back to project_name if key present but None
self.module_name = metadata.get("project_module_name") or project_name
self.project_configs = os.path.join(project_root, self.module_name)
self.settings_folder = os.path.join(self.project_configs, "settings")
@@ -105,7 +103,6 @@ class FileManager:
)
def create_pyproject_toml(self, metadata: dict) -> bool:
# Default package_name to "backend" if it's "." or empty
package_name = metadata.get("package_name", "backend")
package_name = get_package_name(package_name)
context = {"package_name": package_name, "project_name": self.project_name}
@@ -142,16 +139,13 @@ class FileManager:
)
def create_predefined_structure(self) -> bool:
# Ensure apps package
apps_dir = os.path.join(self.project_root, "apps")
create_directory_with_init(apps_dir, "Created apps/__init__.py")
# users app
users_dir = os.path.join(apps_dir, "users")
create_directory_with_init(users_dir, "Created apps/users/__init__.py")
self._create_apps_py(users_dir, "users")
# Nested folders and files for users
users_subfolders = {
"models": [("user.py", "presets/predefined/apps/users/models.j2")],
"serializers": [("user_serializer.py", "presets/predefined/apps/users/serializers.j2")],
@@ -161,7 +155,6 @@ class FileManager:
}
self._create_files_from_specs(users_dir, users_subfolders, {"app_module": "apps.users"})
# users urls.py at app root
users_urls_path = os.path.join(users_dir, "urls.py")
create_file_from_template(
users_urls_path,
@@ -170,11 +163,9 @@ class FileManager:
"Created apps/users/urls.py",
)
# core app
core_dir = os.path.join(apps_dir, "core")
create_directory_with_init(core_dir, "Created apps/core/__init__.py")
# core subfolders and files
core_subfolders = {
"utils": [("responses.py", "presets/predefined/core/utils/responses.j2")],
"mixins": [("timestamped_model.py", "presets/predefined/core/mixins/timestamped_model.j2")],
@@ -182,25 +173,21 @@ class FileManager:
}
self._create_files_from_specs(core_dir, core_subfolders, {})
# core/exceptions.py
exceptions_path = os.path.join(core_dir, "exceptions.py")
create_file_from_template(
exceptions_path, "presets/predefined/core/exceptions.j2", {}, "Created apps/core/exceptions.py"
)
# api package
api_dir = os.path.join(self.project_root, "api")
create_directory_with_init(api_dir, "Created api/__init__.py")
api_urls_path = os.path.join(api_dir, "urls.py")
create_file_from_template(api_urls_path, "presets/predefined/api/urls.j2", {}, "Created api/urls.py")
# api/v1
api_v1_dir = os.path.join(api_dir, "v1")
create_directory_with_init(api_v1_dir, "Created api/v1/__init__.py")
api_v1_urls_path = os.path.join(api_v1_dir, "urls.py")
create_file_from_template(api_v1_urls_path, "presets/predefined/api/v1/urls.j2", {}, "Created api/v1/urls.py")
# overwrite project urls to include api
project_urls_path = os.path.join(self.project_configs, "urls.py")
create_file_from_template(
project_urls_path,
@@ -213,21 +200,16 @@ class FileManager:
return True
def create_unified_structure(self) -> bool:
# Create core directory structure
core_dir = os.path.join(self.project_root, "core")
create_directory_with_init(core_dir, "Created core/__init__.py")
# Create core/settings directory
settings_dir = os.path.join(core_dir, "settings")
create_directory_with_init(settings_dir, "Created core/settings/__init__.py")
# Generate secret key for development settings
from djinit.scripts.secretkey_generator import generate_secret_key
secret_key = generate_secret_key()
# Create settings files using project templates with unified context
# For unified structure, project_module_name is "core"
base_context = {
"project_name": "core", # Use "core" as the module name
"app_names": ["apps.core", "apps.api"] + [f"apps.{app}" for app in self.app_names],
@@ -235,7 +217,6 @@ class FileManager:
}
dev_context = {"secret_key": secret_key}
# Settings files
for filename, context in [
("base.py", base_context),
("development.py", dev_context),
@@ -247,7 +228,6 @@ class FileManager:
filepath, template_path, context, f"Created core/settings/{filename}", should_format=True
)
# Core project files
core_files = [
("urls.py", "config/urls/with_api.j2", {"api_module": "apps.api"}),
("wsgi.py", "config/wsgi.j2", {}),
@@ -257,18 +237,14 @@ class FileManager:
filepath = os.path.join(core_dir, filename)
create_file_from_template(filepath, template, context, f"Created core/{filename}", should_format=True)
# Create apps directory
apps_dir = os.path.join(self.project_root, "apps")
create_directory_with_init(apps_dir, "Created apps/__init__.py")
# Create apps/core
apps_core_dir = os.path.join(apps_dir, "core")
create_directory_with_init(apps_core_dir, "Created apps/core/__init__.py")
# Create apps/core/apps.py
self._create_apps_py(apps_core_dir, "", "Created apps/core/apps.py", should_format=True)
# Create apps/core/models
models_dir = os.path.join(apps_core_dir, "models")
model_files = [
("__init__.py", "components/models.j2"),
@@ -280,7 +256,6 @@ class FileManager:
models_dir, [(f, t, {}) for f, t in model_files], "apps/core/models/", should_format=True
)
# Create apps/core/utils
utils_dir = os.path.join(apps_core_dir, "utils")
utils_files = [
("__init__.py", "presets/unified/apps/core/utils/__init__.py.j2"),
@@ -291,15 +266,12 @@ class FileManager:
utils_dir, [(f, t, {}) for f, t in utils_files], "apps/core/utils/", should_format=True
)
# Create apps/core/permissions and middleware
self._create_subdirectories_with_init(apps_core_dir, ["permissions", "middleware"], "apps/core/")
# Create apps/api
apps_api_dir = os.path.join(apps_dir, "api")
create_directory_with_init(apps_api_dir, "Created apps/api/__init__.py")
self._create_apps_py(apps_api_dir, "apps.api", "Created apps/api/apps.py", should_format=True)
# Create apps/api subdirectories
self._create_subdirectories_with_init(
apps_api_dir, ["models", "serializers", "views", "services", "tests", "urls", "admin"], "apps/api/"
)
@@ -307,20 +279,16 @@ class FileManager:
return True
def create_single_structure(self) -> bool:
# Create project directory structure (project/)
project_dir = os.path.join(self.project_root, self.module_name)
create_directory_with_init(project_dir, f"Created {self.module_name}/__init__.py")
# Create project/settings directory
settings_dir = os.path.join(project_dir, "settings")
create_directory_with_init(settings_dir, f"Created {self.module_name}/settings/__init__.py")
# Generate secret key for development settings
from djinit.scripts.secretkey_generator import generate_secret_key
secret_key = generate_secret_key()
# Create settings files
base_context = {
"project_name": self.module_name,
"app_names": [self.module_name], # Project acts as the app
@@ -339,7 +307,6 @@ class FileManager:
filepath, template_path, context, f"Created {self.module_name}/settings/{filename}", should_format=True
)
# Core project files
project_files = [
(
"urls.py",
@@ -355,15 +322,9 @@ class FileManager:
filepath, template, context, f"Created {self.module_name}/{filename}", should_format=True
)
# Create app component directories
# Note: routes, serializers, views are NOT created here
# They should be organized under api/ by model name (e.g., api/user/views.py)
components = ["admin", "api", "models", "tests"]
self._create_subdirectories_with_init(project_dir, components, f"{self.module_name}/")
# Create basic files for components to ensure valid python packages/modules
# admin
create_file_from_template(
os.path.join(project_dir, "admin", "__init__.py"),
"components/admin.j2",
@@ -371,7 +332,6 @@ class FileManager:
f"Created {self.module_name}/admin/__init__.py",
)
# models
create_file_from_template(
os.path.join(project_dir, "models", "__init__.py"),
"components/models.j2",
@@ -379,7 +339,6 @@ class FileManager:
f"Created {self.module_name}/models/__init__.py",
)
# Create README files for api and models directories
create_file_from_template(
os.path.join(project_dir, "api", "README.md"),
"components/api_readme.j2",
-15
View File
@@ -35,7 +35,6 @@ class ProjectMetadata:
nested_apps: bool = False
nested_dir: str | None = None
use_database_url: bool = False
# predefined structure support
predefined_structure: bool = False
predefined_structure: bool = False
unified_structure: bool = False
@@ -170,7 +169,6 @@ class InputCollector:
f"[{UIColors.HIGHLIGHT}]Enter project directory name:[/{UIColors.HIGHLIGHT}] "
).strip()
# 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 "."
@@ -370,14 +368,12 @@ class CharReader:
@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(
@@ -416,7 +412,6 @@ class CharReader:
for encoding in encodings:
try:
ch = msvcrt.getch()
# Detect Ctrl+C (ETX character \x03)
if isinstance(ch, bytes):
if ch == b"\x03":
raise KeyboardInterrupt
@@ -452,7 +447,6 @@ class CharReader:
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
# Detect Ctrl+C (ETX character \x03)
if ord(ch) == 3: # Ctrl+C
raise KeyboardInterrupt
return ch.lower()
@@ -465,7 +459,6 @@ def get_user_input() -> Tuple[str, str, str, list, dict]:
collector = InputCollector()
console.print()
# Pre-step: Ask for structure type first
UIFormatter.print_separator()
console.print(f"\n[{UIColors.INFO}]Choose Structure Type[/{UIColors.INFO}]\n")
console.print(f"[{UIColors.MUTED}]1. Standard structure (default Django layout)[/{UIColors.MUTED}]")
@@ -491,7 +484,6 @@ def get_user_input() -> Tuple[str, str, str, list, dict]:
UIFormatter.print_error("Maximum attempts reached for project directory name. Exiting.")
sys.exit(1)
# Ask for module name after project directory for single layout
single_module_name = None
if use_single:
console.print()
@@ -517,7 +509,6 @@ def get_user_input() -> Tuple[str, str, str, list, dict]:
return project_dir, project_name, primary_app, app_names, metadata_dict
# Section 1: Project Setup (standard flow)
UIFormatter.print_separator()
console.print(f"\n[{UIColors.INFO}]Step 1: Project Setup[/{UIColors.INFO}]\n")
console.print(f"[{UIColors.MUTED}]Press Enter or enter '.' to create in current directory[/{UIColors.MUTED}]")
@@ -536,7 +527,6 @@ def get_user_input() -> Tuple[str, str, str, list, dict]:
)
console.print()
# Section 2: Django Apps
console.print()
UIFormatter.print_separator()
console.print(f"\n[{UIColors.INFO}]Step 2: Django Apps[/{UIColors.INFO}]\n")
@@ -544,14 +534,10 @@ def get_user_input() -> Tuple[str, str, str, list, dict]:
app_names = collector.get_app_names()
console.print()
# Section 3: CI/CD Pipeline
use_github, use_gitlab = collector.get_cicd_choice()
# Section 4: Database Configuration
use_database_url = collector.get_database_config_choice()
# Create metadata
# Default package_name to "backend" if project_dir is "." or empty
package_name = get_package_name(project_dir)
metadata = ProjectMetadata(
package_name=package_name,
@@ -564,7 +550,6 @@ def get_user_input() -> Tuple[str, str, str, list, dict]:
console.print()
# Return in legacy format for backward compatibility
return project_dir, project_name, app_names[0], app_names, metadata.to_dict()
except KeyboardInterrupt:
UIFormatter.print_info("\nSetup cancelled by user.")
-2
View File
@@ -8,10 +8,8 @@ import re
import sys
from typing import Any, Callable, Tuple
# Names that conflict with Django's structure
DJANGO_RESERVED = {"django", "test", "site-packages", "admin"}
# Common Python builtin modules
PYTHON_BUILTINS = set(sys.builtin_module_names)
NAME_PATTERN = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*$")
-4
View File
@@ -24,8 +24,6 @@ class ProjectManager:
self.app_names = app_names
self.metadata = metadata
self.project_root = os.getcwd() if project_dir == "." else os.path.join(os.getcwd(), project_dir)
# Support custom module name for the Django config package (e.g., 'config')
# Fall back to project_name if key present but None
self.module_name = metadata.get("project_module_name") or self.project_name
def create_project(self) -> bool:
@@ -59,7 +57,6 @@ class ProjectManager:
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
@@ -113,7 +110,6 @@ class ProjectManager:
apps_base_dir = self._get_apps_base_dir()
# In predefined or unified structure, apps layout differs; skip strict per-app validation
if (
not self.metadata.get("predefined_structure")
and not self.metadata.get("unified_structure")
-23
View File
@@ -17,7 +17,6 @@ def format_file(filename: str) -> None:
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:
with open(filename, "w") as file:
file.write(content)
@@ -25,11 +24,9 @@ def create_file_with_content(filename: str, content: str, success_message: str,
if should_format:
format_file(filename)
# UIFormatter.print_success(success_message)
return True
# create a file from a template
def create_file_from_template(
file_path: str,
template_path: str,
@@ -41,7 +38,6 @@ def create_file_from_template(
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, "project/init.j2", {}, success_message, should_format=False)
@@ -79,7 +75,6 @@ def get_package_name(project_dir: str) -> str:
return "backend" if project_dir == "." or not project_dir else project_dir
# change the current working dir tempporary
@contextmanager
def change_cwd(path: str):
original_cwd = os.getcwd()
@@ -118,7 +113,6 @@ def _iterate_user_apps_lines(content: str):
yield line
# get app names from USER_DEFINED_APPS section in project_name/settings/base.py
def extract_existing_apps(content: str) -> set:
existing_apps = set()
for line in _iterate_user_apps_lines(content):
@@ -128,17 +122,14 @@ def extract_existing_apps(content: str) -> set:
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()
@@ -147,7 +138,6 @@ def is_user_apps_closing_bracket(lines: list, current_idx: int) -> bool:
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()
@@ -159,7 +149,6 @@ def split_bracket_line(line: str, apps_to_add: list) -> list:
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 = []
@@ -167,11 +156,9 @@ def insert_apps_into_user_defined_apps(content: str, apps_to_add: list) -> str:
apps_added = False
for i, line in enumerate(lines):
# Entering USER_DEFINED_APPS section
if _is_user_apps_section_start(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
@@ -179,7 +166,6 @@ def insert_apps_into_user_defined_apps(content: str, apps_to_add: list) -> str:
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))
@@ -189,7 +175,6 @@ def insert_apps_into_user_defined_apps(content: str, apps_to_add: list) -> str:
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("]")
@@ -207,19 +192,16 @@ def insert_apps_into_user_defined_apps(content: str, apps_to_add: list) -> str:
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 [calculate_app_module_path(app_name, nested, nested_dir_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()
@@ -227,7 +209,6 @@ def is_django_project(directory: str = None) -> bool:
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()
@@ -241,7 +222,6 @@ def find_project_dir(search_dir: str = None) -> tuple[str | None, str | None]:
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:
@@ -249,13 +229,11 @@ def find_settings_path(search_dir: str = None) -> str | None:
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):
@@ -265,7 +243,6 @@ def read_base_settings(project_root: str, project_name: str) -> str | None:
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]: