simpletodoapp-ayt143/alembic/find_modules.py

74 lines
2.2 KiB
Python

"""
Module finder helper for Alembic migrations in containerized environments.
"""
import sys
from pathlib import Path
def setup_python_path():
"""
Add necessary paths to Python's sys.path to make imports work
in various environments including Docker containers
"""
# Get the directory where this script is located
current_dir = Path(__file__).resolve().parent
# The project root is one level up from the 'alembic' directory
project_root = current_dir.parent
# Add the project root to the Python path if it's not already there
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
# Container environments often mount code in specific locations
# Check multiple possible locations
possible_repo_paths = [
Path('/app/repo'), # Common Kubernetes/Docker path
Path('/app'), # Another common Docker path
Path('/projects/simpletodoapp-ayt143') # Local development path
]
# Add all existing paths to sys.path
for repo_path in possible_repo_paths:
if repo_path.exists() and str(repo_path) not in sys.path:
sys.path.insert(0, str(repo_path))
# Debug information to help troubleshoot path issues
print(f"Python sys.path configured as: {sys.path}")
# Return the actual Python paths used, for debugging
return sys.path
def find_module_path(module_name, possible_paths=None):
"""
Try to find a module by checking multiple possible locations.
Returns the full path to the module if found, None otherwise.
Args:
module_name: Name of the module to find (e.g. 'app.models.todo')
possible_paths: List of base paths to check
Returns:
Path object if module found, None otherwise
"""
if possible_paths is None:
possible_paths = sys.path
module_parts = module_name.split('.')
for base_path in possible_paths:
path = Path(base_path)
for part in module_parts:
path = path / part
py_path = path.with_suffix('.py')
init_path = path / '__init__.py'
if py_path.exists():
return py_path
elif init_path.exists():
return init_path
return None