feat(djinit/utils): add replace_app_in_user_defined_apps and extend startapp with custom app_module support

This change introduces a helper to replace app entries in USER_DEFINED_APPS and makes the startapp command more flexible by allowing callers to specify the app module name.

New Features:
- Add replace_app_in_user_defined_apps utility function in djinit/utils/common.py
- Introduce app_config_name context and accept app_module argument in DjangoHelper.startapp()

Enhancements:
- Preserve indentation when replacing entries
- Allow custom app module specification instead of defaulting to app_name

Bug Fixes: (none)
This commit is contained in:
sankalp committed 2026-01-31 02:15:36 +05:45
1 parent 0fde5c7aa8
commit 41782c3df0
2 files changed
+41 -2

No files matched your search

+27
View File
@@ -203,6 +203,33 @@ def insert_apps_into_user_defined_apps(content: str, apps_to_add: list) -> str:
return "\n".join(new_lines)
def replace_app_in_user_defined_apps(content: str, old_app: str, new_app: str) -> str | None:
"""Replace an app entry in USER_DEFINED_APPS with a new one."""
lines = content.split("\n")
new_lines = []
replaced = False
for line in lines:
if not replaced and _parse_app_entry_from_line(line) == old_app:
# Try to preserve indentation
indent_idx = 0
for char in line:
if char.isspace():
indent_idx += 1
else:
break
indent = line[:indent_idx] if indent_idx > 0 else " "
new_lines.append(f'{indent}"{new_app}",')
replaced = True
else:
new_lines.append(line)
if replaced:
return "\n".join(new_lines)
return None
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
+14 -2
View File
@@ -60,12 +60,24 @@ class DjangoHelper:
raise DjinitError(f"Error creating Django project: {e}", details=str(e)) from e
@staticmethod
def startapp(app_name: str, directory: str) -> None:
def startapp(app_name: str, directory: str, app_module: str = None) -> None:
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}
# Prepare context
app_config_name = app_name.title().replace('_', '')
context = {
"app_name": app_name,
"app_config_name": app_config_name,
"django_version": DjangoHelper.DJANGO_VERSION
}
# Use provided app_module or default to app_name (path calculation handled by caller)
if not app_module:
app_module = app_name
context["app_module"] = app_module
create_init_file(app_dir, f"Created {app_name}/__init__.py")