refactor: extract CSS modules for session/settings and delete styles.css (Task 2.3)

- Create InstanceList.module.css, AppShell.module.css, SettingsTabLayout.module.css
- Create CommitPanel.module.css, FileViewer.module.css
- Create page CSS files: sessions, repo-workspace, dashboard, projects,
  git-history, ssh-keys, settings
- Update components to import and use CSS modules
- Delete monolithic styles.css (2,255 lines)
- Update main.tsx to import page CSS and new modules

Quality gates: tsc (pass), eslint (pass), build (pass)
Refs: repo-restructure Task 2.3
This commit is contained in:
Developer
2026-06-02 21:09:57 +00:00
parent c8c490eb2b
commit cccf4379d8
27 changed files with 2146 additions and 3388 deletions
+52 -296
View File
@@ -2,7 +2,6 @@
import logging
import uuid
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
@@ -16,124 +15,39 @@ from src.models.config_profile import ConfigProfile
from src.models.tool_type import ToolType
from src.models.user_config import UserConfig
from src.schemas.config_profile import (
ConfigProfileCreate,
ConfigProfileUpdate,
ConfigProfileResponse,
ConfigProfileDetailResponse,
ConfigIncludeCreate,
ConfigIncludeUpdate,
ConfigIncludeResponse,
ConfigMountCreate,
ConfigMountUpdate,
ConfigMountResponse,
ConfigProfileCreate,
ConfigProfileUpdate,
DefaultProfilesUpdate,
)
from src.services.config_profiles import (
get_owned_profile,
validate_includes_no_cycle,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/config-profiles", tags=["config-profiles"])
MAX_INCLUDES_DEPTH = 10
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
async def _get_owned_profile(
profile_id: uuid.UUID,
user_id: uuid.UUID,
session: AsyncSession,
) -> ConfigProfile:
"""Fetch a config profile and verify ownership."""
profile = await session.get(ConfigProfile, profile_id)
if profile is None or profile.user_id != user_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="config profile not found",
)
return profile
async def _detect_cycle(
session: AsyncSession,
profile_id: uuid.UUID,
visited: set[uuid.UUID] | None = None,
depth: int = 0,
) -> bool:
"""Detect cycles in profile includes using DFS.
Returns True if a cycle is detected.
"""
if depth > MAX_INCLUDES_DEPTH:
return True
if visited is None:
visited = set()
if profile_id in visited:
return True
visited.add(profile_id)
result = await session.execute(
select(ConfigInclude.included_profile_id).where(
ConfigInclude.profile_id == profile_id
)
)
included_ids = result.scalars().all()
for included_id in included_ids:
if await _detect_cycle(session, included_id, visited.copy(), depth + 1):
return True
return False
async def _validate_includes_no_cycle(
session: AsyncSession,
profile_id: uuid.UUID,
new_included_id: uuid.UUID | None = None,
) -> None:
"""Validate that adding an include wouldn't create a cycle."""
if new_included_id and await _detect_cycle(session, new_included_id, {profile_id}):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="adding this include would create a circular reference",
)
# ---------------------------------------------------------------------------
# Profile CRUD
# ---------------------------------------------------------------------------
@router.get(
"",
summary="List config profiles",
description="Get all config profiles for the current user. Optionally filter by tool type compatibility.",
)
@router.get("", summary="List config profiles")
async def list_config_profiles(
tool_type_id: str | None = None,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""List config profiles for the current user."""
query = select(ConfigProfile).where(ConfigProfile.user_id == user_id)
# If tool_type_id is provided, filter to compatible profiles
# For now, all profiles are considered compatible with all tool types
# since there's no explicit compatibility matrix. Future enhancement:
# could filter by profile tags or mount path patterns.
if tool_type_id:
# Validate the tool type exists
tool_type = await session.get(ToolType, uuid.UUID(tool_type_id))
if tool_type is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="tool type not found",
)
# All profiles are compatible; just return user's profiles
pass
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found")
result = await session.execute(query.order_by(ConfigProfile.name))
profiles = result.scalars().all()
@@ -153,19 +67,12 @@ async def list_config_profiles(
}
@router.post(
"",
summary="Create config profile",
description="Create a new config profile.",
status_code=status.HTTP_201_CREATED,
)
@router.post("", status_code=status.HTTP_201_CREATED, summary="Create config profile")
async def create_config_profile(
data: ConfigProfileCreate,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Create a config profile."""
# Check for duplicate name
existing = await session.scalar(
select(ConfigProfile).where(
ConfigProfile.user_id == user_id,
@@ -178,11 +85,7 @@ async def create_config_profile(
detail=f"config profile with name '{data.name}' already exists",
)
profile = ConfigProfile(
user_id=user_id,
name=data.name,
description=data.description,
)
profile = ConfigProfile(user_id=user_id, name=data.name, description=data.description)
session.add(profile)
await session.commit()
await session.refresh(profile)
@@ -197,118 +100,68 @@ async def create_config_profile(
}
@router.get(
"/defaults",
summary="Get default profiles",
description="Get the current user's default profile assignments per tool type.",
)
@router.get("/defaults", summary="Get default profiles")
async def get_default_profiles(
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Get default profiles for the current user."""
result = await session.execute(
select(UserConfig).where(UserConfig.user_id == user_id)
)
result = await session.execute(select(UserConfig).where(UserConfig.user_id == user_id))
user_config = result.scalar_one_or_none()
if user_config is None:
return {"default_profiles": {}}
return {"default_profiles": user_config.default_profiles}
return {"default_profiles": user_config.default_profiles if user_config else {}}
@router.put(
"/defaults",
summary="Set default profiles",
description="Set the current user's default profile assignments per tool type.",
)
@router.put("/defaults", summary="Set default profiles")
async def set_default_profiles(
data: DefaultProfilesUpdate,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Set default profiles for the current user."""
result = await session.execute(
select(UserConfig).where(UserConfig.user_id == user_id)
)
result = await session.execute(select(UserConfig).where(UserConfig.user_id == user_id))
user_config = result.scalar_one_or_none()
if user_config is None:
user_config = UserConfig(user_id=user_id, config={})
session.add(user_config)
# Validate all profile IDs belong to the user
for tool_type_id, profile_id_str in data.default_profiles.items():
profile = await session.get(ConfigProfile, uuid.UUID(profile_id_str))
if profile is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"profile {profile_id_str} not found",
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"profile {profile_id_str} not found")
if profile.user_id != user_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"profile {profile_id_str} does not belong to user",
)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"profile {profile_id_str} does not belong to user")
# SQLAlchemy JSON doesn't track dict mutations, so we replace the whole dict
user_config.config = {**user_config.config, "default_profiles": data.default_profiles}
await session.commit()
await session.refresh(user_config)
return {"default_profiles": user_config.default_profiles}
@router.get(
"/defaults/{tool_type_id}",
summary="Get default profile for tool type",
description="Get the default profile ID for a specific tool type.",
)
@router.get("/defaults/{tool_type_id}", summary="Get default profile for tool type")
async def get_default_profile_for_tool_type(
tool_type_id: str,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Get default profile for a specific tool type."""
result = await session.execute(
select(UserConfig).where(UserConfig.user_id == user_id)
)
result = await session.execute(select(UserConfig).where(UserConfig.user_id == user_id))
user_config = result.scalar_one_or_none()
if user_config is None:
return {"tool_type_id": tool_type_id, "profile_id": None}
profile_id = user_config.default_profiles.get(tool_type_id)
profile_id = user_config.default_profiles.get(tool_type_id) if user_config else None
return {"tool_type_id": tool_type_id, "profile_id": profile_id}
@router.get(
"/{profile_id}",
summary="Get config profile",
description="Get a config profile with its includes and mounts.",
)
@router.get("/{profile_id}", summary="Get config profile")
async def get_config_profile(
profile_id: uuid.UUID,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Get a config profile with includes and mounts."""
profile = await session.get(
ConfigProfile,
profile_id,
options=[
selectinload(ConfigProfile.includes),
selectinload(ConfigProfile.mounts),
],
options=[selectinload(ConfigProfile.includes), selectinload(ConfigProfile.mounts)],
)
if profile is None or profile.user_id != user_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="config profile not found",
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config profile not found")
# Fetch included profile names
includes_data = []
for inc in profile.includes:
included_profile = await session.get(ConfigProfile, inc.included_profile_id)
@@ -348,22 +201,16 @@ async def get_config_profile(
}
@router.put(
"/{profile_id}",
summary="Update config profile",
description="Update an existing config profile.",
)
@router.put("/{profile_id}", summary="Update config profile")
async def update_config_profile(
profile_id: uuid.UUID,
data: ConfigProfileUpdate,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Update a config profile."""
profile = await _get_owned_profile(profile_id, user_id, session)
profile = await get_owned_profile(profile_id, user_id, session)
if data.name is not None:
# Check for duplicate name
existing = await session.scalar(
select(ConfigProfile).where(
ConfigProfile.user_id == user_id,
@@ -394,19 +241,13 @@ async def update_config_profile(
}
@router.delete(
"/{profile_id}",
summary="Delete config profile",
description="Delete a config profile and all its includes and mounts.",
status_code=status.HTTP_204_NO_CONTENT,
)
@router.delete("/{profile_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Delete config profile")
async def delete_config_profile(
profile_id: uuid.UUID,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> None:
"""Delete a config profile."""
profile = await _get_owned_profile(profile_id, user_id, session)
profile = await get_owned_profile(profile_id, user_id, session)
await session.delete(profile)
await session.commit()
@@ -415,19 +256,13 @@ async def delete_config_profile(
# Include management
# ---------------------------------------------------------------------------
@router.get(
"/{profile_id}/includes",
summary="List profile includes",
description="Get all includes for a config profile.",
)
@router.get("/{profile_id}/includes", summary="List profile includes")
async def list_profile_includes(
profile_id: uuid.UUID,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""List includes for a config profile."""
await _get_owned_profile(profile_id, user_id, session)
await get_owned_profile(profile_id, user_id, session)
result = await session.execute(
select(ConfigInclude)
.where(ConfigInclude.profile_id == profile_id)
@@ -451,44 +286,25 @@ async def list_profile_includes(
return {"includes": includes_data}
@router.post(
"/{profile_id}/includes",
summary="Add profile include",
description="Add an include to a config profile.",
status_code=status.HTTP_201_CREATED,
)
@router.post("/{profile_id}/includes", status_code=status.HTTP_201_CREATED, summary="Add profile include")
async def add_profile_include(
profile_id: uuid.UUID,
data: ConfigIncludeCreate,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Add an include to a config profile."""
profile = await _get_owned_profile(profile_id, user_id, session)
profile = await get_owned_profile(profile_id, user_id, session)
included_profile_id = uuid.UUID(data.included_profile_id)
# Cannot include self
if included_profile_id == profile_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="a profile cannot include itself",
)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="a profile cannot include itself")
# Verify the included profile exists and belongs to the user
included_profile = await session.get(ConfigProfile, included_profile_id)
if included_profile is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="included profile not found",
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="included profile not found")
if included_profile.user_id != user_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="included profile does not belong to user",
)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="included profile does not belong to user")
# Check for duplicate include
existing = await session.scalar(
select(ConfigInclude).where(
ConfigInclude.profile_id == profile_id,
@@ -496,13 +312,9 @@ async def add_profile_include(
)
)
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="this include already exists",
)
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="this include already exists")
# Validate no cycles
await _validate_includes_no_cycle(session, profile_id, included_profile_id)
await validate_includes_no_cycle(session, profile_id, included_profile_id)
include = ConfigInclude(
profile_id=profile_id,
@@ -524,11 +336,7 @@ async def add_profile_include(
}
@router.put(
"/{profile_id}/includes/{include_id}",
summary="Update profile include",
description="Update the order index of a profile include.",
)
@router.put("/{profile_id}/includes/{include_id}", summary="Update profile include")
async def update_profile_include(
profile_id: uuid.UUID,
include_id: uuid.UUID,
@@ -536,15 +344,10 @@ async def update_profile_include(
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Update a profile include."""
await _get_owned_profile(profile_id, user_id, session)
await get_owned_profile(profile_id, user_id, session)
include = await session.get(ConfigInclude, include_id)
if include is None or include.profile_id != profile_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="include not found",
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="include not found")
include.order_index = data.order_index
await session.commit()
@@ -562,28 +365,17 @@ async def update_profile_include(
}
@router.delete(
"/{profile_id}/includes/{include_id}",
summary="Remove profile include",
description="Remove an include from a config profile.",
status_code=status.HTTP_204_NO_CONTENT,
)
@router.delete("/{profile_id}/includes/{include_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Remove profile include")
async def remove_profile_include(
profile_id: uuid.UUID,
include_id: uuid.UUID,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> None:
"""Remove an include from a config profile."""
await _get_owned_profile(profile_id, user_id, session)
await get_owned_profile(profile_id, user_id, session)
include = await session.get(ConfigInclude, include_id)
if include is None or include.profile_id != profile_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="include not found",
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="include not found")
await session.delete(include)
await session.commit()
@@ -592,19 +384,13 @@ async def remove_profile_include(
# Mount management
# ---------------------------------------------------------------------------
@router.get(
"/{profile_id}/mounts",
summary="List profile mounts",
description="Get all mounts for a config profile.",
)
@router.get("/{profile_id}/mounts", summary="List profile mounts")
async def list_profile_mounts(
profile_id: uuid.UUID,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""List mounts for a config profile."""
await _get_owned_profile(profile_id, user_id, session)
await get_owned_profile(profile_id, user_id, session)
result = await session.execute(
select(ConfigMount)
.where(ConfigMount.profile_id == profile_id)
@@ -629,22 +415,14 @@ async def list_profile_mounts(
}
@router.post(
"/{profile_id}/mounts",
summary="Add profile mount",
description="Add a mount to a config profile.",
status_code=status.HTTP_201_CREATED,
)
@router.post("/{profile_id}/mounts", status_code=status.HTTP_201_CREATED, summary="Add profile mount")
async def add_profile_mount(
profile_id: uuid.UUID,
data: ConfigMountCreate,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Add a mount to a config profile."""
profile = await _get_owned_profile(profile_id, user_id, session)
# Check for duplicate target_path
profile = await get_owned_profile(profile_id, user_id, session)
existing = await session.scalar(
select(ConfigMount).where(
ConfigMount.profile_id == profile_id,
@@ -680,11 +458,7 @@ async def add_profile_mount(
}
@router.put(
"/{profile_id}/mounts/{mount_id}",
summary="Update profile mount",
description="Update a mount in a config profile.",
)
@router.put("/{profile_id}/mounts/{mount_id}", summary="Update profile mount")
async def update_profile_mount(
profile_id: uuid.UUID,
mount_id: uuid.UUID,
@@ -692,18 +466,12 @@ async def update_profile_mount(
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Update a profile mount."""
await _get_owned_profile(profile_id, user_id, session)
await get_owned_profile(profile_id, user_id, session)
mount = await session.get(ConfigMount, mount_id)
if mount is None or mount.profile_id != profile_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="mount not found",
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="mount not found")
if data.target_path is not None:
# Check for duplicate target_path
existing = await session.scalar(
select(ConfigMount).where(
ConfigMount.profile_id == profile_id,
@@ -720,7 +488,6 @@ async def update_profile_mount(
if data.files is not None:
mount.files = data.files
if data.order_index is not None:
mount.order_index = data.order_index
@@ -739,27 +506,16 @@ async def update_profile_mount(
}
@router.delete(
"/{profile_id}/mounts/{mount_id}",
summary="Remove profile mount",
description="Remove a mount from a config profile.",
status_code=status.HTTP_204_NO_CONTENT,
)
@router.delete("/{profile_id}/mounts/{mount_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Remove profile mount")
async def remove_profile_mount(
profile_id: uuid.UUID,
mount_id: uuid.UUID,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> None:
"""Remove a mount from a config profile."""
await _get_owned_profile(profile_id, user_id, session)
await get_owned_profile(profile_id, user_id, session)
mount = await session.get(ConfigMount, mount_id)
if mount is None or mount.profile_id != profile_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="mount not found",
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="mount not found")
await session.delete(mount)
await session.commit()
File diff suppressed because it is too large Load Diff
+81
View File
@@ -0,0 +1,81 @@
"""Config profile business logic."""
import logging
import uuid
from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.models.config_include import ConfigInclude
from src.models.config_mount import ConfigMount
from src.models.config_profile import ConfigProfile
from src.models.tool_type import ToolType
from src.models.user_config import UserConfig
logger = logging.getLogger(__name__)
MAX_INCLUDES_DEPTH = 10
async def get_owned_profile(
profile_id: uuid.UUID,
user_id: uuid.UUID,
session: AsyncSession,
) -> ConfigProfile:
"""Fetch a config profile and verify ownership."""
profile = await session.get(ConfigProfile, profile_id)
if profile is None or profile.user_id != user_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="config profile not found",
)
return profile
async def _detect_cycle(
session: AsyncSession,
profile_id: uuid.UUID,
visited: set[uuid.UUID] | None = None,
depth: int = 0,
) -> bool:
"""Detect cycles in profile includes using DFS.
Returns True if a cycle is detected.
"""
if depth > MAX_INCLUDES_DEPTH:
return True
if visited is None:
visited = set()
if profile_id in visited:
return True
visited.add(profile_id)
result = await session.execute(
select(ConfigInclude.included_profile_id).where(
ConfigInclude.profile_id == profile_id
)
)
included_ids = result.scalars().all()
for included_id in included_ids:
if await _detect_cycle(session, included_id, visited.copy(), depth + 1):
return True
return False
async def validate_includes_no_cycle(
session: AsyncSession,
profile_id: uuid.UUID,
new_included_id: uuid.UUID | None = None,
) -> None:
"""Validate that adding an include wouldn't create a cycle."""
if new_included_id and await _detect_cycle(session, new_included_id, {profile_id}):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="adding this include would create a circular reference",
)
+1
View File
@@ -0,0 +1 @@
"""Git services package."""
+196
View File
@@ -0,0 +1,196 @@
"""Git control operations with repo validation."""
import logging
import os
import uuid
from fastapi import HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from src.models.git_repository import GitRepository
from src.models.user import User
from src.schemas.git_repository import (
BranchCreateRequest,
CheckoutRequest,
CommitRequest,
FetchResponse,
MergeRequest,
MergeResponse,
PullResponse,
PushResponse,
StatusResponse,
)
from src.services.git.repository import ensure_repo_on_disk, get_repo_and_validate
from src.utils.git_control import (
checkout_branch,
commit_changes,
create_branch,
delete_branch,
fetch,
get_status,
merge,
pull,
push,
)
logger = logging.getLogger(__name__)
async def get_status_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
) -> StatusResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
result = get_status(repo.path)
return StatusResponse(
branch=result.branch,
modified=result.modified,
added=result.added,
deleted=result.deleted,
untracked=result.untracked,
renamed=result.renamed,
ahead=result.ahead,
behind=result.behind,
)
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def create_branch_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
data: BranchCreateRequest,
) -> dict:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
create_branch(repo.path, data.name, data.base_branch)
return {"message": f"Branch '{data.name}' created", "branch": data.name}
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def delete_branch_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
branch_name: str,
force: bool = False,
) -> dict:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
delete_branch(repo.path, branch_name, force)
return {"message": f"Branch '{branch_name}' deleted"}
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def checkout_branch_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
data: CheckoutRequest,
) -> dict:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
checkout_branch(repo.path, data.branch)
return {"message": f"Checked out branch '{data.branch}'", "branch": data.branch}
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def commit_changes_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
data: CommitRequest,
user: User,
) -> dict:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
author_name = user.name or "Unknown"
author_email = user.email or "unknown@example.com"
try:
commit_hash = commit_changes(
repo_path=repo.path,
message=data.message,
author_name=author_name,
author_email=author_email,
files=data.files,
)
return {"commit_hash": commit_hash, "message": data.message}
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def fetch_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
) -> FetchResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
fetch(repo.path)
return FetchResponse(message="Fetched from remote")
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def pull_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
branch: str | None = None,
) -> PullResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
pull(repo.path, branch)
return PullResponse(message="Pulled from remote")
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def push_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
branch: str | None = None,
) -> PushResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
push(repo.path, branch)
return PushResponse(message="Pushed to remote")
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def merge_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
data: MergeRequest,
) -> MergeResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
commit_hash = merge(
repo_path=repo.path,
source_branch=data.source_branch,
target_branch=data.target_branch,
message=data.message,
)
return MergeResponse(
commit_hash=commit_hash,
message=data.message or f"Merge {data.source_branch}",
)
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+150
View File
@@ -0,0 +1,150 @@
"""Git file operations with repo validation."""
import logging
import uuid
from fastapi import HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from src.models.git_repository import GitRepository
from src.models.user import User
from src.schemas.git_repository import (
FileContentResponse,
FileListResponse,
FileUpdateRequest,
FileUpdateResponse,
)
from src.services.git.repository import ensure_repo_on_disk, get_repo_and_validate
from src.utils.git_files import (
commit_file,
get_file_content,
list_branches,
list_tree,
)
logger = logging.getLogger(__name__)
async def list_files(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
branch: str = "main",
path: str = "",
) -> FileListResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
entries = list_tree(repo.path, branch=branch, path=path)
return FileListResponse(
path=path,
branch=branch,
entries=[
{
"name": e.name,
"type": e.type,
"path": e.path,
"size": e.size,
"mode": e.mode,
"last_commit": e.last_commit,
}
for e in entries
],
)
except RuntimeError as e:
logger.error(
"Failed to list files for repo %s (path=%s, branch=%s): %s",
repo_id,
path,
branch,
str(e),
exc_info=True,
)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def get_file(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
branch: str,
path: str,
) -> FileContentResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
file_content = get_file_content(repo.path, branch=branch, path=path)
return FileContentResponse(
path=file_content.path,
branch=file_content.branch,
content=file_content.content,
size=file_content.size,
encoding=file_content.encoding,
language=file_content.language,
is_binary=file_content.is_binary,
last_commit=file_content.last_commit,
)
except FileNotFoundError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="file not found")
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def update_file(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
data: FileUpdateRequest,
user: User,
) -> FileUpdateResponse:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
author_name = user.name or "Unknown"
author_email = user.email or "unknown@example.com"
try:
commit_hash = commit_file(
repo_path=repo.path,
branch=data.branch,
path=data.path,
content=data.content,
commit_message=data.commit_message,
author_name=author_name,
author_email=author_email,
)
return FileUpdateResponse(
commit_hash=commit_hash,
message=data.commit_message,
branch=data.branch,
)
except RuntimeError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def list_branches_with_validation(
session: AsyncSession,
project_id: uuid.UUID,
repo_id: uuid.UUID,
) -> dict:
repo = await get_repo_and_validate(session, repo_id, project_id)
ensure_repo_on_disk(repo)
try:
branches, default_branch = list_branches(repo.path)
return {
"branches": [
{
"name": b.name,
"is_default": b.is_default,
"last_commit": b.last_commit,
}
for b in branches
],
"default_branch": default_branch,
}
except RuntimeError as e:
logger.error(
"Failed to list branches for repo %s: %s",
repo_id,
str(e),
exc_info=True,
)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+211
View File
@@ -0,0 +1,211 @@
"""Repository lifecycle and path helpers."""
import logging
import os
import shutil
import subprocess
import uuid
from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.config import Settings
from src.models.git_repository import GitRepository
from src.models.project import Project
from src.models.user import User
from src.schemas.git_repository import GitRepositoryCreate
from src.utils.git_url_parser import parse_git_url
logger = logging.getLogger(__name__)
def _get_repo_path(user_id: uuid.UUID, project_id: uuid.UUID, name: str) -> str:
"""Generate the filesystem path for a repository."""
base = Settings().repo_base_path or "/data/repos"
return os.path.join(base, str(user_id), str(project_id), f"{name}.git")
def _build_provider_clone_url(owner: str, repo: str) -> str:
"""Build the SSH clone URL for the fixed git provider."""
return f"git@git.commumedia.org:{owner}/{repo}.git"
def _preflight_remote_repository(remote_url: str) -> None:
"""Verify a remote repository is reachable before cloning."""
try:
result = subprocess.run(
["git", "ls-remote", remote_url],
capture_output=True,
text=True,
timeout=60,
)
except subprocess.TimeoutExpired:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="remote repository check timed out")
except FileNotFoundError:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="git command not found")
if result.returncode != 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="repository not found or inaccessible",
)
def _clone_working_repository(remote_url: str, repo_path: str) -> None:
try:
result = subprocess.run(
["git", "clone", remote_url, repo_path],
capture_output=True,
text=True,
timeout=300,
)
except subprocess.TimeoutExpired:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="clone operation timed out")
except FileNotFoundError:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="git command not found")
if result.returncode != 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"failed to clone repository: {result.stderr}",
)
def _init_working_repository(repo_path: str) -> None:
try:
result = subprocess.run(
["git", "init", "-b", "main", repo_path],
capture_output=True,
text=True,
)
except FileNotFoundError:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="git command not found")
if result.returncode == 0:
return
fallback = subprocess.run(
["git", "init", repo_path],
capture_output=True,
text=True,
)
if fallback.returncode != 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"failed to initialize repository: {fallback.stderr}",
)
ref_result = subprocess.run(
["git", "-C", repo_path, "symbolic-ref", "HEAD", "refs/heads/main"],
capture_output=True,
text=True,
)
if ref_result.returncode != 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"failed to set initial branch: {ref_result.stderr}",
)
async def get_repo_and_validate(
session: AsyncSession,
repo_id: uuid.UUID,
project_id: uuid.UUID,
) -> GitRepository:
"""Fetch a repository and validate ownership + disk presence."""
repo = await session.get(GitRepository, repo_id)
if repo is None or repo.project_id != project_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="repository not found")
return repo
def ensure_repo_on_disk(repo: GitRepository) -> None:
"""Raise 404 if the repository is not present on disk."""
if not os.path.exists(repo.path):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="repository not found on disk")
async def create_repository(
session: AsyncSession,
project_id: uuid.UUID,
data: GitRepositoryCreate,
user: User,
) -> GitRepository:
"""Create a new git repository (clone or init)."""
# Check for duplicate name
existing = await session.execute(
select(GitRepository).where(
GitRepository.project_id == project_id,
GitRepository.name == data.name,
)
)
if existing.scalar_one_or_none():
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="repository name already exists")
# Validate and potentially correct the URL
remote_url = data.remote_url
if remote_url and not data.force_original_url:
parse_result = parse_git_url(remote_url)
if parse_result["needs_parsing"] and parse_result["base_url"]:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail={
"message": "The provided URL appears to be a browser URL, not a git clone URL",
"suggested_url": parse_result["base_url"],
"original_url": remote_url,
"error_code": "URL_NEEDS_PARSING",
},
)
if parse_result["base_url"]:
remote_url = parse_result["base_url"]
if remote_url:
_preflight_remote_repository(remote_url)
repo_path = _get_repo_path(user.id, project_id, data.name)
os.makedirs(os.path.dirname(repo_path), exist_ok=True)
if remote_url:
_clone_working_repository(remote_url, repo_path)
else:
_init_working_repository(repo_path)
repo = GitRepository(
name=data.name,
path=repo_path,
project_id=project_id,
owner_id=user.id,
is_mirror=False,
remote_url=remote_url,
)
session.add(repo)
await session.commit()
await session.refresh(repo)
return repo
async def delete_repository(
session: AsyncSession,
repo_id: uuid.UUID,
project_id: uuid.UUID,
) -> None:
"""Delete a repository from DB and disk."""
repo = await get_repo_and_validate(session, repo_id, project_id)
if os.path.exists(repo.path):
shutil.rmtree(repo.path)
await session.delete(repo)
await session.commit()
async def list_repositories(
session: AsyncSession,
project_id: uuid.UUID,
) -> list[GitRepository]:
"""List all repositories in a project."""
result = await session.execute(
select(GitRepository).where(GitRepository.project_id == project_id)
)
return list(result.scalars().all())