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")
|
||||
Reference in New Issue
Block a user