mirror of
https://github.com/ZTatman/myst.git
synced 2026-11-22 21:07:57 +00:00
Compare commits
No commits in common. "7d680d593013a873c2c98abd16cd288a830e90e3" and "394e68abeb18bf0a658f2e19889b3418f96e8e38" have entirely different histories.
7d680d5930
...
394e68abeb
6 changed files with 115 additions and 345 deletions
42
agents.md
42
agents.md
|
|
@ -157,45 +157,3 @@ This file is the single source of truth for codebase obstacles, oddities, and th
|
||||||
**Obstacle:** `pnpm run` spawns node as a child, so `$!` captured pnpm's PID rather than the Tailwind process. The `trap "kill $TW_PID"` cleanup killed the wrapper and left the node watcher running, accumulating orphans across dev-server restarts.
|
**Obstacle:** `pnpm run` spawns node as a child, so `$!` captured pnpm's PID rather than the Tailwind process. The `trap "kill $TW_PID"` cleanup killed the wrapper and left the node watcher running, accumulating orphans across dev-server restarts.
|
||||||
**Solution/Workaround:** Enable job control with `set -m` before backgrounding so the job becomes a process-group leader, then kill the group: `kill -- -$TW_PID`.
|
**Solution/Workaround:** Enable job control with `set -m` before backgrounding so the job becomes a process-group leader, then kill the group: `kill -- -$TW_PID`.
|
||||||
**Preference:** When backgrounding a package-manager wrapper, always kill the process group rather than the wrapper PID.
|
**Preference:** When backgrounding a package-manager wrapper, always kill the process group rather than the wrapper PID.
|
||||||
|
|
||||||
### Owned repository pagination needs an owner-specific endpoint
|
|
||||||
**Area:** web/app/clients/forgejo.py, web/app/routers/repositories.py, web/app/main.py
|
|
||||||
**Obstacle:** Forgejo's `/user/repos` handler does not read `type=owner`; filtering accessible repositories after pagination can produce sparse pages and misleading totals.
|
|
||||||
**Solution/Workaround:** Use authenticated `/users/{username}/repos` for owned listings and preserve `x-total-count`. Dashboard and JSON listings consume the returned page without filtering it again.
|
|
||||||
**Preference:** Filter upstream before paginating; keep the JSON list response shape unchanged. User approved removing redundant consumer-side owner checks because silently dropping results could make page contents disagree with pagination metadata.
|
|
||||||
|
|
||||||
### Repository failures must not replace the dashboard
|
|
||||||
**Area:** web/app/main.py, web/app/templates/dashboard.html
|
|
||||||
**Obstacle:** Fetch failures and token/identity dependencies could abort the whole dashboard, including its no-PAT state.
|
|
||||||
**Solution/Workaround:** Resolve repository credentials and identity only when a PAT exists, inside the dashboard's repository error boundary. Render expected 403/502/503 failures inline and hide pagination on error; leave authentication outside that boundary. Use one dashboard page-size constant.
|
|
||||||
**Preference:** Keep the dashboard usable without masking unexpected application errors.
|
|
||||||
|
|
||||||
### Declarative base lint error remains deferred
|
|
||||||
**Area:** web/app/database.py
|
|
||||||
**Obstacle:** Existing `Base.type_annotation_map` triggers Ruff RUF012 for an unannotated mutable class attribute.
|
|
||||||
**Solution/Workaround:** Deferred outside the repository-table cleanup. Annotate the mapping with `ClassVar` when addressing this lint issue.
|
|
||||||
**Preference:** Do not mix unrelated database cleanup into repository UI changes.
|
|
||||||
|
|
||||||
### Create-share-link button points to an unfinished route
|
|
||||||
**Area:** web/app/templates/dashboard.html, web/app/routers/links.py
|
|
||||||
**Obstacle:** The existing button points to `/links/create`, which has no handler; `POST /links/` is still a 501 stub and the public viewer is not built.
|
|
||||||
**Solution/Workaround:** Deferred to the share-link implementation. The user intends to write link creation themselves.
|
|
||||||
**Preference:** Keep repository-table cleanup separate from implementing the share-link flow.
|
|
||||||
|
|
||||||
### Table divider utility has no matching theme token
|
|
||||||
**Area:** web/app/templates/dashboard.html, web/app/static/css/input.css
|
|
||||||
**Obstacle:** Both dashboard tables use `divide-border-subtle`, but no `--color-border-subtle` token exists. The repository table copied the existing share-links table styling.
|
|
||||||
**Solution/Workaround:** Replaced `divide-border-subtle` with the existing semantic `divide-border` utility in both dashboard tables, as approved by the user.
|
|
||||||
**Preference:** Reuse the existing border token rather than adding an appearance-specific token.
|
|
||||||
|
|
||||||
### Automated tests deferred while learning the feature
|
|
||||||
**Area:** web/tests/
|
|
||||||
**Obstacle:** The user wants to understand how tests work before adding them to this feature.
|
|
||||||
**Solution/Workaround:** Removed the newly added repository tests at the user's request. Defer adding automated tests until the user is ready; use manual verification in the meantime.
|
|
||||||
**Preference:** Explain testing before introducing test files; do not add them yet.
|
|
||||||
|
|
||||||
### Forgejo page-size caps can hide remaining repositories
|
|
||||||
**Area:** web/app/clients/forgejo.py, web/app/main.py
|
|
||||||
**Obstacle:** Calculating the next page from the requested limit stops pagination early when Forgejo's configured page-size cap is lower.
|
|
||||||
**Solution/Workaround:** Preserve the `next` relation from Forgejo's `Link` header as `RepoPage.has_next_page` and use it directly on the dashboard.
|
|
||||||
**Preference:** Use upstream pagination links rather than assuming the requested page size was honored.
|
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any, Literal
|
from typing import Any, Literal
|
||||||
from urllib.parse import quote
|
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from fastapi import HTTPException, status
|
from fastapi import HTTPException, status
|
||||||
|
|
@ -13,8 +11,6 @@ from app.models.app_settings import AppSettings
|
||||||
|
|
||||||
|
|
||||||
class Repo(BaseModel):
|
class Repo(BaseModel):
|
||||||
"""A repository returned by Forgejo."""
|
|
||||||
|
|
||||||
repo_name: str = Field(validation_alias="name")
|
repo_name: str = Field(validation_alias="name")
|
||||||
repo_full_name: str = Field(validation_alias="full_name")
|
repo_full_name: str = Field(validation_alias="full_name")
|
||||||
repo_owner: str = Field(validation_alias=AliasPath("owner", "username"))
|
repo_owner: str = Field(validation_alias=AliasPath("owner", "username"))
|
||||||
|
|
@ -35,13 +31,6 @@ class Repo(BaseModel):
|
||||||
return "private" if value else "public"
|
return "private" if value else "public"
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class RepoPage:
|
|
||||||
repos: list[Repo]
|
|
||||||
total_count: int | None
|
|
||||||
has_next_page: bool
|
|
||||||
|
|
||||||
|
|
||||||
class Commit(BaseModel):
|
class Commit(BaseModel):
|
||||||
"""A commit, normalized across Forgejo's two payload shapes.
|
"""A commit, normalized across Forgejo's two payload shapes.
|
||||||
|
|
||||||
|
|
@ -67,8 +56,6 @@ class Commit(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
class Branch(BaseModel):
|
class Branch(BaseModel):
|
||||||
"""A branch returned by Forgejo."""
|
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
protected: bool
|
protected: bool
|
||||||
commit: Commit
|
commit: Commit
|
||||||
|
|
@ -80,8 +67,7 @@ async def get_repos(
|
||||||
*,
|
*,
|
||||||
limit: int = 30,
|
limit: int = 30,
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
owner: str | None = None,
|
) -> list[Repo]:
|
||||||
) -> RepoPage:
|
|
||||||
"""Get the user's repositories from the Forgejo API.
|
"""Get the user's repositories from the Forgejo API.
|
||||||
|
|
||||||
Forgejo paginates this endpoint and caps `limit` at the instance's
|
Forgejo paginates this endpoint and caps `limit` at the instance's
|
||||||
|
|
@ -94,46 +80,18 @@ async def get_repos(
|
||||||
access_token: The Forgejo API token.
|
access_token: The Forgejo API token.
|
||||||
limit: The maximum number of repositories to return.
|
limit: The maximum number of repositories to return.
|
||||||
page: The page number to return.
|
page: The page number to return.
|
||||||
owner: Restrict results to repositories owned by this username.
|
|
||||||
Returns:
|
Returns:
|
||||||
The repositories and Forgejo's total-count pagination metadata.
|
A list of repositories.
|
||||||
"""
|
"""
|
||||||
params: dict[str, str | int] = {"limit": limit, "page": page}
|
|
||||||
endpoint = f"/users/{quote(owner, safe='')}/repos" if owner else "/user/repos"
|
repos = await get(
|
||||||
path = f"/api/v1{endpoint}?{httpx.QueryParams(params)}"
|
app_settings,
|
||||||
try:
|
f"/api/v1/user/repos?limit={limit}&page={page}",
|
||||||
async with httpx.AsyncClient(
|
access_token,
|
||||||
base_url=app_settings.forgejo_base_url, timeout=30.0
|
|
||||||
) as client:
|
|
||||||
response = await client.get(
|
|
||||||
path, headers={"Authorization": f"token {access_token}"}
|
|
||||||
)
|
|
||||||
except httpx.RequestError:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
||||||
detail="Cannot reach Forgejo. Check your connection settings.",
|
|
||||||
)
|
|
||||||
if response.status_code in {401, 403}:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
||||||
detail="Forgejo rejected your access token. Check its permissions or replace it in settings.",
|
|
||||||
)
|
|
||||||
if response.status_code != 200:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
||||||
detail=f"Forgejo could not load repositories ({response.status_code}). Try again later.",
|
|
||||||
)
|
|
||||||
repos = [Repo.model_validate(repo) for repo in response.json()]
|
|
||||||
total_count_header = response.headers.get("x-total-count")
|
|
||||||
try:
|
|
||||||
total_count = int(total_count_header) if total_count_header else None
|
|
||||||
except ValueError:
|
|
||||||
total_count = None
|
|
||||||
return RepoPage(
|
|
||||||
repos=repos,
|
|
||||||
total_count=total_count,
|
|
||||||
has_next_page="next" in response.links,
|
|
||||||
)
|
)
|
||||||
|
if not repos:
|
||||||
|
return []
|
||||||
|
return [Repo.model_validate(r) for r in repos]
|
||||||
|
|
||||||
|
|
||||||
async def get_branches(
|
async def get_branches(
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ from contextlib import asynccontextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import Depends, FastAPI, HTTPException, Query, Request
|
from fastapi import Depends, FastAPI, Request
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse
|
from fastapi.responses import HTMLResponse, JSONResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from sqlalchemy import func as sql_func
|
from sqlalchemy import func as sql_func
|
||||||
|
|
@ -15,14 +15,12 @@ from starlette.responses import Response
|
||||||
|
|
||||||
from app import models as _models # noqa: F401 - register ORM tables on metadata
|
from app import models as _models # noqa: F401 - register ORM tables on metadata
|
||||||
from app.auth.session import get_current_session, get_optional_session
|
from app.auth.session import get_current_session, get_optional_session
|
||||||
from app.clients import forgejo
|
|
||||||
from app.database import Base
|
from app.database import Base
|
||||||
from app.deps import get_db
|
|
||||||
from app.middleware import SetupRequiredMiddleware
|
from app.middleware import SetupRequiredMiddleware
|
||||||
from app.models.app_settings import AppSettings
|
from app.models.app_settings import AppSettings
|
||||||
from app.models.session import Session as UserBrowserSession
|
from app.models.session import Session as UserBrowserSession
|
||||||
from app.routers import auth, links, repositories, settings, setup
|
from app.routers import auth, links, settings, setup
|
||||||
from app.settings import get_app_settings, get_settings
|
from app.settings import get_settings
|
||||||
from app.templating import templates
|
from app.templating import templates
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -90,7 +88,6 @@ app.mount(
|
||||||
# Routers
|
# Routers
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
app.include_router(links.router)
|
app.include_router(links.router)
|
||||||
app.include_router(repositories.router)
|
|
||||||
app.include_router(settings.router)
|
app.include_router(settings.router)
|
||||||
app.include_router(setup.router)
|
app.include_router(setup.router)
|
||||||
|
|
||||||
|
|
@ -139,51 +136,15 @@ async def root(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
REPOS_PER_PAGE = 30
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/dashboard", response_class=HTMLResponse)
|
@app.get("/dashboard", response_class=HTMLResponse)
|
||||||
async def dashboard(
|
async def dashboard(
|
||||||
request: Request,
|
request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)]
|
||||||
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
|
||||||
db: Annotated[AsyncSession, Depends(get_db)],
|
|
||||||
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
|
||||||
page: Annotated[int, Query(ge=1)] = 1,
|
|
||||||
) -> Response:
|
) -> Response:
|
||||||
repos = []
|
|
||||||
total_count = 0
|
|
||||||
has_next_page = False
|
|
||||||
repo_error = None
|
|
||||||
if sess.user.has_pat:
|
|
||||||
try:
|
|
||||||
access_token = await repositories.get_forgejo_token(sess)
|
|
||||||
owner = await repositories.get_forgejo_owner(sess, db)
|
|
||||||
repo_page = await forgejo.get_repos(
|
|
||||||
app_settings,
|
|
||||||
access_token,
|
|
||||||
limit=REPOS_PER_PAGE,
|
|
||||||
page=page,
|
|
||||||
owner=owner,
|
|
||||||
)
|
|
||||||
except HTTPException as exc:
|
|
||||||
if exc.status_code not in {403, 502, 503}:
|
|
||||||
raise
|
|
||||||
repo_error = exc.detail
|
|
||||||
else:
|
|
||||||
repos = repo_page.repos
|
|
||||||
total_count = repo_page.total_count or 0
|
|
||||||
has_next_page = repo_page.has_next_page
|
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request,
|
request,
|
||||||
"dashboard.html",
|
"dashboard.html",
|
||||||
{
|
{
|
||||||
"user": sess.user,
|
"user": sess.user,
|
||||||
"pat_registered": sess.user.has_pat,
|
"pat_registered": sess.user.has_pat,
|
||||||
"repos": repos,
|
|
||||||
"repo_error": repo_error,
|
|
||||||
"repo_page": page,
|
|
||||||
"repo_total_count": total_count,
|
|
||||||
"repo_has_previous_page": page > 1,
|
|
||||||
"repo_has_next_page": has_next_page,
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,19 @@
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Literal
|
from typing import Annotated, Literal
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
|
||||||
from pydantic import BaseModel, EmailStr
|
from pydantic import BaseModel, EmailStr
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.crypto import decrypt_token
|
||||||
|
from app.auth.session import get_current_session
|
||||||
|
from app.clients import forgejo
|
||||||
|
from app.deps import get_db
|
||||||
|
from app.models.app_settings import AppSettings
|
||||||
|
from app.models.session import Session as UserBrowserSession
|
||||||
|
from app.models.user import LinkedIdentity
|
||||||
|
from app.settings import get_app_settings, get_fernet
|
||||||
|
|
||||||
router = APIRouter(prefix="/links", tags=["links"])
|
router = APIRouter(prefix="/links", tags=["links"])
|
||||||
|
|
||||||
|
|
@ -22,7 +33,94 @@ class CreateLinkResponse(BaseModel):
|
||||||
share_url: str
|
share_url: str
|
||||||
|
|
||||||
|
|
||||||
|
async def get_forgejo_token(
|
||||||
|
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
||||||
|
) -> str:
|
||||||
|
if not sess.user.has_pat:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Personal access token not found. Please register one and try again.",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return decrypt_token(get_fernet(), sess.user.pat_encrypted)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Stored Forgejo token cannot be decrypted. Reconnect your account in settings.",
|
||||||
|
) from None
|
||||||
|
|
||||||
|
|
||||||
@router.post("/", status_code=501)
|
@router.post("/", status_code=501)
|
||||||
async def create_link(request: CreateLinkRequest) -> dict:
|
async def create_link(request: CreateLinkRequest) -> dict:
|
||||||
"""Stub — link creation not yet implemented."""
|
"""Stub — link creation not yet implemented."""
|
||||||
return {"detail": "Link creation is not yet implemented."}
|
return {"detail": "Link creation is not yet implemented."}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/repositories")
|
||||||
|
async def get_repositories(
|
||||||
|
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
||||||
|
access_token: Annotated[str, Depends(get_forgejo_token)],
|
||||||
|
):
|
||||||
|
"""Get a list of the user's repositories from Forgejo."""
|
||||||
|
|
||||||
|
repos = await forgejo.get_repos(app_settings, access_token)
|
||||||
|
return repos
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/repositories/{repo}/branches")
|
||||||
|
async def get_repository_branches(
|
||||||
|
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
||||||
|
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
||||||
|
access_token: Annotated[str, Depends(get_forgejo_token)],
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
repo: Annotated[str, Path(min_length=1, description="The name of the repository")],
|
||||||
|
limit: int = 10,
|
||||||
|
page: int = 1,
|
||||||
|
):
|
||||||
|
# Derive {owner} path param from users linked identity provider server-side
|
||||||
|
stmt = select(LinkedIdentity).where(
|
||||||
|
LinkedIdentity.user_id == sess.user_id, LinkedIdentity.provider == "forgejo"
|
||||||
|
)
|
||||||
|
result = await db.execute(stmt)
|
||||||
|
identity = result.scalar_one_or_none()
|
||||||
|
if identity is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="No linked identity for forgejo was found. Please sign-in and try again.",
|
||||||
|
)
|
||||||
|
owner = identity.provider_username
|
||||||
|
|
||||||
|
branches = await forgejo.get_branches(
|
||||||
|
app_settings, access_token, owner, repo, limit=limit, page=page
|
||||||
|
)
|
||||||
|
return branches
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/repositories/{repo}/commits")
|
||||||
|
async def get_repository_commits(
|
||||||
|
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
||||||
|
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
||||||
|
access_token: Annotated[str, Depends(get_forgejo_token)],
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
repo: Annotated[str, Path(min_length=1, description="The name of the repository")],
|
||||||
|
ref: Annotated[str, Query(description="Branch name, commit sha, or tag")] = "main",
|
||||||
|
limit: int = 10,
|
||||||
|
page: int = 1,
|
||||||
|
):
|
||||||
|
# Derive {owner} path param from users linked identity provider server-side
|
||||||
|
stmt = select(LinkedIdentity).where(
|
||||||
|
LinkedIdentity.user_id == sess.user_id, LinkedIdentity.provider == "forgejo"
|
||||||
|
)
|
||||||
|
result = await db.execute(stmt)
|
||||||
|
identity = result.scalar_one_or_none()
|
||||||
|
if identity is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="No linked identity for forgejo was found. Please sign-in and try again.",
|
||||||
|
)
|
||||||
|
owner = identity.provider_username
|
||||||
|
|
||||||
|
commits = await forgejo.get_commits(
|
||||||
|
app_settings, access_token, owner, repo, ref=ref, limit=limit, page=page
|
||||||
|
)
|
||||||
|
return commits
|
||||||
|
|
|
||||||
|
|
@ -1,124 +0,0 @@
|
||||||
from typing import Annotated
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
|
|
||||||
from sqlalchemy import select
|
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
|
||||||
|
|
||||||
from app.auth.crypto import decrypt_token
|
|
||||||
from app.auth.session import get_current_session
|
|
||||||
from app.clients import forgejo
|
|
||||||
from app.deps import get_db
|
|
||||||
from app.models.app_settings import AppSettings
|
|
||||||
from app.models.session import Session as UserBrowserSession
|
|
||||||
from app.models.user import LinkedIdentity
|
|
||||||
from app.settings import get_app_settings, get_fernet
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/links", tags=["repositories"])
|
|
||||||
|
|
||||||
|
|
||||||
async def get_forgejo_token(
|
|
||||||
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
|
||||||
) -> str:
|
|
||||||
"""Decrypt the current user's Forgejo access token.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
sess: The authenticated browser session.
|
|
||||||
Returns:
|
|
||||||
The decrypted Forgejo access token.
|
|
||||||
Raises:
|
|
||||||
HTTPException: If no token is registered, or it cannot be decrypted.
|
|
||||||
"""
|
|
||||||
encrypted_token = sess.user.pat_encrypted
|
|
||||||
if encrypted_token is None:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
detail="Personal access token not found. Please register one and try again.",
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
return decrypt_token(get_fernet(), encrypted_token)
|
|
||||||
except ValueError:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
||||||
detail="Stored Forgejo token cannot be decrypted. Reconnect your account in settings.",
|
|
||||||
) from None
|
|
||||||
|
|
||||||
|
|
||||||
async def get_forgejo_owner(
|
|
||||||
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
|
||||||
db: Annotated[AsyncSession, Depends(get_db)],
|
|
||||||
) -> str:
|
|
||||||
"""Resolve the {owner} path value from the user's linked identity.
|
|
||||||
|
|
||||||
Owner is derived server-side rather than taken from the request so a
|
|
||||||
caller cannot address repositories belonging to someone else.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
sess: The authenticated browser session.
|
|
||||||
db: A request-scoped database session.
|
|
||||||
Returns:
|
|
||||||
The Forgejo username linked to the signed-in user.
|
|
||||||
Raises:
|
|
||||||
HTTPException: If the session has no linked Forgejo identity.
|
|
||||||
"""
|
|
||||||
stmt = select(LinkedIdentity).where(
|
|
||||||
LinkedIdentity.user_id == sess.user_id, LinkedIdentity.provider == "forgejo"
|
|
||||||
)
|
|
||||||
result = await db.execute(stmt)
|
|
||||||
identity = result.scalar_one_or_none()
|
|
||||||
if identity is None:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
detail="No linked identity for forgejo was found. Please sign-in and try again.",
|
|
||||||
)
|
|
||||||
return identity.provider_username
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/repositories")
|
|
||||||
async def get_repositories(
|
|
||||||
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
|
||||||
access_token: Annotated[str, Depends(get_forgejo_token)],
|
|
||||||
owner: Annotated[str, Depends(get_forgejo_owner)],
|
|
||||||
limit: Annotated[int, Query(ge=1, le=50)] = 30,
|
|
||||||
page: Annotated[int, Query(ge=1)] = 1,
|
|
||||||
):
|
|
||||||
"""Get a page of repositories owned by the linked Forgejo account."""
|
|
||||||
|
|
||||||
repo_page = await forgejo.get_repos(
|
|
||||||
app_settings, access_token, owner=owner, limit=limit, page=page
|
|
||||||
)
|
|
||||||
return repo_page.repos
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/repositories/{repo}/branches")
|
|
||||||
async def get_repository_branches(
|
|
||||||
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
|
||||||
access_token: Annotated[str, Depends(get_forgejo_token)],
|
|
||||||
owner: Annotated[str, Depends(get_forgejo_owner)],
|
|
||||||
repo: Annotated[str, Path(min_length=1, description="The name of the repository")],
|
|
||||||
limit: int = 10,
|
|
||||||
page: int = 1,
|
|
||||||
):
|
|
||||||
"""List the branches of the signed-in user's repository."""
|
|
||||||
|
|
||||||
branches = await forgejo.get_branches(
|
|
||||||
app_settings, access_token, owner, repo, limit=limit, page=page
|
|
||||||
)
|
|
||||||
return branches
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/repositories/{repo}/commits")
|
|
||||||
async def get_repository_commits(
|
|
||||||
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
|
||||||
access_token: Annotated[str, Depends(get_forgejo_token)],
|
|
||||||
owner: Annotated[str, Depends(get_forgejo_owner)],
|
|
||||||
repo: Annotated[str, Path(min_length=1, description="The name of the repository")],
|
|
||||||
ref: Annotated[str, Query(description="Branch name, commit sha, or tag")] = "main",
|
|
||||||
limit: int = 10,
|
|
||||||
page: int = 1,
|
|
||||||
):
|
|
||||||
"""List the commits of the signed-in user's repository at a ref."""
|
|
||||||
|
|
||||||
commits = await forgejo.get_commits(
|
|
||||||
app_settings, access_token, owner, repo, ref=ref, limit=limit, page=page
|
|
||||||
)
|
|
||||||
return commits
|
|
||||||
|
|
@ -57,7 +57,7 @@
|
||||||
<th class="px-4 py-3">Expires</th>
|
<th class="px-4 py-3">Expires</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody class="divide-y divide-border">
|
<tbody class="divide-y divide-border-subtle">
|
||||||
<tr class="text-muted-foreground text-center">
|
<tr class="text-muted-foreground text-center">
|
||||||
<td class="px-4 py-5" colspan="5">You have not created any share links yet.</td>
|
<td class="px-4 py-5" colspan="5">You have not created any share links yet.</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
@ -66,86 +66,5 @@
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<div class="space-y-3">
|
|
||||||
<div class="flex flex-col justify-between gap-2 sm:flex-row sm:items-end">
|
|
||||||
<div>
|
|
||||||
<h2 class="text-base font-semibold">Repositories</h2>
|
|
||||||
<p class="mt-2 text-sm text-muted-foreground">Repositories owned by your Forgejo account.</p>
|
|
||||||
</div>
|
|
||||||
{% if pat_registered and repo_total_count %}
|
|
||||||
<p class="text-xs text-muted-foreground">{{ repo_total_count }} total</p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
<section class="card">
|
|
||||||
<div class="overflow-x-auto">
|
|
||||||
<table class="w-full min-w-180 text-left text-sm">
|
|
||||||
<thead class="bg-muted text-xs font-semibold uppercase tracking-[0.05em] text-muted-foreground">
|
|
||||||
<tr>
|
|
||||||
<th class="px-4 py-3">Repository</th>
|
|
||||||
<th class="px-4 py-3">Default branch</th>
|
|
||||||
<th class="px-4 py-3">Visibility</th>
|
|
||||||
<th class="px-4 py-3">Updated</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody class="divide-y divide-border">
|
|
||||||
{% if not pat_registered %}
|
|
||||||
<tr class="text-muted-foreground text-center">
|
|
||||||
<td class="px-4 py-5" colspan="4">Register a Forgejo access token to view your repositories.</td>
|
|
||||||
</tr>
|
|
||||||
{% elif repo_error %}
|
|
||||||
<tr class="text-center text-warning-foreground">
|
|
||||||
<td class="px-4 py-5" colspan="4" role="alert">{{ repo_error }}</td>
|
|
||||||
</tr>
|
|
||||||
{% elif repos %}
|
|
||||||
{% for repo in repos %}
|
|
||||||
<tr class="hover:bg-muted/40">
|
|
||||||
<td class="px-4 py-3">
|
|
||||||
<a href="{{ repo.html_url }}"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
class="font-medium text-foreground hover:underline">{{ repo.repo_name }}</a>
|
|
||||||
{% if repo.description %}
|
|
||||||
<p class="mt-1 max-w-xl truncate text-xs text-muted-foreground">{{ repo.description }}</p>
|
|
||||||
{% endif %}
|
|
||||||
{% if repo.archived %}
|
|
||||||
<span class="badge-warning mt-1 inline-flex">Archived</span>
|
|
||||||
{% endif %}
|
|
||||||
</td>
|
|
||||||
<td class="px-4 py-3 font-mono text-xs">{{ repo.default_branch }}</td>
|
|
||||||
<td class="px-4 py-3">
|
|
||||||
{% if repo.visibility == "public" %}
|
|
||||||
<span class="badge-success">Public</span>
|
|
||||||
{% else %}
|
|
||||||
<span class="badge bg-muted text-muted-foreground">Private</span>
|
|
||||||
{% endif %}
|
|
||||||
</td>
|
|
||||||
<td class="px-4 py-3 whitespace-nowrap text-xs text-muted-foreground">{{ repo.updated_at.strftime("%b %d, %Y") }}</td>
|
|
||||||
</tr>
|
|
||||||
{% endfor %}
|
|
||||||
{% else %}
|
|
||||||
<tr class="text-muted-foreground text-center">
|
|
||||||
<td class="px-4 py-5" colspan="4">No owned repositories found on this page.</td>
|
|
||||||
</tr>
|
|
||||||
{% endif %}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
{% if pat_registered and not repo_error and (repo_has_previous_page or repo_has_next_page) %}
|
|
||||||
<nav class="flex items-center justify-between border-t border-border px-4 py-3" aria-label="Repository pages">
|
|
||||||
{% if repo_has_previous_page %}
|
|
||||||
<a href="/dashboard?page={{ repo_page - 1 }}" class="btn btn-sm btn-secondary">Previous</a>
|
|
||||||
{% else %}
|
|
||||||
<span></span>
|
|
||||||
{% endif %}
|
|
||||||
<span class="text-xs text-muted-foreground">Page {{ repo_page }}</span>
|
|
||||||
{% if repo_has_next_page %}
|
|
||||||
<a href="/dashboard?page={{ repo_page + 1 }}" class="btn btn-sm btn-secondary">Next</a>
|
|
||||||
{% else %}
|
|
||||||
<span></span>
|
|
||||||
{% endif %}
|
|
||||||
</nav>
|
|
||||||
{% endif %}
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue