Merge branch 'main' of ssh://git.commumedia.org:2222/alex/headquarter
This commit is contained in:
@@ -89,6 +89,88 @@ def _get_repo_path(user_id: uuid.UUID, project_id: uuid.UUID, name: str) -> str:
|
||||
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}",
|
||||
)
|
||||
|
||||
|
||||
class GitRepositoryCreate(BaseModel):
|
||||
name: str
|
||||
remote_url: str | None = None
|
||||
@@ -217,7 +299,7 @@ async def parse_repository_url(data: URLParseRequest) -> URLParseResponse:
|
||||
response_model=GitRepositoryResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a repository",
|
||||
description="Create a new git repository in a project. Can clone from remote or initialize bare.",
|
||||
description="Create a new git repository in a project. Can clone from remote or initialize a working repository.",
|
||||
)
|
||||
async def create_repository(
|
||||
project_id: uuid.UUID,
|
||||
@@ -267,47 +349,25 @@ async def create_repository(
|
||||
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)
|
||||
|
||||
# Ensure parent directory exists
|
||||
os.makedirs(os.path.dirname(repo_path), exist_ok=True)
|
||||
|
||||
if remote_url:
|
||||
# Clone as mirror
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "clone", "--mirror", remote_url, repo_path],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=300,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"failed to clone repository: {result.stderr}",
|
||||
)
|
||||
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")
|
||||
_clone_working_repository(remote_url, repo_path)
|
||||
else:
|
||||
# Init bare repo
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "init", "--bare", repo_path],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="git command not found")
|
||||
_init_working_repository(repo_path)
|
||||
|
||||
repo = GitRepository(
|
||||
name=data.name,
|
||||
path=repo_path,
|
||||
project_id=project_id,
|
||||
owner_id=user_id,
|
||||
is_mirror=bool(remote_url),
|
||||
is_mirror=False,
|
||||
remote_url=remote_url,
|
||||
)
|
||||
session.add(repo)
|
||||
|
||||
@@ -45,7 +45,10 @@ def get_status(repo_path: str) -> GitStatus:
|
||||
try:
|
||||
branch = _run_git_command(repo_path, "rev-parse", "--abbrev-ref", "HEAD").strip()
|
||||
except RuntimeError:
|
||||
branch = "HEAD"
|
||||
try:
|
||||
branch = _run_git_command(repo_path, "symbolic-ref", "--short", "HEAD").strip()
|
||||
except RuntimeError:
|
||||
branch = "HEAD"
|
||||
|
||||
status = GitStatus(branch=branch)
|
||||
|
||||
@@ -118,6 +121,13 @@ def create_branch(repo_path: str, name: str, base_branch: str = "HEAD") -> None:
|
||||
Raises:
|
||||
RuntimeError: If branch creation fails
|
||||
"""
|
||||
if base_branch == "HEAD":
|
||||
try:
|
||||
_run_git_command(repo_path, "rev-parse", "--verify", "HEAD")
|
||||
except RuntimeError:
|
||||
_run_git_command(repo_path, "checkout", "--orphan", name)
|
||||
return
|
||||
|
||||
_run_git_command(repo_path, "branch", name, base_branch)
|
||||
|
||||
|
||||
@@ -215,7 +225,8 @@ def pull(repo_path: str, branch: str | None = None) -> None:
|
||||
"""
|
||||
args = ["pull"]
|
||||
if branch:
|
||||
args.extend(["origin", branch])
|
||||
args.append("origin")
|
||||
args.append(branch)
|
||||
_run_git_command(repo_path, *args)
|
||||
|
||||
|
||||
@@ -279,4 +290,7 @@ def get_current_branch(repo_path: str) -> str:
|
||||
Returns:
|
||||
Current branch name
|
||||
"""
|
||||
return _run_git_command(repo_path, "rev-parse", "--abbrev-ref", "HEAD").strip()
|
||||
try:
|
||||
return _run_git_command(repo_path, "rev-parse", "--abbrev-ref", "HEAD").strip()
|
||||
except RuntimeError:
|
||||
return _run_git_command(repo_path, "symbolic-ref", "--short", "HEAD").strip()
|
||||
|
||||
@@ -346,7 +346,20 @@ def list_branches(repo_path: str) -> tuple[list[BranchInfo], str]:
|
||||
)
|
||||
default_branch = branch_name
|
||||
except RuntimeError:
|
||||
pass
|
||||
try:
|
||||
output = _run_git_command(repo_path, "symbolic-ref", "--short", "HEAD")
|
||||
branch_name = output.strip()
|
||||
if branch_name:
|
||||
branches.append(
|
||||
BranchInfo(
|
||||
name=branch_name,
|
||||
is_default=True,
|
||||
last_commit=None,
|
||||
)
|
||||
)
|
||||
default_branch = branch_name
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
return branches, default_branch
|
||||
|
||||
|
||||
@@ -63,6 +63,13 @@ class TestGitStatus:
|
||||
assert "new.py" in status.untracked
|
||||
|
||||
|
||||
def test_get_current_branch_handles_unborn_main() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
os.system(f"git init -b main {tmpdir} >/dev/null 2>&1")
|
||||
|
||||
assert get_current_branch(tmpdir) == "main"
|
||||
|
||||
|
||||
class TestBranchOperations:
|
||||
"""Tests for branch management functions."""
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from src.api.git_repositories import _build_provider_clone_url, _preflight_remote_repository
|
||||
|
||||
|
||||
def test_build_provider_clone_url_uses_fixed_host() -> None:
|
||||
assert _build_provider_clone_url("alice", "demo") == "git@git.commumedia.org:alice/demo.git"
|
||||
|
||||
|
||||
def test_preflight_remote_repository_allows_accessible_repo() -> None:
|
||||
completed = Mock(returncode=0)
|
||||
with patch("src.api.git_repositories.subprocess.run", return_value=completed) as run_mock:
|
||||
_preflight_remote_repository("git@git.commumedia.org:alice/demo.git")
|
||||
|
||||
run_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_preflight_remote_repository_rejects_missing_repo() -> None:
|
||||
completed = Mock(returncode=128)
|
||||
with patch("src.api.git_repositories.subprocess.run", return_value=completed):
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_preflight_remote_repository("git@git.commumedia.org:alice/missing.git")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
assert exc_info.value.detail == "repository not found or inaccessible"
|
||||
@@ -0,0 +1,64 @@
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from src.api.git_repositories import _clone_working_repository, _init_working_repository
|
||||
from src.utils.git_control import create_branch
|
||||
|
||||
|
||||
def test_clone_working_repository_uses_normal_clone() -> None:
|
||||
completed = Mock(returncode=0, stderr="")
|
||||
with patch("src.api.git_repositories.subprocess.run", return_value=completed) as run_mock:
|
||||
_clone_working_repository("git@git.commumedia.org:alice/demo.git", "/tmp/demo.git")
|
||||
|
||||
run_mock.assert_called_once()
|
||||
assert run_mock.call_args.args[0] == ["git", "clone", "git@git.commumedia.org:alice/demo.git", "/tmp/demo.git"]
|
||||
|
||||
|
||||
def test_clone_working_repository_raises_on_failure() -> None:
|
||||
completed = Mock(returncode=128, stderr="fatal: repository not found")
|
||||
with patch("src.api.git_repositories.subprocess.run", return_value=completed):
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_clone_working_repository("git@git.commumedia.org:alice/missing.git", "/tmp/missing.git")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "failed to clone repository" in exc_info.value.detail
|
||||
|
||||
|
||||
def test_init_working_repository_prefers_init_b() -> None:
|
||||
init_b = Mock(returncode=0, stderr="")
|
||||
with patch("src.api.git_repositories.subprocess.run", return_value=init_b) as run_mock:
|
||||
_init_working_repository("/tmp/new-repo")
|
||||
|
||||
assert run_mock.call_args.args[0] == ["git", "init", "-b", "main", "/tmp/new-repo"]
|
||||
|
||||
|
||||
def test_init_working_repository_falls_back_to_symbolic_ref() -> None:
|
||||
init_b = Mock(returncode=1, stderr="unknown switch `b'")
|
||||
init_ok = Mock(returncode=0, stderr="")
|
||||
symbolic_ref = Mock(returncode=0, stderr="")
|
||||
|
||||
with patch("src.api.git_repositories.subprocess.run", side_effect=[init_b, init_ok, symbolic_ref]) as run_mock:
|
||||
_init_working_repository("/tmp/new-repo")
|
||||
|
||||
assert run_mock.call_args_list[0].args[0] == ["git", "init", "-b", "main", "/tmp/new-repo"]
|
||||
assert run_mock.call_args_list[1].args[0] == ["git", "init", "/tmp/new-repo"]
|
||||
assert run_mock.call_args_list[2].args[0] == ["git", "-C", "/tmp/new-repo", "symbolic-ref", "HEAD", "refs/heads/main"]
|
||||
|
||||
|
||||
def test_create_branch_uses_orphan_checkout_when_head_is_unborn() -> None:
|
||||
call_count = 0
|
||||
|
||||
def mock_run(repo_path: str, *args: str) -> str:
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count == 1:
|
||||
raise RuntimeError("fatal: Needed a single revision")
|
||||
return ""
|
||||
|
||||
with patch("src.utils.git_control._run_git_command", side_effect=mock_run) as run_mock:
|
||||
create_branch("/tmp/new-repo", "feature/test")
|
||||
|
||||
assert run_mock.call_args_list[0].args[1:] == ("rev-parse", "--verify", "HEAD^{commit}")
|
||||
assert run_mock.call_args_list[1].args[1:] == ("checkout", "--orphan", "feature/test")
|
||||
@@ -17,6 +17,7 @@ interface GitToolbarProps {
|
||||
repoId: string;
|
||||
currentBranch: string;
|
||||
branches: string[];
|
||||
hasRemote: boolean;
|
||||
onBranchChange: (branch: string) => void;
|
||||
onRefresh: () => void;
|
||||
}
|
||||
@@ -26,6 +27,7 @@ export const GitToolbar = ({
|
||||
repoId,
|
||||
currentBranch,
|
||||
branches,
|
||||
hasRemote,
|
||||
onBranchChange,
|
||||
onRefresh,
|
||||
}: GitToolbarProps) => {
|
||||
@@ -55,6 +57,7 @@ export const GitToolbar = ({
|
||||
}, [loadStatus]);
|
||||
|
||||
const handleFetch = async () => {
|
||||
if (!hasRemote) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await fetchRepository(projectId, repoId);
|
||||
@@ -67,9 +70,10 @@ export const GitToolbar = ({
|
||||
};
|
||||
|
||||
const handlePull = async () => {
|
||||
if (!hasRemote) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await pullRepository(projectId, repoId, currentBranch);
|
||||
await pullRepository(projectId, repoId, currentBranch || undefined);
|
||||
await loadStatus();
|
||||
onRefresh();
|
||||
} catch {
|
||||
@@ -108,7 +112,7 @@ export const GitToolbar = ({
|
||||
if (!newBranchName.trim()) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await createBranch(projectId, repoId, newBranchName, newBranchBase || "HEAD");
|
||||
await createBranch(projectId, repoId, newBranchName, newBranchBase || currentBranch || "HEAD");
|
||||
setShowNewBranch(false);
|
||||
setNewBranchName("");
|
||||
setNewBranchBase("");
|
||||
@@ -127,6 +131,8 @@ export const GitToolbar = ({
|
||||
status.untracked.length > 0
|
||||
);
|
||||
|
||||
const canSync = hasRemote;
|
||||
|
||||
return (
|
||||
<div className="git-toolbar">
|
||||
{error && <div className="toolbar-error">{error}</div>}
|
||||
@@ -162,10 +168,10 @@ export const GitToolbar = ({
|
||||
</div>
|
||||
|
||||
<div className="toolbar-group">
|
||||
<button
|
||||
<button
|
||||
className="toolbar-button"
|
||||
onClick={handleFetch}
|
||||
disabled={loading}
|
||||
disabled={loading || !canSync}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="fetch" size="sm" /> Fetch
|
||||
@@ -173,7 +179,7 @@ export const GitToolbar = ({
|
||||
<button
|
||||
className="toolbar-button"
|
||||
onClick={handlePull}
|
||||
disabled={loading}
|
||||
disabled={loading || !canSync}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="pull" size="sm" /> Pull
|
||||
@@ -182,7 +188,7 @@ export const GitToolbar = ({
|
||||
<button
|
||||
className="toolbar-button"
|
||||
onClick={handlePush}
|
||||
disabled={loading || !status?.ahead}
|
||||
disabled={loading || !canSync || !status?.ahead}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="push" size="sm" /> Push
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { RepositoriesSettingsTab } from "./repositories-settings-tab";
|
||||
import * as gitRepositoriesApi from "../api/git_repositories";
|
||||
|
||||
const mockRepositories = [
|
||||
{
|
||||
id: "repo-1",
|
||||
name: "Main Repo",
|
||||
path: "/repos/main",
|
||||
project_id: "proj-1",
|
||||
owner_id: "user-1",
|
||||
is_mirror: false,
|
||||
remote_url: null,
|
||||
last_push: null,
|
||||
created_at: null,
|
||||
},
|
||||
];
|
||||
|
||||
vi.mock("react-router-dom", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router-dom")>("react-router-dom");
|
||||
return {
|
||||
...actual,
|
||||
useParams: () => ({ projectId: "proj-1" }),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("RepositoriesSettingsTab", () => {
|
||||
it("opens create dialog and clones an existing repository", async () => {
|
||||
const listMock = vi.spyOn(gitRepositoriesApi, "listRepositories").mockResolvedValue(mockRepositories);
|
||||
const createMock = vi.spyOn(gitRepositoriesApi, "createRepository").mockResolvedValue(mockRepositories[0]);
|
||||
|
||||
render(<RepositoriesSettingsTab />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Main Repo")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /add repository/i }));
|
||||
fireEvent.change(screen.getByPlaceholderText(/repository-name/i), {
|
||||
target: { value: "New Repo" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText(/owner/i), {
|
||||
target: { value: "alice" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText(/repo-name/i), {
|
||||
target: { value: "demo" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: /clone repository/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMock).toHaveBeenCalledWith("proj-1", {
|
||||
name: "New Repo",
|
||||
remote_url: "git@git.commumedia.org:alice/demo.git",
|
||||
});
|
||||
});
|
||||
expect(listMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("uses advanced url fallback when requested", async () => {
|
||||
const listMock = vi.spyOn(gitRepositoriesApi, "listRepositories").mockResolvedValue(mockRepositories);
|
||||
const createMock = vi.spyOn(gitRepositoriesApi, "createRepository").mockResolvedValue(mockRepositories[0]);
|
||||
|
||||
render(<RepositoriesSettingsTab />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Main Repo")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /add repository/i }));
|
||||
fireEvent.change(screen.getByPlaceholderText(/repository-name/i), {
|
||||
target: { value: "New Repo" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: /use full url instead/i }));
|
||||
fireEvent.change(screen.getByPlaceholderText(/https:\/\/github.com\/user\/repo.git/i), {
|
||||
target: { value: "https://github.com/user/repo.git" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: /clone repository/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMock).toHaveBeenCalledWith("proj-1", {
|
||||
name: "New Repo",
|
||||
remote_url: "https://github.com/user/repo.git",
|
||||
});
|
||||
});
|
||||
expect(listMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("shows validation when cloning without a remote url", async () => {
|
||||
vi.spyOn(gitRepositoriesApi, "listRepositories").mockResolvedValue(mockRepositories);
|
||||
render(<RepositoriesSettingsTab />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Main Repo")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /add repository/i }));
|
||||
fireEvent.change(screen.getByPlaceholderText(/repository-name/i), {
|
||||
target: { value: "New Repo" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText(/owner/i), {
|
||||
target: { value: "" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: /clone repository/i }));
|
||||
|
||||
expect(screen.getByText(/owner and repository name are required/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,37 +1,45 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { apiClient } from "../api/client";
|
||||
import { GitRepository } from "../api/git_repositories";
|
||||
|
||||
import { deleteRepository, listRepositories, type GitRepository } from "../api/git_repositories";
|
||||
import { RepositoryCreateDialog } from "./repository-create-dialog";
|
||||
import { Icon } from "./icon";
|
||||
|
||||
export const RepositoriesSettingsTab: React.FC = () => {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
const [repositories, setRepositories] = useState<GitRepository[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(">");
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const fetchRepositories = async () => {
|
||||
try {
|
||||
const response = await apiClient.get(
|
||||
`/projects/${projectId}/repositories`
|
||||
);
|
||||
setRepositories(response.data);
|
||||
} catch (err) {
|
||||
setError("Failed to load repositories");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const loadRepositories = useCallback(async () => {
|
||||
if (!projectId) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
fetchRepositories();
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await listRepositories(projectId);
|
||||
setRepositories(data);
|
||||
} catch {
|
||||
setError("Failed to load repositories");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadRepositories();
|
||||
}, [loadRepositories]);
|
||||
|
||||
const handleDelete = async (repoId: string) => {
|
||||
if (!projectId) return;
|
||||
if (!window.confirm("Are you sure you want to delete this repository?")) return;
|
||||
try {
|
||||
await apiClient.delete(`/projects/${projectId}/repositories/${repoId}`);
|
||||
setRepositories(repositories.filter((r) => r.id !== repoId));
|
||||
} catch (err) {
|
||||
await deleteRepository(projectId, repoId);
|
||||
setRepositories((current) => current.filter((r) => r.id !== repoId));
|
||||
} catch {
|
||||
setError("Failed to delete repository");
|
||||
}
|
||||
};
|
||||
@@ -40,7 +48,17 @@ export const RepositoriesSettingsTab: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div className="repositories-settings-tab">
|
||||
<h2>Repositories</h2>
|
||||
<div className="page-header">
|
||||
<h2>Repositories</h2>
|
||||
<button
|
||||
className="primary-button"
|
||||
onClick={() => setShowCreate(true)}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="add" size="sm" />
|
||||
Add Repository
|
||||
</button>
|
||||
</div>
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
|
||||
<div className="repositories-list">
|
||||
@@ -66,6 +84,16 @@ export const RepositoriesSettingsTab: React.FC = () => {
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showCreate && (
|
||||
<RepositoryCreateDialog
|
||||
projectId={projectId!}
|
||||
open={showCreate}
|
||||
title="Add Repository"
|
||||
onClose={() => setShowCreate(false)}
|
||||
onCreated={loadRepositories}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { createRepository, parseGitUrl, type GitRepositoryCreate, type URLParseResult } from "../api/git_repositories";
|
||||
import { Icon } from "./icon";
|
||||
|
||||
type CreateMode = "clone" | "blank";
|
||||
type UrlValidationStatus = "idle" | "validating" | "valid" | "needs-parsing" | "invalid";
|
||||
|
||||
interface RepositoryCreateDialogProps {
|
||||
projectId: string;
|
||||
open: boolean;
|
||||
title: string;
|
||||
onClose: () => void;
|
||||
onCreated: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
export const RepositoryCreateDialog = ({ projectId, open, title, onClose, onCreated }: RepositoryCreateDialogProps) => {
|
||||
const [createMode, setCreateMode] = useState<CreateMode>("clone");
|
||||
const [formName, setFormName] = useState("");
|
||||
const [owner, setOwner] = useState("");
|
||||
const [repoName, setRepoName] = useState("");
|
||||
const [advancedUrl, setAdvancedUrl] = useState("");
|
||||
const [useAdvancedUrl, setUseAdvancedUrl] = useState(false);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [urlValidation, setUrlValidation] = useState<{
|
||||
status: UrlValidationStatus;
|
||||
result: URLParseResult | null;
|
||||
}>({ status: "idle", result: null });
|
||||
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open && debounceTimer.current) {
|
||||
clearTimeout(debounceTimer.current);
|
||||
debounceTimer.current = null;
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (!useAdvancedUrl) {
|
||||
setUrlValidation({ status: "idle", result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
if (debounceTimer.current) {
|
||||
clearTimeout(debounceTimer.current);
|
||||
}
|
||||
|
||||
if (!advancedUrl.trim()) {
|
||||
setUrlValidation({ status: "idle", result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
setUrlValidation({ status: "validating", result: null });
|
||||
|
||||
debounceTimer.current = setTimeout(async () => {
|
||||
try {
|
||||
const result = await parseGitUrl(advancedUrl.trim());
|
||||
if (result.is_valid_clone_url) {
|
||||
setUrlValidation({ status: "valid", result });
|
||||
} else if (result.needs_parsing) {
|
||||
setUrlValidation({ status: "needs-parsing", result });
|
||||
} else {
|
||||
setUrlValidation({ status: "invalid", result });
|
||||
}
|
||||
} catch {
|
||||
setUrlValidation({ status: "invalid", result: null });
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => {
|
||||
if (debounceTimer.current) {
|
||||
clearTimeout(debounceTimer.current);
|
||||
}
|
||||
};
|
||||
}, [advancedUrl, open, useAdvancedUrl]);
|
||||
|
||||
const resetForm = () => {
|
||||
setCreateMode("clone");
|
||||
setFormName("");
|
||||
setOwner("");
|
||||
setRepoName("");
|
||||
setAdvancedUrl("");
|
||||
setUseAdvancedUrl(false);
|
||||
setFormError(null);
|
||||
setUrlValidation({ status: "idle", result: null });
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
resetForm();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setFormError(null);
|
||||
|
||||
if (!formName.trim()) {
|
||||
setFormError("Repository name is required");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const input: GitRepositoryCreate = {
|
||||
name: formName.trim(),
|
||||
remote_url: undefined,
|
||||
};
|
||||
|
||||
if (createMode === "clone") {
|
||||
if (useAdvancedUrl) {
|
||||
if (!advancedUrl.trim()) {
|
||||
setFormError("Remote URL is required for advanced cloning");
|
||||
return;
|
||||
}
|
||||
input.remote_url = advancedUrl.trim();
|
||||
} else {
|
||||
if (!owner.trim() || !repoName.trim()) {
|
||||
setFormError("Owner and repository name are required");
|
||||
return;
|
||||
}
|
||||
input.remote_url = `git@git.commumedia.org:${owner.trim()}/${repoName.trim()}.git`;
|
||||
}
|
||||
}
|
||||
|
||||
await createRepository(projectId, input);
|
||||
handleClose();
|
||||
await onCreated();
|
||||
} catch (error: unknown) {
|
||||
const response = error as { response?: { data?: { detail?: string } } };
|
||||
const detail = response.response?.data?.detail;
|
||||
setFormError(typeof detail === "string" ? detail : "Failed to create repository");
|
||||
}
|
||||
};
|
||||
|
||||
const handleUseSuggestedUrl = () => {
|
||||
if (urlValidation.result?.base_url) {
|
||||
setAdvancedUrl(urlValidation.result.base_url);
|
||||
setUrlValidation({ status: "idle", result: null });
|
||||
setFormError(null);
|
||||
}
|
||||
};
|
||||
|
||||
const getUrlInputClass = () => {
|
||||
switch (urlValidation.status) {
|
||||
case "valid":
|
||||
return "valid-url";
|
||||
case "needs-parsing":
|
||||
return "needs-parsing-url";
|
||||
case "invalid":
|
||||
return "invalid-url";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div className="dialog-overlay" role="dialog" aria-modal="true">
|
||||
<div className="dialog">
|
||||
<h3>{title}</h3>
|
||||
<p className="muted">
|
||||
Clone an existing repository from git.commumedia.org, or create a blank bare repo here.
|
||||
</p>
|
||||
<form onSubmit={handleSubmit} className="stack">
|
||||
<div className="form-field">
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
name="repository-mode"
|
||||
checked={createMode === "clone"}
|
||||
onChange={() => setCreateMode("clone")}
|
||||
/>
|
||||
Clone existing repository
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
name="repository-mode"
|
||||
checked={createMode === "blank"}
|
||||
onChange={() => setCreateMode("blank")}
|
||||
/>
|
||||
Create blank repository
|
||||
</label>
|
||||
</div>
|
||||
<label className="form-field">
|
||||
Repository name
|
||||
<input
|
||||
type="text"
|
||||
value={formName}
|
||||
onChange={(event) => setFormName(event.target.value)}
|
||||
placeholder="repository-name"
|
||||
/>
|
||||
</label>
|
||||
{createMode === "clone" && !useAdvancedUrl && (
|
||||
<>
|
||||
<label className="form-field">
|
||||
Owner
|
||||
<input
|
||||
type="text"
|
||||
value={owner}
|
||||
onChange={(event) => setOwner(event.target.value)}
|
||||
placeholder="owner"
|
||||
/>
|
||||
</label>
|
||||
<label className="form-field">
|
||||
Repository
|
||||
<input
|
||||
type="text"
|
||||
value={repoName}
|
||||
onChange={(event) => setRepoName(event.target.value)}
|
||||
placeholder="repo-name"
|
||||
/>
|
||||
</label>
|
||||
<p className="muted">SSH target: git@git.commumedia.org:{owner || "owner"}/{repoName || "repo"}.git</p>
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button small"
|
||||
onClick={() => setUseAdvancedUrl(true)}
|
||||
>
|
||||
Use full URL instead
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{createMode === "clone" && useAdvancedUrl && (
|
||||
<label className="form-field">
|
||||
Remote URL
|
||||
<input
|
||||
type="text"
|
||||
value={advancedUrl}
|
||||
onChange={(event) => setAdvancedUrl(event.target.value)}
|
||||
placeholder="https://github.com/user/repo.git"
|
||||
className={getUrlInputClass()}
|
||||
/>
|
||||
{urlValidation.status === "validating" && (
|
||||
<span className="validation-status validating">Validating...</span>
|
||||
)}
|
||||
{urlValidation.status === "valid" && (
|
||||
<span className="validation-status valid">
|
||||
<Icon name="success" size="sm" /> Valid git URL
|
||||
</span>
|
||||
)}
|
||||
{urlValidation.status === "needs-parsing" && urlValidation.result && (
|
||||
<div className="url-suggestion">
|
||||
<span className="validation-status warning">
|
||||
<Icon name="warning" size="sm" /> This looks like a browser URL
|
||||
</span>
|
||||
<div className="suggestion-actions">
|
||||
<span className="suggested-url">Suggested: {urlValidation.result.base_url}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button small"
|
||||
onClick={handleUseSuggestedUrl}
|
||||
>
|
||||
Use Suggested
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{urlValidation.status === "invalid" && (
|
||||
<span className="validation-status invalid">
|
||||
<Icon name="error" size="sm" /> Invalid URL
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button small"
|
||||
onClick={() => setUseAdvancedUrl(false)}
|
||||
>
|
||||
Use owner/repo instead
|
||||
</button>
|
||||
</label>
|
||||
)}
|
||||
{formError && (
|
||||
<div className="error-message">
|
||||
<p className="error-text">{formError}</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="dialog-actions">
|
||||
<button className="secondary-button" onClick={handleClose} type="button">
|
||||
<Icon name="cancel" size="sm" />
|
||||
Cancel
|
||||
</button>
|
||||
<button className="primary-button" type="submit">
|
||||
<Icon name="add" size="sm" />
|
||||
{createMode === "clone" ? "Clone Repository" : "Create Blank Repository"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,19 +1,15 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
|
||||
import {
|
||||
createRepository,
|
||||
deleteRepository,
|
||||
listRepositories,
|
||||
parseGitUrl,
|
||||
type GitRepositoryCreate,
|
||||
type URLParseResult,
|
||||
} from "../api/git_repositories";
|
||||
import type { GitRepository } from "../api/git_repositories";
|
||||
import { Icon } from "../components/icon";
|
||||
import { RepositoryCreateDialog } from "../components/repository-create-dialog";
|
||||
|
||||
type RepoStatus = "loading" | "ready" | "error";
|
||||
type UrlValidationStatus = "idle" | "validating" | "valid" | "needs-parsing" | "invalid";
|
||||
|
||||
export const GitRepositoriesPage = () => {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -21,19 +17,8 @@ export const GitRepositoriesPage = () => {
|
||||
const [status, setStatus] = useState<RepoStatus>("loading");
|
||||
const [repositories, setRepositories] = useState<GitRepository[]>([]);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [formName, setFormName] = useState("");
|
||||
const [formRemoteUrl, setFormRemoteUrl] = useState("");
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
|
||||
|
||||
// URL validation state
|
||||
const [urlValidation, setUrlValidation] = useState<{
|
||||
status: UrlValidationStatus;
|
||||
result: URLParseResult | null;
|
||||
}>({ status: "idle", result: null });
|
||||
|
||||
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const loadRepositories = useCallback(async () => {
|
||||
if (!projectId) return;
|
||||
setStatus("loading");
|
||||
@@ -51,98 +36,6 @@ export const GitRepositoriesPage = () => {
|
||||
void loadRepositories();
|
||||
}, [loadRepositories]);
|
||||
|
||||
// Validate URL with debounce
|
||||
useEffect(() => {
|
||||
if (debounceTimer.current) {
|
||||
clearTimeout(debounceTimer.current);
|
||||
}
|
||||
|
||||
if (!formRemoteUrl.trim()) {
|
||||
setUrlValidation({ status: "idle", result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
setUrlValidation({ status: "validating", result: null });
|
||||
|
||||
debounceTimer.current = setTimeout(async () => {
|
||||
try {
|
||||
const result = await parseGitUrl(formRemoteUrl.trim());
|
||||
if (result.is_valid_clone_url) {
|
||||
setUrlValidation({ status: "valid", result });
|
||||
} else if (result.needs_parsing) {
|
||||
setUrlValidation({ status: "needs-parsing", result });
|
||||
} else {
|
||||
setUrlValidation({ status: "invalid", result });
|
||||
}
|
||||
} catch {
|
||||
setUrlValidation({ status: "invalid", result: null });
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => {
|
||||
if (debounceTimer.current) {
|
||||
clearTimeout(debounceTimer.current);
|
||||
}
|
||||
};
|
||||
}, [formRemoteUrl]);
|
||||
|
||||
const getUrlInputClass = () => {
|
||||
switch (urlValidation.status) {
|
||||
case "valid":
|
||||
return "valid-url";
|
||||
case "needs-parsing":
|
||||
return "needs-parsing-url";
|
||||
case "invalid":
|
||||
return "invalid-url";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
|
||||
if (!formName.trim()) {
|
||||
setFormError("Repository name is required");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!projectId) return;
|
||||
|
||||
try {
|
||||
const input: GitRepositoryCreate = {
|
||||
name: formName.trim(),
|
||||
remote_url: formRemoteUrl.trim() || undefined,
|
||||
};
|
||||
await createRepository(projectId, input);
|
||||
setShowCreate(false);
|
||||
setFormName("");
|
||||
setFormRemoteUrl("");
|
||||
setUrlValidation({ status: "idle", result: null });
|
||||
await loadRepositories();
|
||||
} catch (err: unknown) {
|
||||
const axiosError = err as { response?: { status: number; data: { detail: { suggested_url: string; message: string } } } };
|
||||
if (axiosError.response?.status === 422 && axiosError.response?.data?.detail?.suggested_url) {
|
||||
// Show URL correction suggestion
|
||||
const detail = axiosError.response.data.detail;
|
||||
setFormError(
|
||||
`${detail.message}\nSuggested: ${detail.suggested_url}`
|
||||
);
|
||||
} else {
|
||||
setFormError("Failed to create repository");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleUseSuggestedUrl = () => {
|
||||
if (urlValidation.result?.base_url) {
|
||||
setFormRemoteUrl(urlValidation.result.base_url);
|
||||
setUrlValidation({ status: "idle", result: null });
|
||||
setFormError(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (repoId: string) => {
|
||||
if (!projectId) return;
|
||||
try {
|
||||
@@ -233,81 +126,13 @@ export const GitRepositoriesPage = () => {
|
||||
)}
|
||||
|
||||
{showCreate && (
|
||||
<div className="dialog-overlay" role="dialog" aria-modal="true">
|
||||
<div className="dialog">
|
||||
<h2>Create Repository</h2>
|
||||
<form onSubmit={handleSubmit} className="stack">
|
||||
<label className="form-field">
|
||||
Name
|
||||
<input
|
||||
type="text"
|
||||
value={formName}
|
||||
onChange={(e) => setFormName(e.target.value)}
|
||||
placeholder="repository-name"
|
||||
/>
|
||||
</label>
|
||||
<label className="form-field">
|
||||
Remote URL (optional)
|
||||
<input
|
||||
type="text"
|
||||
value={formRemoteUrl}
|
||||
onChange={(e) => setFormRemoteUrl(e.target.value)}
|
||||
placeholder="https://github.com/user/repo.git"
|
||||
className={getUrlInputClass()}
|
||||
/>
|
||||
{urlValidation.status === "validating" && (
|
||||
<span className="validation-status validating">Validating...</span>
|
||||
)}
|
||||
{urlValidation.status === "valid" && (
|
||||
<span className="validation-status valid">
|
||||
<Icon name="success" size="sm" /> Valid git URL
|
||||
</span>
|
||||
)}
|
||||
{urlValidation.status === "needs-parsing" && urlValidation.result && (
|
||||
<div className="url-suggestion">
|
||||
<span className="validation-status warning">
|
||||
<Icon name="warning" size="sm" /> This looks like a browser URL
|
||||
</span>
|
||||
<div className="suggestion-actions">
|
||||
<span className="suggested-url">
|
||||
Suggested: {urlValidation.result.base_url}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button small"
|
||||
onClick={handleUseSuggestedUrl}
|
||||
>
|
||||
Use Suggested
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{urlValidation.status === "invalid" && (
|
||||
<span className="validation-status invalid">
|
||||
<Icon name="error" size="sm" /> Invalid URL
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
{formError && (
|
||||
<div className="error-message">
|
||||
{formError.split("\n").map((line, i) => (
|
||||
<p key={i} className="error-text">{line}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="dialog-actions">
|
||||
<button className="secondary-button" onClick={() => setShowCreate(false)} type="button">
|
||||
<Icon name="cancel" size="sm" />
|
||||
Cancel
|
||||
</button>
|
||||
<button className="primary-button" type="submit">
|
||||
<Icon name="add" size="sm" />
|
||||
Create
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<RepositoryCreateDialog
|
||||
projectId={projectId!}
|
||||
open={showCreate}
|
||||
title="Create Repository"
|
||||
onClose={() => setShowCreate(false)}
|
||||
onCreated={loadRepositories}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -196,6 +196,7 @@ export const RepoWorkspace = () => {
|
||||
repoId={selectedRepoId}
|
||||
currentBranch={currentBranch}
|
||||
branches={branches}
|
||||
hasRemote={Boolean(selectedRepo?.remote_url)}
|
||||
onBranchChange={(branch) => {
|
||||
setCurrentBranch(branch);
|
||||
const newParams = new URLSearchParams(searchParams);
|
||||
@@ -391,4 +392,3 @@ const FileBrowser = ({
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user