refactor: improve project creation and app generation for better compatibility

This commit is contained in:
sankalp committed 2025-11-09 14:26:00 +05:45
commit cdaeede45a
41 files changed
+239 -810

No files matched your search

+5
View File
@@ -19,7 +19,12 @@ class Cli:
self.primary_app = primary_app
self.app_names = app_names
self.metadata = metadata
<<<<<<< HEAD
if project_dir == ".": # handle '.' for current directory
=======
# Handle '.' for current directory
if project_dir == ".":
>>>>>>> origin/main
self.project_root = os.getcwd()
else:
self.project_root = os.path.join(os.getcwd(), project_dir)
+14
View File
@@ -4,6 +4,11 @@ Handles creation of Django apps and updating settings.
"""
import os
<<<<<<< HEAD
=======
import subprocess
import sys
>>>>>>> origin/main
from typing import Optional
from djinit.scripts.console_ui import UIFormatter
@@ -70,9 +75,18 @@ class AppManager:
UIFormatter.print_error("Could not find manage.py file in project root")
return False
<<<<<<< HEAD
# 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"))
=======
# 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
)
>>>>>>> origin/main
# Otherwise, use standard flat app generation
success = DjangoHelper.startapp(self.app_name, apps_base_dir)
+196
View File
@@ -204,6 +204,10 @@ class InputCollector:
console.print(f" [{UIColors.SUCCESS}]{option.key}[/{UIColors.SUCCESS}] {option.description}")
console.print()
<<<<<<< HEAD
=======
# Get valid keys from CICDOption enum
>>>>>>> origin/main
valid_keys = [option.key for option in CICDOption]
choice = CharReader.get_cicd_choice(
@@ -212,12 +216,24 @@ class InputCollector:
default=CICDOption.NONE.key,
)
<<<<<<< HEAD
choice_map = {
CICDOption.BOTH.key: (True, True),
CICDOption.GITHUB.key: (True, False),
CICDOption.GITLAB.key: (False, True),
}
return choice_map.get(choice, (False, False))
=======
# 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
>>>>>>> origin/main
def get_nested_apps_config(self) -> Tuple[bool, str | None]:
UIFormatter.print_separator()
@@ -226,7 +242,13 @@ class InputCollector:
)
console.print()
<<<<<<< HEAD
choice = CharReader.get_yes_no(f"[{UIColors.HIGHLIGHT}]Nested Django apps? (y/N):[/{UIColors.HIGHLIGHT}]")
=======
choice = CharReader.get_yes_no(
f"[{UIColors.HIGHLIGHT}]Nested Django apps? (y/N):[/{UIColors.HIGHLIGHT}]", default="n"
)
>>>>>>> origin/main
if choice != "y":
return False, None
@@ -246,7 +268,16 @@ class InputCollector:
console.print(f" [{UIColors.SUCCESS}]N[/{UIColors.SUCCESS}] Use individual database parameters")
console.print()
<<<<<<< HEAD
return CharReader.get_yes_no(f"[{UIColors.HIGHLIGHT}]Use DATABASE_URL? (Y/n):[/{UIColors.HIGHLIGHT}]") == "y"
=======
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"
>>>>>>> origin/main
class CharReader:
@@ -259,6 +290,7 @@ class CharReader:
return CharReader._get_char_unix()
@staticmethod
<<<<<<< HEAD
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
@@ -291,10 +323,30 @@ class CharReader:
# Handle Enter key (default)
if CharReader._is_enter_key(response):
return CharReader._handle_default(default)
=======
def get_yes_no(prompt: str, default: str = "n") -> str:
max_attempts = 3
attempt = 0
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()
>>>>>>> origin/main
response = response.lower()
# Validate response
<<<<<<< HEAD
if response in valid_keys_lower:
console.print(response.upper())
return response
@@ -307,11 +359,30 @@ class CharReader:
if attempt < CharReader.MAX_ATTEMPTS:
console.print(
f"[{UIColors.MUTED}]Please try again ({attempt}/{CharReader.MAX_ATTEMPTS}).[/{UIColors.MUTED}]"
=======
if response in ("y", "n"):
console.print(response.upper())
return response
# Invalid input - show error (only show if it's a printable character)
console.print()
if response.isprintable():
UIFormatter.print_error(f"Invalid input '{response}'. Please enter 'y' or 'n'.")
attempt += 1
if attempt < max_attempts:
console.print(
f"[{UIColors.MUTED}]Please try again ({attempt}/{max_attempts}).[/{UIColors.MUTED}]"
>>>>>>> origin/main
)
console.print()
else:
# Control character entered, treat as Enter
<<<<<<< HEAD
return CharReader._handle_default(default)
=======
console.print(default.upper())
return default.lower()
>>>>>>> origin/main
except KeyboardInterrupt:
console.print()
@@ -324,6 +395,7 @@ class CharReader:
return default.lower()
@staticmethod
<<<<<<< HEAD
def get_yes_no(prompt: str, default: str = None) -> str:
# Auto-detect default from prompt format (capital letter indicates default)
if default is None:
@@ -351,6 +423,70 @@ class CharReader:
default=default,
error_message=f"Invalid input '{{response}}'. Please enter one of: {valid_keys_str}.",
)
=======
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()
>>>>>>> origin/main
@staticmethod
def _get_char_windows() -> str:
@@ -389,10 +525,64 @@ def get_user_input() -> Tuple[str, str, str, list, dict]:
# Pre-step: Ask for structure type first
UIFormatter.print_separator()
<<<<<<< HEAD
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}]")
console.print(f"[{UIColors.MUTED}]2. Predefined structure (apps/users, apps/core, api/)[/{UIColors.MUTED}]")
console.print(f"[{UIColors.MUTED}]3. Unified structure (core/, apps/core, apps/api)[/{UIColors.MUTED}]")
=======
console.print(f"\n[{UIColors.INFO}]Step 1: Project Setup[/{UIColors.INFO}]\n")
console.print(f"[{UIColors.HIGHLIGHT}]Project Directory[/{UIColors.HIGHLIGHT}]")
console.print(f"[{UIColors.MUTED}]Where your project files will be created[/{UIColors.MUTED}]")
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)
if project_dir is None:
UIFormatter.print_error("Maximum attempts reached for project directory name. Exiting.")
sys.exit(1)
>>>>>>> origin/main
console.print()
structure_choice = console.input(
@@ -544,7 +734,13 @@ def confirm_setup(project_dir: str, project_name: str, app_names: list, metadata
console.print()
try:
<<<<<<< HEAD
response = CharReader.get_yes_no(f"[{UIColors.WARNING}]Proceed with setup? (y/N):[/{UIColors.WARNING}]")
=======
response = CharReader.get_yes_no(
f"[{UIColors.WARNING}]Proceed with setup? (y/N):[/{UIColors.WARNING}]", default="n"
)
>>>>>>> origin/main
return response == "y"
except KeyboardInterrupt:
+20
View File
@@ -22,14 +22,23 @@ class ProjectManager:
self.project_name = project_name
self.app_names = app_names
self.metadata = metadata
<<<<<<< HEAD
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
=======
# Handle '.' for current directory
if project_dir == ".":
self.project_root = os.getcwd()
else:
self.project_root = os.path.join(os.getcwd(), project_dir)
>>>>>>> origin/main
def create_project(self) -> bool:
os.makedirs(self.project_root, exist_ok=True)
<<<<<<< HEAD
unified = self.metadata.get("unified_structure", False)
success = DjangoHelper.startproject(self.module_name, self.project_root, unified=unified)
if success:
@@ -37,6 +46,17 @@ class ProjectManager:
else:
UIFormatter.print_error(f"Failed to create Django project '{self.project_name}'")
return success
=======
# 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
>>>>>>> origin/main
def create_apps(self) -> bool:
apps_base_dir = self.project_root
+4
View File
@@ -14,6 +14,10 @@ from djinit.scripts.template_engine import template_engine
def format_file(filename: str) -> None:
"""Format Python file using Ruff formatter."""
<<<<<<< HEAD
=======
# Use 'python -m ruff' instead of 'ruff' for better compatibility
>>>>>>> origin/main
subprocess.run([sys.executable, "-m", "ruff", "format", filename], check=False, capture_output=True)