Compare commits
2 Commits
6ceccbadd0
...
0ad30a212c
Author | SHA1 | Date | |
---|---|---|---|
0ad30a212c | |||
7c1079b2fd |
@ -5,6 +5,9 @@ from flask import abort
|
||||
|
||||
import requests
|
||||
|
||||
from .webgit import Gitea, Github
|
||||
from .utils import issue_sentinel, generate_sentinel
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config.from_envvar('GIT_BRIDGE_SETTINGS')
|
||||
|
||||
@ -14,6 +17,19 @@ def index():
|
||||
|
||||
@app.route("/bridge/endpoints/gitea/repo", methods=["POST"])
|
||||
def gitea_handle_repo_action():
|
||||
"""
|
||||
Our plan of action for handling these events:
|
||||
- ignore deleting repositories -- this is a potentially destructive operation
|
||||
that *only* *the* *user* *should* *do*
|
||||
- create a cooresponding repo on github
|
||||
- create a push mirror to github so pushes to gitea get to github
|
||||
- create webhooks for issues (and in the future, pull requests) on both
|
||||
Gitea and Github ends
|
||||
"""
|
||||
|
||||
gitea = Gitea(app.config["GITEA_ACCESS_TOKEN"])
|
||||
github = Github(app.config["GITHUB_ACCESS_TOKEN"])
|
||||
|
||||
data = request.json
|
||||
|
||||
try:
|
||||
@ -28,20 +44,10 @@ def gitea_handle_repo_action():
|
||||
except KeyError:
|
||||
abort(400) # the data isn't formatted correctly
|
||||
|
||||
"""
|
||||
Our plan of action for handling these events:
|
||||
- ignore deleting repositories -- this is a potentially destructive operation
|
||||
that *only* *the* *user* *should* *do*
|
||||
- create a cooresponding repo on github
|
||||
- create a push mirror to github so pushes to gitea get to github
|
||||
- create webhooks for issues (and in the future, pull requests) on both
|
||||
Gitea and Github ends
|
||||
"""
|
||||
|
||||
if not repo_action == "created":
|
||||
return ''
|
||||
|
||||
github_created_repo_result = requests.post(
|
||||
github_created_repo_result = github.post(
|
||||
"https://api.github.com/user/repos",
|
||||
json={
|
||||
"name": repo_name,
|
||||
@ -52,21 +58,11 @@ def gitea_handle_repo_action():
|
||||
repo_name,
|
||||
),
|
||||
},
|
||||
headers={
|
||||
"Accept": "application/vnd.github+json",
|
||||
"Authorization": "token " + app.config["GITHUB_ACCESS_TOKEN"],
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
github_created_repo_result.raise_for_status()
|
||||
except requests.exceptions.HTTPError:
|
||||
abort(500)
|
||||
|
||||
new_github_repo_url = github_created_repo_result.json()["html_url"]
|
||||
|
||||
gitea_add_github_repo_url_result = requests.patch(
|
||||
gitea_add_github_repo_url_result = gitea.patch(
|
||||
"https://{}/api/v1/repos/{}/{}".format(
|
||||
app.config["GITEA_INSTANCE_DOMAIN"],
|
||||
repo_owner,
|
||||
@ -75,17 +71,9 @@ def gitea_handle_repo_action():
|
||||
json={
|
||||
"website": new_github_repo_url,
|
||||
},
|
||||
headers={
|
||||
"Authorization": "token " + app.config["GITEA_ACCESS_TOKEN"],
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
gitea_add_github_repo_url_result.raise_for_status()
|
||||
except requests.exceptions.HTTPError:
|
||||
abort(500)
|
||||
|
||||
gitea_push_target_result = requests.post(
|
||||
gitea_push_target_result = gitea.post(
|
||||
"https://{}/api/v1/repos/{}/{}/push_mirrors".format(
|
||||
app.config["GITEA_INSTANCE_DOMAIN"],
|
||||
repo_owner,
|
||||
@ -98,33 +86,17 @@ def gitea_handle_repo_action():
|
||||
"remote_username": repo_owner,
|
||||
"sync_on_commit": True,
|
||||
},
|
||||
headers={
|
||||
"Authorization": "token " + app.config["GITEA_ACCESS_TOKEN"],
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
gitea_push_target_result.raise_for_status()
|
||||
except requests.exceptions.HTTPError:
|
||||
abort(500)
|
||||
|
||||
gitea_force_target_push = requests.post(
|
||||
gitea_force_target_push = gitea.post(
|
||||
"https://{}/api/v1/repos/{}/{}/push_mirrors-sync".format(
|
||||
app.config["GITEA_INSTANCE_DOMAIN"],
|
||||
repo_owner,
|
||||
repo_name
|
||||
),
|
||||
headers={
|
||||
"Authorization": "token " + app.config["GITEA_ACCESS_TOKEN"],
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
gitea_force_target_push.raise_for_status()
|
||||
except requests.exceptions.HTTPError:
|
||||
abort(500)
|
||||
|
||||
github_create_webhook_result = requests.post(
|
||||
github_create_webhook_result = github.post(
|
||||
"https://api.github.com/repos/{}/{}/hooks".format(
|
||||
repo_owner,
|
||||
repo_name,
|
||||
@ -141,19 +113,9 @@ def gitea_handle_repo_action():
|
||||
"issues", "issue_comment",
|
||||
],
|
||||
},
|
||||
headers={
|
||||
"Accept": "application/vnd.github+json",
|
||||
"Authorization": "token " + app.config["GITHUB_ACCESS_TOKEN"],
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
github_create_webhook_result.raise_for_status()
|
||||
except requests.exceptions.HTTPError:
|
||||
abort(500)
|
||||
|
||||
gitea_create_webhook_result = requests.post(
|
||||
gitea_create_webhook_result = gitea.post(
|
||||
"https://{}/api/v1/repos/{}/{}/hooks".format(
|
||||
app.config["GITEA_INSTANCE_DOMAIN"],
|
||||
repo_owner,
|
||||
@ -173,14 +135,120 @@ def gitea_handle_repo_action():
|
||||
"issues", "issue_comment",
|
||||
],
|
||||
},
|
||||
headers={
|
||||
"Authorization": "token " + app.config["GITEA_ACCESS_TOKEN"],
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
gitea_create_webhook_result.raise_for_status()
|
||||
except requests.exceptions.HTTPError:
|
||||
abort(500)
|
||||
|
||||
return ''
|
||||
return ''
|
||||
|
||||
@app.route("/bridge/endpoints/gitea/issue", methods=["POST"])
|
||||
def gitea_handle_issue_action():
|
||||
"""
|
||||
firstly, check if the sentinal is in the issue body
|
||||
- if it is, then stop processing the event
|
||||
(we don't want infinite loops)
|
||||
if we've opened an issue:
|
||||
- create a new one on the Github side
|
||||
- make it relate to the Gitea one
|
||||
- make the Gitea one related to the Github one
|
||||
|
||||
if we've commented:
|
||||
- add a comment to the cooresponding Github issue
|
||||
|
||||
if we've closed:
|
||||
- add a cooresponding comment and close the Github issue
|
||||
"""
|
||||
|
||||
gitea = Gitea(app.config["GITEA_ACCESS_TOKEN"])
|
||||
github = Github(app.config["GITHUB_ACCESS_TOKEN"])
|
||||
|
||||
data = request.json
|
||||
|
||||
try:
|
||||
event_type = data["action"]
|
||||
|
||||
repo_owner = data["repository"]["owner"]["login"]
|
||||
repo_name = data["repository"]["name"]
|
||||
issue_user = data["issue"]["user"]["login"]
|
||||
issue_user_url = "https://{}/{}".format(
|
||||
app.config["GITEA_INSTANCE_DOMAIN"],
|
||||
issue_user,
|
||||
)
|
||||
issue_number = data["issue"]["number"]
|
||||
|
||||
if event_type == "opened": # new issue created
|
||||
event_title = data["issue"]["title"]
|
||||
event_body = data["issue"]["body"]
|
||||
elif event_type == "created": # new comment on that issue
|
||||
event_title = None
|
||||
event_body = data["comment"]["body"]
|
||||
elif event_type == "closed": # issue closed
|
||||
event_title = None
|
||||
event_body = data["issue"]["body"]
|
||||
|
||||
event_url = data["issue"]["url"]
|
||||
|
||||
except KeyError as e:
|
||||
print(e, type(e))
|
||||
abort(400) # the data isn't formatted correctly
|
||||
|
||||
if "GITEA_GITHUB_ISSUE_SYNC_SENTINAL" in event_body:
|
||||
return ''
|
||||
|
||||
if event_type == "opened":
|
||||
issue_header = "*This issue has automatically been created by [`gitea-github-sync`](https://{}/bridge/about) on behalf of [{}]({}).*".format(
|
||||
app.config["GITEA_INSTANCE_DOMAIN"],
|
||||
issue_user,
|
||||
issue_user_url,
|
||||
)
|
||||
|
||||
issue_footer = """
|
||||
<details>
|
||||
<summary>Internal issue metadata</summary>
|
||||
|
||||
{}
|
||||
</details>
|
||||
""".format(generate_sentinel(event_url))
|
||||
|
||||
issue_body = "\n\n".join([
|
||||
issue_header,
|
||||
event_body,
|
||||
issue_footer
|
||||
])
|
||||
|
||||
github_create_issue_result = github.post(
|
||||
"https://api.github.com/repos/{}/{}/issues".format(
|
||||
repo_owner,
|
||||
repo_name,
|
||||
),
|
||||
json={
|
||||
"title": event_title,
|
||||
"body": issue_body,
|
||||
},
|
||||
)
|
||||
|
||||
returned_data = github_create_issue_result.json()
|
||||
issue_comment_body = """
|
||||
*This issue is being mirrored on Github [here]({}).*
|
||||
|
||||
<details>
|
||||
<summary>Internal issue metadata</summary>
|
||||
|
||||
{}
|
||||
</details>
|
||||
""".format(
|
||||
returned_data["html_url"],
|
||||
generate_sentinel(returned_data["url"])
|
||||
)
|
||||
|
||||
gitea_issue_comment_result = gitea.post(
|
||||
"https://{}/api/v1/repos/{}/{}/issues/{}/comments".format(
|
||||
app.config["GITEA_INSTANCE_DOMAIN"],
|
||||
repo_owner,
|
||||
repo_name,
|
||||
issue_number,
|
||||
),
|
||||
json={
|
||||
"body": issue_comment_body,
|
||||
},
|
||||
)
|
||||
|
||||
return ''
|
16
bridge/utils.py
Normal file
16
bridge/utils.py
Normal file
@ -0,0 +1,16 @@
|
||||
import base64
|
||||
|
||||
def to_base64(s: str) -> str:
|
||||
return base64.b64encode(
|
||||
s.encode("utf-8")
|
||||
).decode("utf-8")
|
||||
|
||||
def from_base64(s: str) -> str:
|
||||
return base64.b64decode(
|
||||
s.encode("utf-8")
|
||||
).decode("utf-8")
|
||||
|
||||
issue_sentinel = "GITEA_GITHUB_ISSUE_SYNC_SENTINEL"
|
||||
|
||||
def generate_sentinel(s: url) -> str:
|
||||
return ' '.join([sentinel, to_base64(url)])
|
65
bridge/webgit.py
Normal file
65
bridge/webgit.py
Normal file
@ -0,0 +1,65 @@
|
||||
from typing import Any
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import requests
|
||||
from requests import Request, Session
|
||||
from requests.exceptions import HTTPError
|
||||
|
||||
from flask import abort
|
||||
|
||||
@dataclass
|
||||
class WebgitClient:
|
||||
"""
|
||||
A quite thin wrapper around various code forges' REST APIs.
|
||||
Designed to be subclassed.
|
||||
"""
|
||||
api_token: str
|
||||
headers: Any = field(init=False)
|
||||
|
||||
def _post_request(self, request_obj):
|
||||
try:
|
||||
request_obj.raise_for_status()
|
||||
except HTTPError as e:
|
||||
print("An exception occured: {}({})".format(
|
||||
type(e).__name__, e
|
||||
))
|
||||
abort(500)
|
||||
|
||||
def _request_wrapper(self, method, *args, **kwargs):
|
||||
s = Session()
|
||||
r = Request(method, *args, **kwargs, headers=self.headers)
|
||||
prepped = s.prepare_request(r)
|
||||
settings = s.merge_environment_settings(prepped.url, {}, None, None, None)
|
||||
r = s.send(prepped, **settings)
|
||||
|
||||
self._post_request(r)
|
||||
return r
|
||||
|
||||
|
||||
def post(self, *args, **kwargs):
|
||||
return self._request_wrapper("POST", *args, **kwargs)
|
||||
|
||||
def patch(self, *args, **kwargs):
|
||||
return self._request_wrapper("PATCH", *args, **kwargs)
|
||||
|
||||
@dataclass
|
||||
class Github(WebgitClient):
|
||||
"""
|
||||
A quite thin wrapper around Github's REST API.
|
||||
"""
|
||||
def __post_init__(self):
|
||||
self.headers = {
|
||||
"Accept": "application/vnd.github+json",
|
||||
"Authorization": "token " + self.api_token,
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
}
|
||||
|
||||
@dataclass
|
||||
class Gitea(WebgitClient):
|
||||
"""
|
||||
A quite thin wrapper around Gitea's REST API.
|
||||
"""
|
||||
def __post_init__(self):
|
||||
self.headers = {
|
||||
"Authorization": "token " + self.api_token,
|
||||
}
|
Loading…
Reference in New Issue
Block a user