feat: Add advanced features and final updates before deployment, implemeted topic OR logic for github issue search to broaden results
Browse files- core/github_client.py +123 -143
core/github_client.py
CHANGED
@@ -1,22 +1,16 @@
|
|
1 |
import requests
|
2 |
-
import os
|
3 |
-
# from urllib.parse import quote # We are letting requests handle most param encoding
|
4 |
|
5 |
-
|
6 |
-
from utils.config_loader import GITHUB_PAT # Make sure this path is correct for your setup
|
7 |
|
8 |
BASE_SEARCH_URL = "https://api.github.com/search/issues"
|
9 |
BASE_REPO_URL = "https://api.github.com/repos"
|
10 |
|
11 |
def _make_github_request(url: str, params: dict = None, headers: dict = None) -> dict | None:
|
12 |
-
|
13 |
-
Helper function to make authenticated GitHub API GET requests expecting JSON response.
|
14 |
-
Handles potential request errors.
|
15 |
-
"""
|
16 |
if not GITHUB_PAT:
|
17 |
print("ERROR (github_client._make_github_request): GITHUB_PAT is not configured.")
|
18 |
return None
|
19 |
-
|
20 |
default_headers = {
|
21 |
"Authorization": f"token {GITHUB_PAT}",
|
22 |
"Accept": "application/vnd.github.v3+json",
|
@@ -24,125 +18,148 @@ def _make_github_request(url: str, params: dict = None, headers: dict = None) ->
|
|
24 |
}
|
25 |
if headers:
|
26 |
default_headers.update(headers)
|
27 |
-
|
28 |
try:
|
29 |
-
|
30 |
-
response = requests.get(url, headers=default_headers, params=params, timeout=15) # Increased timeout slightly
|
31 |
response.raise_for_status()
|
32 |
-
return response.json()
|
33 |
except requests.exceptions.Timeout:
|
34 |
print(f"ERROR (github_client._make_github_request): GitHub API request timed out for URL: {url}")
|
35 |
return None
|
36 |
except requests.exceptions.HTTPError as http_err:
|
37 |
-
# Log specific error details, especially for common issues like 401, 403, 404, 422
|
38 |
error_message = f"ERROR (github_client._make_github_request): GitHub API HTTP error for URL {url}: {http_err}."
|
39 |
try:
|
40 |
-
# Attempt to get more detailed error message from GitHub's JSON response
|
41 |
error_details = http_err.response.json()
|
42 |
error_message += f" Details: {error_details.get('message', 'No specific message')} Docs: {error_details.get('documentation_url', 'N/A')}"
|
43 |
-
except ValueError:
|
44 |
error_message += f" Response: {http_err.response.text}"
|
45 |
print(error_message)
|
46 |
-
return None
|
47 |
except requests.exceptions.RequestException as req_err:
|
48 |
print(f"ERROR (github_client._make_github_request): GitHub API request failed for URL {url}: {req_err}")
|
49 |
return None
|
50 |
-
except ValueError as json_err:
|
51 |
print(f"ERROR (github_client._make_github_request): Failed to decode JSON response from URL {url}: {json_err}")
|
52 |
return None
|
53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
def fetch_beginner_issues(
|
55 |
language: str,
|
56 |
topics: list[str] | None = None,
|
57 |
-
labels: list[str] | None = None,
|
58 |
sort: str = "updated",
|
59 |
order: str = "desc",
|
60 |
per_page: int = 10,
|
61 |
page: int = 1
|
62 |
) -> list[dict] | None:
|
63 |
"""
|
64 |
-
Fetches beginner-friendly issues
|
65 |
-
|
|
|
66 |
"""
|
67 |
if not language:
|
68 |
print("ERROR (github_client.fetch_beginner_issues): Language parameter is required.")
|
69 |
return None
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
else:
|
84 |
-
# No topics specified, cast a slightly wider net with labels.
|
85 |
-
current_labels_to_use = ["good first issue", "help wanted", "beginner", "first-timers-only"]
|
86 |
-
print(f"GitHub Client: No topics specified, using broader default labels: {current_labels_to_use}")
|
87 |
-
|
88 |
-
query_parts = [
|
89 |
-
f"language:{language.strip().lower()}", # Normalize language
|
90 |
-
"state:open",
|
91 |
-
"is:issue",
|
92 |
-
"is:public"
|
93 |
-
]
|
94 |
-
|
95 |
-
# Add label query parts only if current_labels_to_use is not empty
|
96 |
-
if current_labels_to_use:
|
97 |
-
for label_name in current_labels_to_use:
|
98 |
-
if label_name.strip(): # Ensure label is not just whitespace
|
99 |
-
query_parts.append(f'label:"{label_name.strip()}"')
|
100 |
-
else: # If current_labels_to_use ended up empty (e.g., if explicitly passed as []), don't add label filter
|
101 |
-
print("GitHub Client: No labels will be applied to the search query.")
|
102 |
|
103 |
-
|
104 |
-
# Add topics to query if provided
|
105 |
if topics:
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
-
if data and "items" in data:
|
121 |
-
issues_list = []
|
122 |
-
for item in data["items"]:
|
123 |
-
repo_html_url = "/".join(item.get("html_url", "").split('/')[:5])
|
124 |
-
issues_list.append({
|
125 |
-
"title": item.get("title"), "html_url": item.get("html_url"),
|
126 |
-
"state": item.get("state"), "number": item.get("number"),
|
127 |
-
"created_at": item.get("created_at"), "updated_at": item.get("updated_at"),
|
128 |
-
"labels": [label_item.get("name") for label_item in item.get("labels", [])],
|
129 |
-
"repository_api_url": item.get("repository_url"),
|
130 |
-
"repository_html_url": repo_html_url,
|
131 |
-
"user_login": item.get("user", {}).get("login"),
|
132 |
-
"body_snippet": item.get("body", "")[:300] + "..." if item.get("body") else "No body provided."
|
133 |
-
})
|
134 |
-
return issues_list
|
135 |
-
elif data and "items" not in data:
|
136 |
-
print(f"GitHub Client: No 'items' in API response for query '{q_string}'. API Message: {data.get('message', 'N/A')}")
|
137 |
-
return []
|
138 |
-
return None
|
139 |
|
140 |
|
141 |
def get_repository_details(repo_api_url: str) -> dict | None:
|
142 |
-
|
143 |
-
Fetches details for a specific repository using its API URL.
|
144 |
-
Primarily used to get the default_branch.
|
145 |
-
"""
|
146 |
if not repo_api_url:
|
147 |
print("ERROR (github_client.get_repository_details): No repository API URL provided.")
|
148 |
return None
|
@@ -151,14 +168,10 @@ def get_repository_details(repo_api_url: str) -> dict | None:
|
|
151 |
|
152 |
|
153 |
def get_file_url_from_repo(repo_full_name: str, file_paths_to_check: list[str], default_branch: str | None = None) -> str | None:
|
154 |
-
|
155 |
-
Checks for the existence of a file in a list of possible paths within a repository
|
156 |
-
and returns its HTML URL if found.
|
157 |
-
"""
|
158 |
if not repo_full_name or not file_paths_to_check:
|
159 |
print("ERROR (github_client.get_file_url_from_repo): repo_full_name and file_paths_to_check are required.")
|
160 |
return None
|
161 |
-
|
162 |
branch_to_use = default_branch
|
163 |
if not branch_to_use:
|
164 |
print(f"GitHub Client (get_file_url): No default branch provided for {repo_full_name}, attempting to fetch it.")
|
@@ -169,47 +182,27 @@ def get_file_url_from_repo(repo_full_name: str, file_paths_to_check: list[str],
|
|
169 |
print(f"GitHub Client (get_file_url): Fetched default branch '{branch_to_use}' for {repo_full_name}.")
|
170 |
else:
|
171 |
print(f"GitHub Client (get_file_url): Could not determine default branch for {repo_full_name}. Will try common fallbacks.")
|
172 |
-
# If default branch still not found, function will iterate through fallbacks next.
|
173 |
-
|
174 |
-
# Define branches to try: the determined/passed one, then common fallbacks if needed.
|
175 |
branches_to_attempt = []
|
176 |
-
if branch_to_use:
|
177 |
-
|
178 |
-
|
179 |
-
if not branch_to_use: # Only add fallbacks if we couldn't determine one
|
180 |
-
branches_to_attempt.extend(["main", "master"])
|
181 |
-
|
182 |
-
|
183 |
for current_branch_attempt in branches_to_attempt:
|
184 |
print(f"GitHub Client (get_file_url): Trying branch '{current_branch_attempt}' for {repo_full_name}.")
|
185 |
for file_path in file_paths_to_check:
|
186 |
file_api_url = f"{BASE_REPO_URL}/{repo_full_name}/contents/{file_path}?ref={current_branch_attempt}"
|
187 |
-
|
188 |
-
file_metadata = _make_github_request(file_api_url) # This expects JSON
|
189 |
if file_metadata and isinstance(file_metadata, dict) and file_metadata.get("html_url"):
|
190 |
print(f"GitHub Client (get_file_url): Found '{file_path}' in {repo_full_name} on branch '{current_branch_attempt}'.")
|
191 |
return file_metadata.get("html_url")
|
192 |
-
# else: # No need to print "not found" for every path/branch combination, becomes too noisy.
|
193 |
-
# _make_github_request will print if it's a 404 or other HTTP error.
|
194 |
-
|
195 |
print(f"GitHub Client (get_file_url): Could not find any of {file_paths_to_check} in {repo_full_name} on attempted branches.")
|
196 |
return None
|
197 |
|
198 |
-
|
199 |
def get_file_content(repo_full_name: str, file_path: str, branch: str | None = None) -> str | None:
|
200 |
-
|
201 |
-
Fetches the raw text content of a specific file from a repository.
|
202 |
-
Args:
|
203 |
-
repo_full_name: The repository name in "owner/repo" format.
|
204 |
-
file_path: The path to the file within the repository (e.g., "CONTRIBUTING.md").
|
205 |
-
branch: The branch to fetch from. If None, attempts to find default branch.
|
206 |
-
Returns:
|
207 |
-
The text content of the file, or None if not found or an error occurs.
|
208 |
-
"""
|
209 |
if not repo_full_name or not file_path:
|
210 |
print("ERROR (github_client.get_file_content): repo_full_name and file_path are required.")
|
211 |
return None
|
212 |
-
|
213 |
current_branch = branch
|
214 |
if not current_branch:
|
215 |
print(f"GitHub Client (get_file_content): No branch specified for {repo_full_name}/{file_path}, finding default.")
|
@@ -219,50 +212,37 @@ def get_file_content(repo_full_name: str, file_path: str, branch: str | None = N
|
|
219 |
current_branch = repo_details.get("default_branch")
|
220 |
print(f"GitHub Client (get_file_content): Using default branch '{current_branch}' for {repo_full_name}/{file_path}")
|
221 |
else:
|
222 |
-
# Try common fallbacks if default cannot be determined
|
223 |
print(f"GitHub Client (get_file_content): Could not determine default branch for {repo_full_name}. Trying 'main', then 'master' for {file_path}.")
|
224 |
-
|
225 |
-
current_branch = "main"
|
226 |
-
# If 'main' fails, we could try 'master' subsequently, but let's try one at a time.
|
227 |
-
# The request below will try current_branch. If it fails with 404, we could then retry with 'master'.
|
228 |
-
# For now, let's simplify: try determined default, else 'main'. If that 404s, the user gets None.
|
229 |
-
|
230 |
file_api_url = f"{BASE_REPO_URL}/{repo_full_name}/contents/{file_path}?ref={current_branch}"
|
231 |
print(f"GitHub Client (get_file_content): Fetching raw content for '{file_path}' from '{repo_full_name}' on branch '{current_branch}'.")
|
232 |
-
|
233 |
if not GITHUB_PAT:
|
234 |
print("ERROR (github_client.get_file_content): GITHUB_PAT is not configured.")
|
235 |
return None
|
236 |
-
|
237 |
headers = {
|
238 |
"Authorization": f"token {GITHUB_PAT}",
|
239 |
-
"Accept": "application/vnd.github.raw",
|
240 |
"X-GitHub-Api-Version": "2022-11-28"
|
241 |
}
|
242 |
-
|
243 |
try:
|
244 |
-
response = requests.get(file_api_url, headers=headers, timeout=15)
|
245 |
response.raise_for_status()
|
246 |
-
return response.text
|
247 |
-
except requests.exceptions.Timeout:
|
248 |
-
print(f"ERROR (github_client.get_file_content): GitHub API request timed out for URL: {file_api_url}")
|
249 |
-
return None
|
250 |
except requests.exceptions.HTTPError as http_err:
|
251 |
if http_err.response.status_code == 404:
|
252 |
print(f"INFO (github_client.get_file_content): File not found (404) at {file_api_url}")
|
253 |
-
|
254 |
-
if current_branch == "main" and (not branch or branch == "main"): # Check if we already tried specific branch or if 'main' was a fallback
|
255 |
print(f"GitHub Client (get_file_content): '{file_path}' not found on 'main', trying 'master' as fallback.")
|
256 |
-
return get_file_content(repo_full_name, file_path, branch="master")
|
257 |
else:
|
258 |
error_message = f"ERROR (github_client.get_file_content): GitHub API HTTP error for URL {file_api_url}: {http_err}."
|
259 |
try:
|
260 |
-
error_details = http_err.response.json()
|
261 |
error_message += f" Details: {error_details.get('message', http_err.response.text)}"
|
262 |
except ValueError:
|
263 |
error_message += f" Response: {http_err.response.text}"
|
264 |
print(error_message)
|
265 |
return None
|
266 |
-
except
|
267 |
-
print(f"ERROR (github_client.get_file_content):
|
268 |
return None
|
|
|
1 |
import requests
|
2 |
+
import os
|
|
|
3 |
|
4 |
+
from utils.config_loader import GITHUB_PAT
|
|
|
5 |
|
6 |
BASE_SEARCH_URL = "https://api.github.com/search/issues"
|
7 |
BASE_REPO_URL = "https://api.github.com/repos"
|
8 |
|
9 |
def _make_github_request(url: str, params: dict = None, headers: dict = None) -> dict | None:
|
10 |
+
|
|
|
|
|
|
|
11 |
if not GITHUB_PAT:
|
12 |
print("ERROR (github_client._make_github_request): GITHUB_PAT is not configured.")
|
13 |
return None
|
|
|
14 |
default_headers = {
|
15 |
"Authorization": f"token {GITHUB_PAT}",
|
16 |
"Accept": "application/vnd.github.v3+json",
|
|
|
18 |
}
|
19 |
if headers:
|
20 |
default_headers.update(headers)
|
|
|
21 |
try:
|
22 |
+
response = requests.get(url, headers=default_headers, params=params, timeout=15)
|
|
|
23 |
response.raise_for_status()
|
24 |
+
return response.json()
|
25 |
except requests.exceptions.Timeout:
|
26 |
print(f"ERROR (github_client._make_github_request): GitHub API request timed out for URL: {url}")
|
27 |
return None
|
28 |
except requests.exceptions.HTTPError as http_err:
|
|
|
29 |
error_message = f"ERROR (github_client._make_github_request): GitHub API HTTP error for URL {url}: {http_err}."
|
30 |
try:
|
|
|
31 |
error_details = http_err.response.json()
|
32 |
error_message += f" Details: {error_details.get('message', 'No specific message')} Docs: {error_details.get('documentation_url', 'N/A')}"
|
33 |
+
except ValueError:
|
34 |
error_message += f" Response: {http_err.response.text}"
|
35 |
print(error_message)
|
36 |
+
return None
|
37 |
except requests.exceptions.RequestException as req_err:
|
38 |
print(f"ERROR (github_client._make_github_request): GitHub API request failed for URL {url}: {req_err}")
|
39 |
return None
|
40 |
+
except ValueError as json_err:
|
41 |
print(f"ERROR (github_client._make_github_request): Failed to decode JSON response from URL {url}: {json_err}")
|
42 |
return None
|
43 |
|
44 |
+
|
45 |
+
def _construct_label_query(labels_list: list[str]) -> str:
|
46 |
+
"""Constructs a single, comma-separated string for OR logic on labels."""
|
47 |
+
if not labels_list:
|
48 |
+
return ""
|
49 |
+
|
50 |
+
# Quote any labels that contain spaces
|
51 |
+
quoted_labels = []
|
52 |
+
for label in labels_list:
|
53 |
+
clean_label = label.strip()
|
54 |
+
if " " in clean_label:
|
55 |
+
quoted_labels.append(f'"{clean_label}"')
|
56 |
+
else:
|
57 |
+
quoted_labels.append(clean_label)
|
58 |
+
|
59 |
+
# Return in the format: label:label1,"label two",label3
|
60 |
+
return f'label:{",".join(quoted_labels)}'
|
61 |
+
|
62 |
+
|
63 |
+
|
64 |
+
|
65 |
def fetch_beginner_issues(
|
66 |
language: str,
|
67 |
topics: list[str] | None = None,
|
68 |
+
labels: list[str] | None = None,
|
69 |
sort: str = "updated",
|
70 |
order: str = "desc",
|
71 |
per_page: int = 10,
|
72 |
page: int = 1
|
73 |
) -> list[dict] | None:
|
74 |
"""
|
75 |
+
Fetches beginner-friendly issues. If multiple topics are provided, it
|
76 |
+
searches for each topic individually (OR logic). Labels are also combined
|
77 |
+
with OR logic.
|
78 |
"""
|
79 |
if not language:
|
80 |
print("ERROR (github_client.fetch_beginner_issues): Language parameter is required.")
|
81 |
return None
|
82 |
|
83 |
+
def _parse_issue_item(item: dict) -> dict:
|
84 |
+
repo_html_url = "/".join(item.get("html_url", "").split('/')[:5])
|
85 |
+
return {
|
86 |
+
"title": item.get("title"), "html_url": item.get("html_url"),
|
87 |
+
"state": item.get("state"), "number": item.get("number"),
|
88 |
+
"created_at": item.get("created_at"), "updated_at": item.get("updated_at"),
|
89 |
+
"labels": [label_item.get("name") for label_item in item.get("labels", [])],
|
90 |
+
"repository_api_url": item.get("repository_url"),
|
91 |
+
"repository_html_url": repo_html_url,
|
92 |
+
"user_login": item.get("user", {}).get("login"),
|
93 |
+
"body_snippet": item.get("body", "")[:300] + "..." if item.get("body") else "No body provided."
|
94 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
|
|
|
|
96 |
if topics:
|
97 |
+
print(f"GitHub Client: Performing OR search for topics: {topics}")
|
98 |
+
all_issues_map = {}
|
99 |
+
per_topic_per_page = max(3, per_page // len(topics) if len(topics) > 0 else per_page)
|
100 |
+
|
101 |
+
current_labels_to_use = ["good first issue", "help wanted"] if labels is None else labels
|
102 |
+
label_query_part = _construct_label_query(current_labels_to_use)
|
103 |
+
|
104 |
+
for topic in topics:
|
105 |
+
query_parts = [
|
106 |
+
f"language:{language.strip().lower()}", "state:open", "is:issue", "is:public"
|
107 |
+
]
|
108 |
+
if label_query_part: query_parts.append(label_query_part)
|
109 |
+
|
110 |
+
topic_name = topic.strip().lower()
|
111 |
+
if " " in topic_name: query_parts.append(f'topic:"{topic_name}"')
|
112 |
+
else: query_parts.append(f'topic:{topic_name}')
|
113 |
+
|
114 |
+
q_string = " ".join(query_parts)
|
115 |
+
params = {"q": q_string, "sort": sort, "order": order, "per_page": int(per_topic_per_page), "page": page}
|
116 |
+
|
117 |
+
print(f"GitHub Client: Fetching for sub-query: '{q_string}'")
|
118 |
+
data = _make_github_request(BASE_SEARCH_URL, params=params)
|
119 |
+
|
120 |
+
if data and "items" in data:
|
121 |
+
for item in data["items"]:
|
122 |
+
issue_url = item.get("html_url")
|
123 |
+
if issue_url and issue_url not in all_issues_map:
|
124 |
+
all_issues_map[issue_url] = _parse_issue_item(item)
|
125 |
+
|
126 |
+
combined_issues = list(all_issues_map.values())
|
127 |
+
combined_issues.sort(key=lambda x: x.get('updated_at', ''), reverse=(order == 'desc'))
|
128 |
+
|
129 |
+
print(f"GitHub Client: Combined and de-duplicated {len(combined_issues)} issues from topic search.")
|
130 |
+
return combined_issues[:per_page]
|
131 |
+
|
132 |
+
else:
|
133 |
+
print("GitHub Client: Performing search with no topics specified.")
|
134 |
+
default_labels = [
|
135 |
+
"good first issue", "help wanted", "beginner", "first-timers-only",
|
136 |
+
"contributions welcome", "contribution", "contribute"
|
137 |
+
] if labels is None else labels
|
138 |
+
|
139 |
+
label_query_part = _construct_label_query(default_labels)
|
140 |
+
|
141 |
+
query_parts = [
|
142 |
+
f"language:{language.strip().lower()}", "state:open", "is:issue", "is:public"
|
143 |
+
]
|
144 |
+
if label_query_part: query_parts.append(label_query_part)
|
145 |
+
|
146 |
+
q_string = " ".join(query_parts)
|
147 |
+
params = {"q": q_string, "sort": sort, "order": order, "per_page": per_page, "page": page}
|
148 |
+
|
149 |
+
print(f"GitHub Client: Fetching with q_string: '{q_string}'")
|
150 |
+
data = _make_github_request(BASE_SEARCH_URL, params=params)
|
151 |
+
|
152 |
+
if data and "items" in data:
|
153 |
+
return [_parse_issue_item(item) for item in data["items"]]
|
154 |
+
elif data and "items" not in data:
|
155 |
+
print(f"GitHub Client: No 'items' in API response for query '{q_string}'. API Message: {data.get('message', 'N/A')}")
|
156 |
+
return []
|
157 |
+
return None
|
158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
|
160 |
|
161 |
def get_repository_details(repo_api_url: str) -> dict | None:
|
162 |
+
|
|
|
|
|
|
|
163 |
if not repo_api_url:
|
164 |
print("ERROR (github_client.get_repository_details): No repository API URL provided.")
|
165 |
return None
|
|
|
168 |
|
169 |
|
170 |
def get_file_url_from_repo(repo_full_name: str, file_paths_to_check: list[str], default_branch: str | None = None) -> str | None:
|
171 |
+
|
|
|
|
|
|
|
172 |
if not repo_full_name or not file_paths_to_check:
|
173 |
print("ERROR (github_client.get_file_url_from_repo): repo_full_name and file_paths_to_check are required.")
|
174 |
return None
|
|
|
175 |
branch_to_use = default_branch
|
176 |
if not branch_to_use:
|
177 |
print(f"GitHub Client (get_file_url): No default branch provided for {repo_full_name}, attempting to fetch it.")
|
|
|
182 |
print(f"GitHub Client (get_file_url): Fetched default branch '{branch_to_use}' for {repo_full_name}.")
|
183 |
else:
|
184 |
print(f"GitHub Client (get_file_url): Could not determine default branch for {repo_full_name}. Will try common fallbacks.")
|
|
|
|
|
|
|
185 |
branches_to_attempt = []
|
186 |
+
if branch_to_use: branches_to_attempt.append(branch_to_use)
|
187 |
+
if not branch_to_use: branches_to_attempt.extend(["main", "master"])
|
188 |
+
branches_to_attempt = [b for b in branches_to_attempt if b]
|
|
|
|
|
|
|
|
|
189 |
for current_branch_attempt in branches_to_attempt:
|
190 |
print(f"GitHub Client (get_file_url): Trying branch '{current_branch_attempt}' for {repo_full_name}.")
|
191 |
for file_path in file_paths_to_check:
|
192 |
file_api_url = f"{BASE_REPO_URL}/{repo_full_name}/contents/{file_path}?ref={current_branch_attempt}"
|
193 |
+
file_metadata = _make_github_request(file_api_url)
|
|
|
194 |
if file_metadata and isinstance(file_metadata, dict) and file_metadata.get("html_url"):
|
195 |
print(f"GitHub Client (get_file_url): Found '{file_path}' in {repo_full_name} on branch '{current_branch_attempt}'.")
|
196 |
return file_metadata.get("html_url")
|
|
|
|
|
|
|
197 |
print(f"GitHub Client (get_file_url): Could not find any of {file_paths_to_check} in {repo_full_name} on attempted branches.")
|
198 |
return None
|
199 |
|
200 |
+
|
201 |
def get_file_content(repo_full_name: str, file_path: str, branch: str | None = None) -> str | None:
|
202 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
if not repo_full_name or not file_path:
|
204 |
print("ERROR (github_client.get_file_content): repo_full_name and file_path are required.")
|
205 |
return None
|
|
|
206 |
current_branch = branch
|
207 |
if not current_branch:
|
208 |
print(f"GitHub Client (get_file_content): No branch specified for {repo_full_name}/{file_path}, finding default.")
|
|
|
212 |
current_branch = repo_details.get("default_branch")
|
213 |
print(f"GitHub Client (get_file_content): Using default branch '{current_branch}' for {repo_full_name}/{file_path}")
|
214 |
else:
|
|
|
215 |
print(f"GitHub Client (get_file_content): Could not determine default branch for {repo_full_name}. Trying 'main', then 'master' for {file_path}.")
|
216 |
+
current_branch = "main"
|
|
|
|
|
|
|
|
|
|
|
217 |
file_api_url = f"{BASE_REPO_URL}/{repo_full_name}/contents/{file_path}?ref={current_branch}"
|
218 |
print(f"GitHub Client (get_file_content): Fetching raw content for '{file_path}' from '{repo_full_name}' on branch '{current_branch}'.")
|
|
|
219 |
if not GITHUB_PAT:
|
220 |
print("ERROR (github_client.get_file_content): GITHUB_PAT is not configured.")
|
221 |
return None
|
|
|
222 |
headers = {
|
223 |
"Authorization": f"token {GITHUB_PAT}",
|
224 |
+
"Accept": "application/vnd.github.raw",
|
225 |
"X-GitHub-Api-Version": "2022-11-28"
|
226 |
}
|
|
|
227 |
try:
|
228 |
+
response = requests.get(file_api_url, headers=headers, timeout=15)
|
229 |
response.raise_for_status()
|
230 |
+
return response.text
|
|
|
|
|
|
|
231 |
except requests.exceptions.HTTPError as http_err:
|
232 |
if http_err.response.status_code == 404:
|
233 |
print(f"INFO (github_client.get_file_content): File not found (404) at {file_api_url}")
|
234 |
+
if current_branch == "main" and (not branch or branch == "main"):
|
|
|
235 |
print(f"GitHub Client (get_file_content): '{file_path}' not found on 'main', trying 'master' as fallback.")
|
236 |
+
return get_file_content(repo_full_name, file_path, branch="master")
|
237 |
else:
|
238 |
error_message = f"ERROR (github_client.get_file_content): GitHub API HTTP error for URL {file_api_url}: {http_err}."
|
239 |
try:
|
240 |
+
error_details = http_err.response.json()
|
241 |
error_message += f" Details: {error_details.get('message', http_err.response.text)}"
|
242 |
except ValueError:
|
243 |
error_message += f" Response: {http_err.response.text}"
|
244 |
print(error_message)
|
245 |
return None
|
246 |
+
except Exception as e:
|
247 |
+
print(f"ERROR (github_client.get_file_content): An unexpected error occurred: {e}")
|
248 |
return None
|