|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# DejaCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: AGPL-3.0-only |
| 5 | +# See https://github.com/aboutcode-org/dejacode for support or download. |
| 6 | +# See https://aboutcode.org for more information about AboutCode FOSS projects. |
| 7 | +# |
| 8 | + |
| 9 | +from urllib.parse import urlparse |
| 10 | + |
| 11 | +from django.conf import settings |
| 12 | + |
| 13 | +import requests |
| 14 | + |
| 15 | +GITHUB_API_URL = "https://api.github.com" |
| 16 | +DEJACODE_SITE_URL = settings.SITE_URL.rstrip("/") |
| 17 | + |
| 18 | + |
| 19 | +class GitHubIntegration: |
| 20 | + """ |
| 21 | + A class for managing GitHub issue creation, updates, and comments |
| 22 | + from DejaCode requests. |
| 23 | + """ |
| 24 | + |
| 25 | + api_url = GITHUB_API_URL |
| 26 | + default_timeout = 10 |
| 27 | + |
| 28 | + def __init__(self, dataspace): |
| 29 | + if not dataspace: |
| 30 | + raise ValueError("Dataspace must be provided.") |
| 31 | + self.dataspace = dataspace |
| 32 | + self.session = self.get_session() |
| 33 | + |
| 34 | + def get_session(self): |
| 35 | + session = requests.Session() |
| 36 | + session.headers.update(self.get_headers()) |
| 37 | + return session |
| 38 | + |
| 39 | + def get_headers(self): |
| 40 | + github_token = self.dataspace.get_configuration(field_name="github_token") |
| 41 | + if not github_token: |
| 42 | + raise ValueError("The github_token is not set on the Dataspace.") |
| 43 | + return {"Authorization": f"token {github_token}"} |
| 44 | + |
| 45 | + def sync(self, request): |
| 46 | + """Sync the given request with GitHub by creating or updating an issue.""" |
| 47 | + try: |
| 48 | + repo_id = self.extract_github_repo_path(request.request_template.issue_tracker_id) |
| 49 | + except ValueError as error: |
| 50 | + raise ValueError(f"Invalid GitHub repository URL: {error}") |
| 51 | + |
| 52 | + labels = [] |
| 53 | + if request.priority: |
| 54 | + labels.append(str(request.priority)) |
| 55 | + |
| 56 | + external_issue = request.external_issue |
| 57 | + if external_issue: |
| 58 | + self.update_issue( |
| 59 | + repo_id=repo_id, |
| 60 | + issue_id=external_issue.issue_id, |
| 61 | + title=self.make_issue_title(request), |
| 62 | + body=self.make_issue_body(request), |
| 63 | + state="closed" if request.is_closed else "open", |
| 64 | + ) |
| 65 | + else: |
| 66 | + issue = self.create_issue( |
| 67 | + repo_id=repo_id, |
| 68 | + title=self.make_issue_title(request), |
| 69 | + body=self.make_issue_body(request), |
| 70 | + labels=labels, |
| 71 | + ) |
| 72 | + request.link_external_issue( |
| 73 | + platform="github", |
| 74 | + repo=repo_id, |
| 75 | + issue_id=issue["number"], |
| 76 | + ) |
| 77 | + |
| 78 | + def create_issue(self, repo_id, title, body="", labels=None): |
| 79 | + """Create a new GitHub issue.""" |
| 80 | + url = f"{self.api_url}/repos/{repo_id}/issues" |
| 81 | + data = { |
| 82 | + "title": title, |
| 83 | + "body": body, |
| 84 | + } |
| 85 | + if labels: |
| 86 | + data["labels"] = labels |
| 87 | + |
| 88 | + response = self.session.post( |
| 89 | + url, |
| 90 | + json=data, |
| 91 | + timeout=self.default_timeout, |
| 92 | + ) |
| 93 | + response.raise_for_status() |
| 94 | + return response.json() |
| 95 | + |
| 96 | + def update_issue(self, repo_id, issue_id, title=None, body=None, state=None): |
| 97 | + """Update an existing GitHub issue.""" |
| 98 | + url = f"{self.api_url}/repos/{repo_id}/issues/{issue_id}" |
| 99 | + data = {} |
| 100 | + if title: |
| 101 | + data["title"] = title |
| 102 | + if body: |
| 103 | + data["body"] = body |
| 104 | + if state: |
| 105 | + data["state"] = state |
| 106 | + |
| 107 | + response = self.session.patch( |
| 108 | + url, |
| 109 | + json=data, |
| 110 | + timeout=self.default_timeout, |
| 111 | + ) |
| 112 | + response.raise_for_status() |
| 113 | + return response.json() |
| 114 | + |
| 115 | + def post_comment(self, repo_id, issue_id, comment_body): |
| 116 | + """Post a comment on an existing GitHub issue.""" |
| 117 | + url = f"{self.api_url}/repos/{repo_id}/issues/{issue_id}/comments" |
| 118 | + data = {"body": comment_body} |
| 119 | + |
| 120 | + response = self.session.post( |
| 121 | + url, |
| 122 | + json=data, |
| 123 | + timeout=self.default_timeout, |
| 124 | + ) |
| 125 | + response.raise_for_status() |
| 126 | + return response.json() |
| 127 | + |
| 128 | + @staticmethod |
| 129 | + def extract_github_repo_path(url): |
| 130 | + """Extract 'username/repo-name' from a GitHub URL.""" |
| 131 | + parsed = urlparse(url) |
| 132 | + if "github.com" not in parsed.netloc: |
| 133 | + raise ValueError("URL does not point to GitHub.") |
| 134 | + |
| 135 | + path_parts = [part for part in parsed.path.split("/") if part] |
| 136 | + if len(path_parts) < 2: |
| 137 | + raise ValueError("Incomplete GitHub repository path.") |
| 138 | + |
| 139 | + return f"{path_parts[0]}/{path_parts[1]}" |
| 140 | + |
| 141 | + @staticmethod |
| 142 | + def make_issue_title(request): |
| 143 | + return f"[DEJACODE] {request.title}" |
| 144 | + |
| 145 | + @staticmethod |
| 146 | + def make_issue_body(request): |
| 147 | + request_url = f"{DEJACODE_SITE_URL}{request.get_absolute_url()}" |
| 148 | + label_fields = [ |
| 149 | + ("📝 Request Template", request.request_template), |
| 150 | + ("📦 Product Context", request.product_context), |
| 151 | + ("📌 Applies To", request.content_object), |
| 152 | + ("🙋 Submitted By", request.requester), |
| 153 | + ("👤 Assigned To", request.assignee), |
| 154 | + ("🚨 Priority", request.priority), |
| 155 | + ("🗒️ Notes", request.notes), |
| 156 | + ("🔗️ DejaCode URL", request_url), |
| 157 | + ] |
| 158 | + |
| 159 | + lines = [] |
| 160 | + for label, value in label_fields: |
| 161 | + if value: |
| 162 | + lines.append(f"### {label}\n{value}") |
| 163 | + |
| 164 | + lines.append("----") |
| 165 | + |
| 166 | + for question in request.get_serialized_data_as_list(): |
| 167 | + label = question.get("label") |
| 168 | + value = question.get("value") |
| 169 | + input_type = question.get("input_type") |
| 170 | + |
| 171 | + if input_type == "BooleanField": |
| 172 | + value = "Yes" if str(value).lower() in ("1", "true", "yes") else "No" |
| 173 | + |
| 174 | + lines.append(f"### {label}\n{value}") |
| 175 | + |
| 176 | + return "\n\n".join(lines) |
0 commit comments