Repository navigation
feat(wework): add git workspace project creation #1297
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,7 +8,8 @@ | |
| Projects are containers for organizing tasks. Each task can belong to one project. | ||
| """ | ||
|
|
||
| from typing import Optional | ||
| import posixpath | ||
| from typing import Any, Optional | ||
|
|
||
| from fastapi import HTTPException | ||
| from sqlalchemy import func | ||
|
|
@@ -18,6 +19,8 @@ | |
| from app.models.project import Project | ||
| from app.models.task import TaskResource | ||
| from app.schemas.project import ( | ||
| GitWorkspaceProjectCreate, | ||
| GitWorkspaceProjectResponse, | ||
| ProjectConfig, | ||
| ProjectConversationCreate, | ||
| ProjectConversationResponse, | ||
|
|
@@ -30,6 +33,11 @@ | |
| ) | ||
| from app.schemas.task import TaskCreate | ||
| from app.services.adapters.task_kinds import task_kinds_service | ||
| from app.services.device.command_service import ( | ||
| execute_configured_device_command, | ||
| ) | ||
|
|
||
| GIT_CLONE_TIMEOUT_SECONDS = 600 | ||
|
|
||
|
|
||
| def create_project( | ||
|
|
@@ -81,6 +89,196 @@ def create_project( | |
| return response | ||
|
|
||
|
|
||
| async def create_git_workspace_project( | ||
| db: Session, | ||
| project_data: GitWorkspaceProjectCreate, | ||
| user_id: int, | ||
| ) -> GitWorkspaceProjectResponse: | ||
| """Create a Git-backed workspace project and clone its checkout.""" | ||
|
Comment on lines
+92
to
+97
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win Add required tracing instrumentation to new Git workspace flow functions. The newly added async service entry points are missing Example pattern+from app.observability.tracing import trace_async, add_span_event, set_span_attribute
...
+@trace_async
async def create_git_workspace_project(...):
+ set_span_attribute('project.source', 'git')
+ add_span_event('project.create_git_workspace.start')
...
+@trace_async
async def _prepare_git_checkout(...):
+ set_span_attribute('device.id', device_id)
+ add_span_event('project.git_checkout.prepare')
...As per coding guidelines: Also applies to: 156-166 🤖 Prompt for AI Agents |
||
|
|
||
| repo_name = _default_git_project_name(project_data.git.repo, project_data.git.url) | ||
| config = ProjectConfig.model_validate( | ||
| { | ||
| "mode": "workspace", | ||
| "execution": { | ||
| "targetType": "local", | ||
| "deviceId": project_data.device_id, | ||
| }, | ||
| "workspace": {"source": "git"}, | ||
| "git": project_data.git.model_dump(), | ||
| } | ||
| ) | ||
| if not config.workspace or not config.workspace.checkoutPath: | ||
| raise HTTPException( | ||
| status_code=400, | ||
| detail="Git workspace checkout path could not be resolved", | ||
| ) | ||
|
|
||
| project = create_project( | ||
| db=db, | ||
| project_data=ProjectCreate( | ||
| name=project_data.name or repo_name, | ||
| description=project_data.description, | ||
| color=project_data.color, | ||
| client_origin=project_data.client_origin, | ||
| config=config, | ||
| ), | ||
| user_id=user_id, | ||
| ) | ||
|
|
||
| try: | ||
| reused_checkout = await _prepare_git_checkout( | ||
| db=db, | ||
| user_id=user_id, | ||
| device_id=project_data.device_id, | ||
| git_url=project_data.git.url, | ||
| branch=project_data.git.branch, | ||
| checkout_path=config.workspace.checkoutPath, | ||
| ) | ||
| except Exception: | ||
| _deactivate_project(db, project.id, user_id, project_data.client_origin) | ||
| raise | ||
|
|
||
| return GitWorkspaceProjectResponse( | ||
| project=project, | ||
| checkout_path=config.workspace.checkoutPath, | ||
| reused_existing_checkout=reused_checkout, | ||
| ) | ||
|
|
||
|
|
||
| def _default_git_project_name(repo: Optional[str], git_url: str) -> str: | ||
| """Return a display name for a Git workspace project.""" | ||
|
|
||
| source = repo or git_url.rstrip("/").split("/")[-1] | ||
| return source.rstrip("/").removesuffix(".git").split("/")[-1] or "repository" | ||
|
|
||
|
|
||
| async def _prepare_git_checkout( | ||
| *, | ||
| db: Session, | ||
| user_id: int, | ||
| device_id: str, | ||
| git_url: str, | ||
| branch: Optional[str], | ||
| checkout_path: str, | ||
| ) -> bool: | ||
| """Clone the Git checkout on the selected local device.""" | ||
|
|
||
| root_result = await execute_configured_device_command( | ||
| db=db, | ||
| user_id=user_id, | ||
| device_id=device_id, | ||
| command_key="project_workspace_root", | ||
| ) | ||
| workspace_root = str(root_result.get("stdout", "")).strip() | ||
| if not workspace_root: | ||
| raise HTTPException(status_code=400, detail="Project workspace root is empty") | ||
|
|
||
| root_mkdir_result = await execute_configured_device_command( | ||
| db=db, | ||
| user_id=user_id, | ||
| device_id=device_id, | ||
| command_key="mkdir_p", | ||
| args=[workspace_root], | ||
| ) | ||
| _raise_for_failed_command( | ||
| root_mkdir_result, | ||
| "Failed to create project workspace root", | ||
| ) | ||
|
|
||
| target_path = _join_device_path(workspace_root, checkout_path) | ||
| exists_result = await execute_configured_device_command( | ||
| db=db, | ||
| user_id=user_id, | ||
| device_id=device_id, | ||
| command_key="path_exists", | ||
| path=workspace_root, | ||
| args=[checkout_path], | ||
| timeout_seconds=30, | ||
| ) | ||
| if _command_succeeded(exists_result): | ||
| raise _target_path_exists_error(target_path) | ||
|
Comment on lines
+190
to
+200
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Handle On Line 199, any non-zero result is treated as “not exists”. If the check command itself fails, clone still proceeds and masks the root cause. Suggested fix exists_result = await execute_configured_device_command(
db=db,
user_id=user_id,
device_id=device_id,
command_key="path_exists",
path=workspace_root,
args=[checkout_path],
timeout_seconds=30,
)
+ exists_exit_code = exists_result.get("exit_code")
if _command_succeeded(exists_result):
raise _target_path_exists_error(target_path)
+ if exists_exit_code != 1:
+ _raise_for_failed_command(
+ exists_result,
+ "Failed to check whether target project directory exists",
+ )🤖 Prompt for AI Agents |
||
|
|
||
| parent_path = posixpath.dirname(checkout_path) | ||
| if parent_path and parent_path != ".": | ||
| mkdir_result = await execute_configured_device_command( | ||
| db=db, | ||
| user_id=user_id, | ||
| device_id=device_id, | ||
| command_key="mkdir_p", | ||
| path=workspace_root, | ||
| args=[parent_path], | ||
| ) | ||
| _raise_for_failed_command(mkdir_result, "Failed to create project directory") | ||
|
|
||
| clone_args = _build_git_clone_args(git_url, branch, checkout_path) | ||
| clone_result = await execute_configured_device_command( | ||
| db=db, | ||
| user_id=user_id, | ||
| device_id=device_id, | ||
| command_key="git_clone", | ||
| path=workspace_root, | ||
| args=clone_args, | ||
| timeout_seconds=GIT_CLONE_TIMEOUT_SECONDS, | ||
| max_output_bytes=5 * 1024 * 1024, | ||
| ) | ||
| _raise_for_failed_command(clone_result, "Failed to clone Git repository") | ||
| return False | ||
|
|
||
|
|
||
| def _build_git_clone_args( | ||
| git_url: str, | ||
| branch: Optional[str], | ||
| checkout_path: str, | ||
| ) -> list[str]: | ||
| args: list[str] = [] | ||
| if branch and branch.strip(): | ||
| args.extend(["--branch", branch.strip(), "--single-branch"]) | ||
| args.extend([git_url, checkout_path]) | ||
| return args | ||
|
|
||
|
|
||
| def _join_device_path(root: str, relative_path: str) -> str: | ||
| return f"{root.rstrip('/')}/{relative_path.strip('/')}" | ||
|
|
||
|
|
||
| def _command_succeeded(result: dict[str, Any]) -> bool: | ||
| return bool(result.get("success")) and result.get("exit_code") == 0 | ||
|
|
||
|
|
||
| def _raise_for_failed_command(result: dict[str, Any], message: str) -> None: | ||
| if _command_succeeded(result): | ||
| return | ||
| detail = str(result.get("stderr") or result.get("error") or message) | ||
| raise HTTPException(status_code=400, detail=detail) | ||
|
|
||
|
|
||
| def _target_path_exists_error(target_path: str) -> HTTPException: | ||
| return HTTPException( | ||
| status_code=409, | ||
| detail=f"Target project directory already exists: {target_path}", | ||
| ) | ||
|
|
||
|
|
||
| def _deactivate_project( | ||
| db: Session, | ||
| project_id: int, | ||
| user_id: int, | ||
| client_origin: Optional[str], | ||
| ) -> None: | ||
| query = db.query(Project).filter( | ||
| Project.id == project_id, | ||
| Project.user_id == user_id, | ||
| Project.is_active == True, | ||
| ) | ||
| if client_origin: | ||
| query = query.filter(Project.client_origin == client_origin) | ||
| project = query.first() | ||
| if project: | ||
| project.is_active = False | ||
| db.commit() | ||
|
|
||
|
|
||
| def get_project( | ||
| db: Session, project_id: int, user_id: int, client_origin: Optional[str] = None | ||
| ) -> Optional[ProjectWithTasksResponse]: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Instrument the new async endpoint with required tracing decorators/events.
create_git_workspace_project_endpointis newly added and should be wrapped with@trace_asyncand span metadata for request-level observability.As per coding guidelines:
Use OpenTelemetry tracing decorators:@trace_asyncor@trace_syncfor entire functions, and add_span_event() or set_span_attribute() for adding details to spans.🧰 Tools
🪛 Ruff (0.15.15)
[warning] 100-100: Do not perform function call
Dependsin argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable(B008)
[warning] 101-101: Do not perform function call
Dependsin argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable(B008)
🤖 Prompt for AI Agents