Compare commits

...

2 Commits

Author SHA1 Message Date
吴舒先 33a3763410 合并远程 2024-07-10 00:33:52 +08:00
吴舒先 eb61024190 添加issue相关配置 2024-07-10 00:30:39 +08:00
3 changed files with 143 additions and 5 deletions

View File

@ -10,7 +10,7 @@ import src.api.Log
import src.api.Auth
import src.api.Sync_config
from extras.obfastapi.frame import OBFastAPI
from src.router import CE_ROBOT, PROJECT, JOB, ACCOUNT, PULL_REQUEST, USER, LOG, AUTH, SYNC_CONFIG
from src.router import CE_ROBOT, PROJECT, JOB, ACCOUNT, PULL_REQUEST, USER, LOG, AUTH, SYNC_CONFIG, ISSUES
from fastapi.staticfiles import StaticFiles
app = OBFastAPI()
@ -24,6 +24,7 @@ app.include_router(USER)
app.include_router(LOG)
app.include_router(AUTH)
app.include_router(SYNC_CONFIG)
app.include_router(ISSUES)
app.mount("/", StaticFiles(directory="web/dist"), name="static")

View File

@ -5,9 +5,11 @@ from fastapi import (
Query,
Depends,
Security,
Body
Body,
requests
)
from typing import Optional
import requests
from starlette.exceptions import HTTPException
@ -17,11 +19,13 @@ from extras.obfastapi.frame import OBResponse as Response
from src.base.code import Code
from src.base.error_code import ErrorTemplate, Errors
from src.router import PULL_REQUEST as pull_request
from src.router import ISSUES as issues
from src.api.Controller import APIController as Controller
from src.dto.pull_request import PullRequest as PullRequestData
from src.service.pull_request import PullRequestService
from src.service.sync import ProjectService
from src.utils import github
from src.utils import gitee
class PullRequest(Controller):
@ -36,10 +40,11 @@ class PullRequest(Controller):
search: Optional[str] = Query(None, description='搜索内容'),
orderby: Optional[str] = Query(None, description='排序选项')
):
# 项目是否存在
await self._check_project(name)
pull_request_service = PullRequestService()
count = await pull_request_service.count_pull_request(name)
answer = await pull_request_service.fetch_pull_request(name)
answer = await pull_request_service.fetch_pull_request(name) # 获取所有PR信息从哪里
if not answer:
logger.info(f"The project {name} has no pull request")
answer = []
@ -48,20 +53,25 @@ class PullRequest(Controller):
data=DataList(total=count, list=answer)
)
@pull_request.get("/projects/{name}/pullrequests/sync", response_model=Response, description='列出pull request')
@pull_request.get("/projects/{name}/pullrequests/sync", response_model=Response, description='同步pull request')
async def sync_pull_request(
self,
name: str = Query(..., description='工程名字')
):
# 项目是否存在查sync_project表,同时获取数据库中的一条完整记录
resp = await self._check_project(name)
# 解析 resp 获取需要的信息(仓库地址、名字等)
organization, repo = github.transfer_github_to_name(
resp[0].github_address)
# 如果仓库存在,执行同步操作
if organization and repo:
pull_request_service = PullRequestService()
await pull_request_service.sync_pull_request(name, organization, repo)
else:
# 否则抛出异常
logger.error(f"The pull rquest of project {name} sync failed")
raise Errors.QUERY_FAILD
# 返回响应信息
return Response(
code=Code.SUCCESS,
msg="发送同意请求成功"
@ -173,9 +183,61 @@ class PullRequest(Controller):
async def _check_project(self, name: str):
project_service = ProjectService()
resp = await project_service.search_project(name=name)
resp = await project_service.search_project(name=name) # 从sync_project中查询项目是否存在
if len(resp) == 0:
logger.error(
f"The project {name} is not exist")
raise Errors.QUERY_FAILD
return resp
@pull_request.get("/projects/{name}/pullrequests/", description='获取指定仓库的PR')
async def fetch_pull_request(
self,
domain: str = Query(..., description='平台'),
owner: str = Query(..., description='仓库所有者'),
repo: str = Query(..., description='仓库名称'),
token: str = Query(..., description='用户token'),
state: str = Query(None, description='可选PR的状态'),
):
try:
if 'gitee' in domain:
if state:
url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/pulls?state={state}'
else:
url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/pulls'
elif 'gitlink' in domain:
url = f'https://www.gitlink.org.cn/api/v1/{owner}/{repo}/pulls.json'
headers = {
'Authorization': f'token {token}'
}
response = requests.get(url, headers=headers)
response.raise_for_status() # 如果请求返回了不成功的状态码,就会产生一个 HTTPError 异常。
return response.json()
except requests.HTTPError as errh:
raise HTTPException(status_code=400, detail=str(errh))
except requests.RequestException as err:
raise HTTPException(status_code=500, detail=str(err))
@pull_request.get("/projects/{name}/pullrequests/test", description='测试接口')
async def testInterface(
self,
token: str = Query(..., description='用户授权码'),
owner: str = Query(..., description='仓库所有者'),
repo: str = Query(..., description='仓库名称'),
state: str = Query(None, description='可选PR的状态'),
):
return gitee.fetch_gitee_pull_request(token, owner, repo, state)
class Issues(Controller):
def get_user(self, cookie_key=Security(Controller.API_KEY_BUC_COOKIE), token: str = None):
return super().get_user(cookie_key=cookie_key, token=token)
@issues.get("/fetch/issues", description='获取issues列表')
async def get_issues(
self,
owner: str = Query(..., description= '仓库所有者'),
repo: str = Query(..., description='仓库名称')
):
issue_list = gitee.fetch_gitee_issues(owner, repo)
return issue_list

View File

@ -1,6 +1,9 @@
import re
import requests
from typing import Optional
from fastapi import HTTPException
from src.base import config
from src.utils.logger import logger
@ -37,3 +40,75 @@ def get_gitee_address_with_token(http_address: str, token: str) -> str:
return http_address[:8] + owner_name + ":" + token + '@' + http_address[8:]
except Exception as e:
print(e)
def fetch_gitee_pull_request(token: str, owner: str, repo: str, state: str = None):
"""
获取指定仓库的PR数据
Attributes
token 用户授权码
owner 仓库拥有者
repo 仓库名称
state 可选PR的状态
"""
# 根据state决定request的地址
if state:
url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/pulls?state={state}'
else:
url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/pulls'
# 请求头的内容
headers = {
'Authorization': f'token {token}'
}
response = requests.get(url, headers=headers)
pull_requests = response.json()
data = []
for pull_request in pull_requests:
data_item = {
'pull_request_id': pull_request['id'],
'project': repo,
'title': pull_request['title'],
'type': 'Gitee',
'address': pull_request['html_url'],
'author': pull_request['user']['login'],
'email': None,
'target_branch': pull_request['base']['ref'],
'latest_commit': pull_request['head']['sha'],
'inline': pull_request['base']['repo']['internal'],
}
data.append(data_item)
return data
def create_pull_request(owner: str, repo: str, title: str, head: str, base: str):
"""
创建一个合并请求
Attributes:
owner 仓库拥有者
repo 仓库名称
title PR的标题
head PR提交的源分支
base PR的目标分支
"""
pass
def fetch_gitee_issues(owner: str, repo: str):
url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/issues'
response = requests.get(url)
issues = response.json()
issue_list = []
for issue in issues:
state = 1
if issue['state'] == 'progressing':
state = 2
elif issue['state'] == 'closed':
state = 5
elif issue['state'] == 'rejected':
state = 6
issue_item = {
'status_id': state,
'priority_id': 1,
'subject': issue['title'],
'description': issue['body']
}
issue_list.append(issue_item)
return issue_list