Simplify API

This commit is contained in:
Stéphane Bidoul 2021-11-01 00:02:34 +01:00
parent daa920c845
commit a2ed957819
No known key found for this signature in database
GPG key ID: BCAB2555446B5B92
4 changed files with 33 additions and 78 deletions

View file

@ -52,18 +52,6 @@ class Build(BaseModel):
read_with_orm_mode = True read_with_orm_mode = True
class BranchOrPull(BaseModel):
repo: str
target_branch: str
pr: Optional[int]
link: str
builds: list[Build]
class Config:
orm_mode = True
read_with_orm_mode = True
@router.get("/status", response_model=Status) @router.get("/status", response_model=Status)
async def controller_status(): async def controller_status():
return controller return controller
@ -75,25 +63,24 @@ async def repos():
@router.get( @router.get(
"/repos/{org}/{repo}/branches-and-pulls", "/builds",
response_model=list[BranchOrPull], response_model=list[Build],
response_model_exclude_none=True, response_model_exclude_none=True,
) )
async def branches_and_pulls(org: str, repo: str): async def builds(repo: Optional[str] = None):
return controller.db.branches_and_pulls(f"{org}/{repo}") return controller.db.search(repo)
@router.post( @router.post(
"/repos/{org}/{repo}/branches/{branch}/trigger", "/builds/trigger/branch",
response_model=Build,
dependencies=[Depends(authenticated)], dependencies=[Depends(authenticated)],
) )
async def trigger_branch(org: str, repo: str, branch: str): async def trigger_branch(repo: str, branch: str):
"""Trigger build for a branch.""" """Trigger build for a branch."""
# TODO async github call # TODO async github call
branch_info = github.get_branch_info(org, repo, branch) branch_info = github.get_branch_info(repo, branch)
await controller.deploy_or_delay_start( await controller.deploy_or_delay_start(
repo=f"{branch_info.org}/{branch_info.repo}", repo=branch_info.repo,
target_branch=branch_info.name, target_branch=branch_info.name,
pr=None, pr=None,
git_commit=branch_info.head_sha, git_commit=branch_info.head_sha,
@ -101,16 +88,15 @@ async def trigger_branch(org: str, repo: str, branch: str):
@router.post( @router.post(
"/repos/{org}/{repo}/pulls/{pr}/trigger", "/builds/trigger/pr",
response_model=Build,
dependencies=[Depends(authenticated)], dependencies=[Depends(authenticated)],
) )
async def trigger_pull(org: str, repo: str, pr: int): async def trigger_pull(repo: str, pr: int):
"""Trigger build for a pull request.""" """Trigger build for a pull request."""
# TODO async github call # TODO async github call
pull_info = github.get_pull_info(org, repo, pr) pull_info = github.get_pull_info(repo, pr)
await controller.deploy_or_delay_start( await controller.deploy_or_delay_start(
repo=f"{pull_info.org}/{pull_info.repo}", repo=pull_info.repo,
target_branch=pull_info.target_branch, target_branch=pull_info.target_branch,
pr=pull_info.number, pr=pull_info.number,
git_commit=pull_info.head_sha, git_commit=pull_info.head_sha,

View file

@ -1,7 +1,8 @@
import logging import logging
import sqlite3 import sqlite3
from typing import Optional
from .models import BranchOrPull, Build, BuildInitStatus, BuildStatus from .models import Build, BuildInitStatus, BuildStatus
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -166,27 +167,15 @@ class BuildsDb:
).fetchall() ).fetchall()
return [self._build_from_row(row) for row in rows] return [self._build_from_row(row) for row in rows]
def branches_and_pulls(self, repo: str) -> list[BranchOrPull]: def search(self, repo: Optional[str] = None) -> list[Build]:
res = [] query = "SELECT * FROM builds "
branch_or_pull: BranchOrPull | None = None where = []
for row in self._con.execute( params = []
"SELECT * FROM builds WHERE repo=?" if repo:
"ORDER BY target_branch, pr, created DESC", where.append("repo=?")
(repo.lower(),), params.append(repo.lower())
).fetchall(): if where:
build = self._build_from_row(row) query += "WHERE " + " AND ".join(where)
if ( query += "ORDER BY repo, target_branch, pr, created DESC"
branch_or_pull is None rows = self._con.execute(query, params).fetchall()
or branch_or_pull.repo != build.repo return [self._build_from_row(row) for row in rows]
or branch_or_pull.target_branch != build.target_branch
or branch_or_pull.pr != build.pr
):
branch_or_pull = BranchOrPull(
repo=build.repo,
target_branch=build.target_branch,
pr=build.pr,
builds=[],
)
res.append(branch_or_pull)
branch_or_pull.builds.append(build)
return res

View file

@ -24,16 +24,14 @@ def _github_get(url: str) -> Any:
@dataclass @dataclass
class BranchInfo: class BranchInfo:
org: str
repo: str repo: str
name: str name: str
head_sha: str head_sha: str
def get_branch_info(org: str, repo: str, branch: str) -> BranchInfo: def get_branch_info(repo: str, branch: str) -> BranchInfo:
branch_data = _github_get(f"/repos/{org}/{repo}/git/ref/heads/{branch}") branch_data = _github_get(f"/repos/{repo}/git/ref/heads/{branch}")
return BranchInfo( return BranchInfo(
org=org,
repo=repo, repo=repo,
name=branch, name=branch,
head_sha=branch_data["object"]["sha"], head_sha=branch_data["object"]["sha"],
@ -42,17 +40,15 @@ def get_branch_info(org: str, repo: str, branch: str) -> BranchInfo:
@dataclass @dataclass
class PullInfo: class PullInfo:
org: str
repo: str repo: str
number: int number: int
head_sha: str head_sha: str
target_branch: str target_branch: str
def get_pull_info(org: str, repo: str, pr: int) -> PullInfo: def get_pull_info(repo: str, pr: int) -> PullInfo:
pr_data = _github_get(f"/repos/{org}/{repo}/pulls/{pr}") pr_data = _github_get(f"/repos/{repo}/pulls/{pr}")
return PullInfo( return PullInfo(
org=org,
repo=repo, repo=repo,
number=pr, number=pr,
head_sha=pr_data["head"]["sha"], head_sha=pr_data["head"]["sha"],

View file

@ -45,6 +45,9 @@ class Build(BaseModel):
last_scaled: datetime.datetime last_scaled: datetime.datetime
created: datetime.datetime created: datetime.datetime
class Config:
read_with_orm_mode = True
def __str__(self) -> str: def __str__(self) -> str:
return f"{self.slug} ({self.name})" return f"{self.slug} ({self.name})"
@ -290,22 +293,3 @@ class Repo(BaseModel):
class Config: class Config:
read_with_orm_mode = True read_with_orm_mode = True
class BranchOrPull(BaseModel):
repo: str
target_branch: str
pr: Optional[int]
builds: list[Build]
class Config:
read_with_orm_mode = True
@property
def link(self) -> str:
link = f"https://github.com/{self.repo}"
if self.pr:
link = f"{link}/pull/{self.pr}"
else:
link = f"{link}/tree/{self.target_branch}"
return link