Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions aegis/commands/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,14 @@ def init_command(
typer.echo("❌ Project creation cancelled")
raise typer.Exit(0)

# Handle force overwrite by completely removing existing directory
project_path = base_output_dir / project_name
if force and project_path.exists():
typer.echo(f"🗑️ Removing existing directory: {project_path}")
import shutil

shutil.rmtree(project_path)

# Create project using cookiecutter
typer.echo()
typer.echo(f"🔧 Creating project: {project_name}")
Expand All @@ -317,18 +325,11 @@ def init_command(
extra_context=extra_context,
output_dir=str(base_output_dir),
no_input=True, # Don't prompt user, use our context
overwrite_if_exists=force,
overwrite_if_exists=False, # No longer needed since we remove directory first
)

typer.echo("✅ Project created successfully!")

# Show next steps
typer.echo()
typer.echo("📋 Next steps:")
typer.echo(f" cd {project_path.resolve()}")
typer.echo(" uv sync")
typer.echo(" cp .env.example .env")
typer.echo(" make server")
# Note: Comprehensive setup output is now handled by the post-generation hook
# which provides better status reporting and automated setup

except ImportError:
typer.echo("❌ Error: cookiecutter not installed", err=True)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

"_comment_internal": "Internal variables for template logic",
"_has_additional_components": "{% if cookiecutter.include_scheduler == 'yes' or cookiecutter.include_redis == 'yes' or cookiecutter.include_worker == 'yes' or cookiecutter.include_database == 'yes' or cookiecutter.include_cache == 'yes' %}yes{% else %}no{% endif %}",
"_include_migrations": "{% if cookiecutter.include_auth == 'yes' %}yes{% else %}no{% endif %}",

"_comment_dependencies": "Component-specific dependencies",
"_scheduler_deps": "{% if cookiecutter.include_scheduler == 'yes' %}apscheduler>=3.10.0{% endif %}",
Expand Down
137 changes: 137 additions & 0 deletions aegis/templates/cookiecutter-aegis-project/hooks/post_gen_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,117 @@ def process_j2_templates():
return processed_files


def setup_project_environment():
"""
Complete project setup: dependencies, env file, migrations.

This function automates the entire setup process so users can
immediately start using their project after generation.
"""
print("\n🚀 Setting up your project environment...")

# Step 1: Install dependencies with uv
try:
print("📦 Installing dependencies with uv...")
result = subprocess.run(
["uv", "sync"],
cwd=PROJECT_DIRECTORY,
capture_output=True,
text=True,
timeout=300, # 5 minutes for dependency installation
Comment thread
lbedner marked this conversation as resolved.
)

if result.returncode == 0:
print("✅ Dependencies installed successfully")
else:
print("⚠️ Dependency installation failed")
if result.stderr:
print(f" Error: {result.stderr.strip()}")
print("💡 Run 'uv sync' manually after project creation")
return False

except subprocess.TimeoutExpired:
print("⚠️ Dependency installation timeout - run 'uv sync' manually")
return False
except FileNotFoundError:
print("⚠️ uv not found in PATH")
print("💡 Install uv first: https://github.com/astral-sh/uv")
return False
except Exception as e:
print(f"⚠️ Dependency installation failed: {e}")
print("💡 Run 'uv sync' manually after project creation")
return False

# Step 2: Copy .env file
try:
print("📄 Setting up environment configuration...")
env_example = Path(PROJECT_DIRECTORY) / ".env.example"
env_file = Path(PROJECT_DIRECTORY) / ".env"

if env_example.exists() and not env_file.exists():
shutil.copy(env_example, env_file)
print("✅ Environment file created from .env.example")
elif env_file.exists():
print("✅ Environment file already exists")
else:
print("⚠️ No .env.example file found")

except Exception as e:
print(f"⚠️ Environment setup failed: {e}")
print("💡 Copy .env.example to .env manually")

# Step 3: Run migrations (if auth service included)
if "{{ cookiecutter.include_auth }}" == "yes":
try:
print("🗃️ Setting up database with auth schema...")

# Ensure data directory exists
data_dir = Path(PROJECT_DIRECTORY) / "data"
data_dir.mkdir(exist_ok=True)

# Verify alembic config exists before running migration
alembic_ini_path = Path(PROJECT_DIRECTORY) / "alembic" / "alembic.ini"
if not alembic_ini_path.exists():
print(f"⚠️ Alembic config file not found at {alembic_ini_path}")
print(
"💡 Skipping database migration. Please ensure the config file exists and run 'alembic upgrade head' manually."
)
return

# Run alembic migrations using uv run (ensures correct environment)
result = subprocess.run(
[
"uv",
"run",
"alembic",
"-c",
str(alembic_ini_path),
"upgrade",
"head",
],
cwd=PROJECT_DIRECTORY,
capture_output=True,
text=True,
timeout=30, # Reasonable timeout for initial migration
)

if result.returncode == 0:
print("✅ Database tables created successfully")
else:
print("⚠️ Database migration setup failed")
if result.stderr:
print(f" Error: {result.stderr.strip()}")
print("💡 Run 'alembic upgrade head' manually after project creation")

except subprocess.TimeoutExpired:
print("⚠️ Migration setup timeout - run 'alembic upgrade head' manually")
except Exception as e:
print(f"⚠️ Migration setup failed: {e}")
print("💡 Run 'alembic upgrade head' manually after project creation")

return True


def run_auto_formatting():
"""
Auto-format generated code by calling make fix.
Expand Down Expand Up @@ -196,14 +307,40 @@ def main():
):
remove_dir("docs/components")

# Remove Alembic directory if auth service not included
if "{{ cookiecutter.include_auth }}" != "yes":
remove_dir("alembic")

# Print only templates that survived cleanup
for file_path in processed_files:
if file_path.exists():
print(f"Processed template: {file_path.name}")

# Complete project setup: dependencies, env file, migrations
setup_success = setup_project_environment()

# Run auto-formatting after all processing is complete
run_auto_formatting()

# Print final status and next steps
print("\n" + "=" * 60)
if setup_success:
print("✅ Project ready to run!")
print("\n📋 Next steps:")
print(f" cd {Path(PROJECT_DIRECTORY).name}")
print(" make server")
print("\n💡 Your application is fully configured and ready to use!")
else:
print("⚠️ Project created with some setup issues")
print("\n📋 Manual setup required:")
print(f" cd {Path(PROJECT_DIRECTORY).name}")
print(" uv sync")
print(" cp .env.example .env")
if "{{ cookiecutter.include_auth }}" == "yes":
print(" alembic upgrade head")
print(" make server")
print("=" * 60)


if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,31 @@ docs-build: ## Build static documentation
@echo "📚 Building documentation..."
@uv run mkdocs build

{% if cookiecutter.include_database == "yes" %}#=============================================================================
# DATABASE MIGRATIONS
#=============================================================================

migrate: ## Apply database migrations
@echo "🗃️ Applying database migrations..."
@docker compose exec webserver alembic upgrade head

migrate-check: ## Check migration status
@echo "🔍 Checking migration status..."
@docker compose exec webserver alembic current

migrate-history: ## Show migration history
@echo "📜 Migration history:"
@docker compose exec webserver alembic history --verbose

migrate-reset: ## Reset database (WARNING: destructive)
@echo "⚠️ This will destroy all data in the database!"
@read -p "Are you sure? Type 'yes' to continue: " confirm && [ "$$confirm" = "yes" ] || exit 1
@docker compose exec webserver alembic downgrade base
@docker compose exec webserver alembic upgrade head
@echo "✅ Database reset complete"

{% endif %}

#=============================================================================
# WORKER DEBUGGING (arq)
#=============================================================================
Expand Down Expand Up @@ -205,7 +230,7 @@ help: ## Show this help message
@echo
@echo "💡 TIP: Use 'make refresh' when everything is broken!"

.PHONY: build serve stop clean rebuild refresh restart logs logs-web logs-worker logs-redis{% if cookiecutter.include_scheduler == "yes" %} logs-scheduler{% endif %} shell shell-worker ps redis-cli redis-stats redis-keys redis-reset health health-detailed health-json health-probe test test-verbose lint fix format typecheck check install deps-update clean-cache docs-serve docs-build worker-test status help
.PHONY: build serve stop clean rebuild refresh restart logs logs-web logs-worker logs-redis{% if cookiecutter.include_scheduler == "yes" %} logs-scheduler{% endif %} shell shell-worker ps redis-cli redis-stats redis-keys redis-reset health health-detailed health-json health-probe test test-verbose lint fix format typecheck check install deps-update clean-cache docs-serve docs-build{% if cookiecutter.include_database == "yes" %} migrate migrate-check migrate-history migrate-reset{% endif %} worker-test status help

# Default target - show help
.DEFAULT_GOAL := help
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version number format. This value is passed to the
# strftime() function and is used to generate revision timestamps.
# version_num_format = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses
# os.pathsep. If this key is omitted entirely, it falls back to the legacy
# behavior of splitting on spaces and/or commas.
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = driver://user:pass@localhost/dbname


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# format using "ruff" - use the console_scripts runner, against the "ruff" entrypoint
# hooks = ruff
# ruff.type = console_scripts
# ruff.entrypoint = ruff
# ruff.options = format REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Loading