llama-github 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llama_github/__init__.py +3 -0
- llama_github/config/__init__.py +0 -0
- llama_github/config/config.json +20 -0
- llama_github/config/config.py +30 -0
- llama_github/data_retrieval/__init__.py +0 -0
- llama_github/data_retrieval/github_api.py +296 -0
- llama_github/data_retrieval/github_entities.py +301 -0
- llama_github/features/__init__.py +0 -0
- llama_github/features/feature_flags.py +0 -0
- llama_github/features/insider_features.py +0 -0
- llama_github/github_integration/__init__.py +7 -0
- llama_github/github_integration/github_auth_manager.py +266 -0
- llama_github/github_rag.py +348 -0
- llama_github/llm_integration/__init__.py +0 -0
- llama_github/llm_integration/initial_load.py +101 -0
- llama_github/llm_integration/llm_handler.py +131 -0
- llama_github/logger.py +28 -0
- llama_github/rag_processing/__init__.py +0 -0
- llama_github/rag_processing/rag_processor.py +490 -0
- llama_github/utils.py +98 -0
- llama_github/version.py +1 -0
- llama_github-0.1.0.dist-info/LICENSE +201 -0
- llama_github-0.1.0.dist-info/METADATA +100 -0
- llama_github-0.1.0.dist-info/RECORD +26 -0
- llama_github-0.1.0.dist-info/WHEEL +5 -0
- llama_github-0.1.0.dist-info/top_level.txt +1 -0
llama_github/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"general_prompt": "You are a highly intelligent assistant with expertise in GitHub repositories and coding practices. Your task is to analyze questions related to GitHub projects, coding issues, or programming concepts. Using your extensive knowledge base, you will provide detailed, accurate, and contextually relevant answers. You have the ability to understand complex coding queries, retrieve pertinent information from GitHub repositories, and augment this data with your advanced reasoning capabilities. Your responses should guide developers towards solving their problems, understanding new concepts, or finding the information they seek related to GitHub projects and software development.",
|
|
3
|
+
"always_answer_prompt": "**Instructions:**\nAs an advanced AI assistant with deep expertise in GitHub repositories, coding practices, and programming concepts, your primary goal is to provide concise, accurate, and contextually relevant answers to complex coding queries. When presented with a question, your first step is to analyze the query and generate a succinct abstraction that captures its core essence by using only one sentence, especially if the original question is lengthy or convoluted.\n\nNext, leverage your extensive knowledge base and reasoning capabilities to craft a coherent and informative response. If possible, enhance your answer with sample code snippets that demonstrate the practical application of the concepts discussed. Remember, your responses should guide developers towards solving their problems, understanding new concepts, or finding the information they seek related to GitHub projects and software development. Please keep your responses concise and to the point, focusing on the most essential information needed to address the query. Avoid generating long articles or overly detailed explanations.\n\nIn addition to the answer itself, provide a brief analysis of how you would approach searching for relevant code and issues within GitHub repositories. This analysis should outline your thought process and the key factors you would consider when conducting these searches. However, keep this analysis concise and focused on the high-level logic rather than delving into specific search criteria or keywords.\n\nThroughout your responses, prioritize clarity and brevity. Focus on delivering the most essential information needed to address the query effectively. Even if certain details are unknown, ensure that your answers are plausible, useful, and serve as a foundation for further exploration and context generation.\n\nRemember, your ultimate aim is to empower developers with the knowledge and guidance they need to overcome challenges, expand their understanding, and navigate the vast landscape of GitHub repositories and software development practices.",
|
|
4
|
+
"code_search_criteria_prompt": "**Instructions:**\n- **Expertise-Driven Github Code Search Criteria Generation:** Generate GitHub code search criteria strings based on the provided question and its draft answer. Analyze both the question and answer to identify key concepts, technologies, and coding practices that can help locate relevant code snippets on GitHub. Always include the `language:` qualifier to focus your search on language-related content.\n\n**Output Format:** Present each search criteria string on a new line, formatted for immediate use in GitHub's code search, without additional explanations or commentary.\n\n**Optimization Considerations:**\n- **Keyword Relevance:** Extract keywords and phrases tightly related to the question from the question and answer that are likely to appear in relevant code and code comments. Prioritize terms that reflect specific coding concepts, libraries, or techniques. Avoid generic terms like \"example\" or \"integration\" that may not be present in actual code.\n- **Contextual Understanding:** Use the provided answer as additional context to inform your keyword selection. Identify key insights, technologies, or approaches mentioned in the answer tightly related to the question that can help refine the search criteria.\n- **Language and Platform Specificity:** If the question is specific to a certain programming language or platform, ensure to include relevant language or platform-specific keywords, libraries, or frameworks in the search criteria. This helps filter out irrelevant results from other languages or platforms.\n- **Simplicity and Effectiveness:** Craft search criteria with simple and limited keywords which could lead to precise search results to relevant code snippets tightly related to original question. Strike a balance between specificity and breadth to ensure the criteria capture the essential aspects of the question and answer. The search criteria should be neither too narrow that no results are returned, nor too broad that many irrelevant results are included.\n- **Multiple Perspectives:** Generate multiple search criteria strings that approach the question from different angles or emphasize different aspects mentioned in the question and answer. This increases the chances of finding relevant code snippets.",
|
|
5
|
+
"issue_search_criteria_prompt": "**Instructions:**\n- **Question-Driven GitHub Issue Search Criteria Generation:** Generate GitHub issue search criteria strings based on the provided question. Analyze the question to identify key concepts, technologies, and problem-solving approaches that can help locate relevant issues on GitHub. Consider using relevant `label:` or `is:` qualifiers when applicable.\n\n**Output Format:** Present each search criteria string on a new line, formatted for immediate use in GitHub's issue search, without additional explanations or commentary.\n\n**Optimization Considerations:**\n- **Keyword Relevance:** Extract keywords and phrases tightly related to the question that are likely to appear in issue titles, descriptions, and discussions. Prioritize terms that reflect specific problems, error messages, or technologies. Avoid generic terms like \"help\" or \"problem\" that may not effectively narrow down the search results.\n- **Contextual Understanding:** Use the question's draft answer to inform your keyword selection. Identify key aspects, technologies, or potential troubleshooting areas tightly related to the question but not only specific aspects of answers that can help refine the search criteria.\n- **Simplicity and Effectiveness:** Craft search criteria with simple and limited keywords which could lead to precise search results relevant to the original question. Strike a balance between specificity and breadth to ensure the criteria capture the essential aspects of the question without being overly restrictive.\n- **Multiple Perspectives:** Generate multiple search criteria strings that approach the question from different angles or emphasize different aspects mentioned in the question. This increases the chances of finding relevant issues that discuss similar problems or solutions.\n- **Leveraging Labels:** When appropriate, include relevant `label:` qualifiers in the search criteria to narrow down the results to issues with specific labels, such as \"bug,\" \"enhancement,\" or \"documentation.\" This can help focus the search on issues that align with the nature of the question.\n- **Considering Issue Discussions:** Keep in mind that issue discussions often contain valuable information, experiences, and workarounds shared by other developers. Craft search criteria that not only match the issue title and description but also consider the likelihood of the keywords appearing in the issue's comments and discussions.",
|
|
6
|
+
"repo_search_criteria_prompt": "**Instructions:**\n- **Expertise-Driven Github Repository Search Criteria Generation:** Generate GitHub repo search criteria strings based on the provided question. Analyze the question leverage your expertise for related key concepts, technologies, and problem-solving approaches that can help locate relevant repositories on GitHub. Focus on practical keywords and phrases likely to be present in repository names, descriptions, and topics. Use the `language:` qualifier to direct your search toward repositories written in a specific language, keeping the criteria simple and effective.\n- **Necessity Score Determination:** Evaluate the necessity of conducting a GitHub repository search based on the difficulty of question. Determine if repository-level information is essential to comprehensively address the question. Assign a necessity score indicating the importance of performing a repository search.\n\n**Output Format:**\n- **Necessity Score:** Begin your output with a necessity score (0-100) indicating the importance of performing a separate GitHub repository search. Use the following scale:\n - 0-59: Low necessity - Only code and issue search results is sufficient.\n - 60-79: Medium necessity - One repository search may offer additional insights and context.\n - 80-100: High necessity - Two repository searches are crucial to gather comprehensive information, such as project structure, documentation, or community engagement, to thoroughly address the question.\n\n- **Search Criteria:** Present each search criteria string on a new line, formatted for immediate use in GitHub's repository search, without additional explanations or commentary.\n**Optimization Considerations:**\n- **Keyword Relevance:** Generate search criteria keywords and phrases from the question that are uniquely relevant to repository names, descriptions, and topics. Prioritize terms that reflect the broader context, expertise, and strategic thinking required to address the question effectively. Avoid generic terms that may lead to irrelevant search results.\n- **Simplicity and Effectiveness:** Craft search criteria that are simple yet effective in narrowing down the repository search results to the most relevant and informative ones. Strike a balance between specificity and breadth, ensuring that the criteria capture the essential aspects of the question without being overly restrictive. Aim for criteria that yield a manageable number of high-quality repository results.\n- **Language and Platform Specificity:** If the question pertains to a specific programming language or platform, incorporate relevant language or platform-specific keywords in the search criteria. Use the `language:` qualifier to filter repositories based on the language of interest. This helps focus the search on repositories that are more likely to contain relevant code, documentation, and community expertise.\n- **Multiple Criteria Flexibility:** Generate multiple search criteria strings that approach the question from different angles or emphasize different aspects mentioned in the question. This flexibility allows for a more comprehensive repository search, increasing the chances of discovering relevant repositories that may offer valuable insights, code samples, or best practices related to the question at hand.",
|
|
7
|
+
"scoring_context_prompt": "You are an expert in evaluating the relevance of coding-related contexts to given questions. Your primary function is to analyze the provided context and question, and output a single integer score between 0 and 100, indicating how well the context supports answering the question.\n\nScoring criteria:\n0-20: The context is completely irrelevant to the question and provides no useful information to answer it.\n21-40: The context is slightly relevant to the question but lacks crucial information to provide a complete answer.\n41-60: The context is somewhat relevant to the question and provides some useful information, but it may not be sufficient to fully answer the question.\n61-80: The context is highly relevant to the question and provides most of the necessary information to answer it, but some minor details may be missing.\n81-100: The context is extremely relevant to the question and provides all the necessary information to comprehensively answer it.\n\nRemember, your output should consist of only a single integer score without any additional text or explanation. Analyze the context and question carefully, and provide a score that accurately reflects the relevance of the context in answering the question.",
|
|
8
|
+
"default_embedding": "jinaai/jina-embeddings-v2-base-code",
|
|
9
|
+
"default_reranker": "jinaai/jina-reranker-v1-turbo-en",
|
|
10
|
+
"min_stars_to_keep_result": 20,
|
|
11
|
+
"max_workers": 8,
|
|
12
|
+
"code_search_max_hits": 30,
|
|
13
|
+
"issue_search_max_hits": 30,
|
|
14
|
+
"repo_search_max_hits": 10,
|
|
15
|
+
"chunk_size": 2000,
|
|
16
|
+
"issue_chunk_size": 7000,
|
|
17
|
+
"repo_chunk_size": 7000,
|
|
18
|
+
"google_chunk_size": 7000,
|
|
19
|
+
"top_n_contexts": 5
|
|
20
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# config.py
|
|
2
|
+
import json
|
|
3
|
+
from importlib import resources
|
|
4
|
+
from llama_github.logger import logger
|
|
5
|
+
|
|
6
|
+
# utils.py
|
|
7
|
+
class SingletonMeta(type):
|
|
8
|
+
_instances = {}
|
|
9
|
+
def __call__(cls, *args, **kwargs):
|
|
10
|
+
if cls not in cls._instances:
|
|
11
|
+
instance = super().__call__(*args, **kwargs)
|
|
12
|
+
cls._instances[cls] = instance
|
|
13
|
+
return cls._instances[cls]
|
|
14
|
+
|
|
15
|
+
class Config(metaclass=SingletonMeta):
|
|
16
|
+
_config = None
|
|
17
|
+
|
|
18
|
+
def __init__(self):
|
|
19
|
+
if Config._config is None:
|
|
20
|
+
with resources.open_text('llama_github.config', 'config.json') as file:
|
|
21
|
+
Config._config = json.load(file)
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def get(cls, key, default=None):
|
|
25
|
+
# Ensure the singleton instance is created
|
|
26
|
+
if cls._config is None:
|
|
27
|
+
cls()
|
|
28
|
+
return cls._config.get(key, default)
|
|
29
|
+
|
|
30
|
+
config = Config()
|
|
File without changes
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
from github import GithubException
|
|
2
|
+
from .github_entities import Repository, RepositoryPool
|
|
3
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
4
|
+
from llama_github.logger import logger
|
|
5
|
+
from llama_github.github_integration.github_auth_manager import ExtendedGithub
|
|
6
|
+
from llama_github.config.config import config
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GitHubAPIHandler:
|
|
11
|
+
def __init__(self, github_instance: ExtendedGithub):
|
|
12
|
+
"""
|
|
13
|
+
Initializes the GitHubAPIHandler with a GitHub instance.
|
|
14
|
+
|
|
15
|
+
:param github_instance: Authenticated instance of a Github client.
|
|
16
|
+
"""
|
|
17
|
+
self._github = github_instance
|
|
18
|
+
self.pool = RepositoryPool(github_instance)
|
|
19
|
+
|
|
20
|
+
def search_repositories(self, query, sort="best match", order="desc"):
|
|
21
|
+
"""
|
|
22
|
+
Searches for repositories on GitHub based on a query.
|
|
23
|
+
|
|
24
|
+
:param query: The search query string.
|
|
25
|
+
:param sort: The field to sort the results by. Default is 'stars'.
|
|
26
|
+
:param order: The order of sorting, 'asc' or 'desc'. Default is 'desc'.
|
|
27
|
+
:return: A list of Repository objects or None if an error occurs.
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
if sort not in ['stars', 'forks', 'updated']:
|
|
31
|
+
repositories = self._github.search_repositories(
|
|
32
|
+
query=query, order=order)
|
|
33
|
+
else:
|
|
34
|
+
repositories = self._github.search_repositories(
|
|
35
|
+
query=query, sort=sort, order=order)
|
|
36
|
+
result = []
|
|
37
|
+
for i, repo in enumerate(repositories):
|
|
38
|
+
if i >= config.get("repo_search_max_hits"):
|
|
39
|
+
break
|
|
40
|
+
result.append(
|
|
41
|
+
Repository(
|
|
42
|
+
repo.full_name,
|
|
43
|
+
self._github,
|
|
44
|
+
**{
|
|
45
|
+
'id': repo.id,
|
|
46
|
+
'name': repo.name,
|
|
47
|
+
'description': repo.description,
|
|
48
|
+
'html_url': repo.html_url,
|
|
49
|
+
'stargazers_count': repo.stargazers_count,
|
|
50
|
+
'language': repo.language,
|
|
51
|
+
'default_branch': repo.default_branch,
|
|
52
|
+
'updated_at': repo.updated_at,
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
return result
|
|
57
|
+
except GithubException as e:
|
|
58
|
+
logger.exception(
|
|
59
|
+
f"Error searching repositories with query '{query}':")
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
def get_repository(self, full_repo_name):
|
|
63
|
+
"""
|
|
64
|
+
Retrieves a single repository by its full name.
|
|
65
|
+
|
|
66
|
+
:param full_repo_name: The full name of the repository (e.g., 'octocat/Hello-World').
|
|
67
|
+
:return: A Repository object or None if an error occurs.
|
|
68
|
+
"""
|
|
69
|
+
return self.pool.get_repository(full_repo_name)
|
|
70
|
+
|
|
71
|
+
def _get_file_content_through_repository(self, code_search_result):
|
|
72
|
+
"""
|
|
73
|
+
Helper method to get file content through a Repository object.
|
|
74
|
+
|
|
75
|
+
:param code_search_result: A single code search result.
|
|
76
|
+
:return: Tuple containing the Repository object and the file content.
|
|
77
|
+
"""
|
|
78
|
+
# Assuming RepositoryPool is accessible and initialized somewhere in this class
|
|
79
|
+
repository_obj = self.get_repository(
|
|
80
|
+
code_search_result['repository']['full_name'])
|
|
81
|
+
file_content = repository_obj.get_file_content(
|
|
82
|
+
code_search_result['path'])
|
|
83
|
+
return repository_obj, file_content
|
|
84
|
+
|
|
85
|
+
def search_code(self, query, repo_full_name=None):
|
|
86
|
+
"""
|
|
87
|
+
Searches for code on GitHub based on a query, optionally within a specific repository.
|
|
88
|
+
|
|
89
|
+
:param query: The search query string.
|
|
90
|
+
:param repo_full_name: Optional. The full name of the repository (e.g., 'octocat/Hello-World') to restrict the search to.
|
|
91
|
+
:return: A list of code search results or None if an error occurs.
|
|
92
|
+
"""
|
|
93
|
+
try:
|
|
94
|
+
logger.debug(f"Searching code with query '{query}'...")
|
|
95
|
+
# If a repository full name is provided, include it in the query
|
|
96
|
+
if repo_full_name:
|
|
97
|
+
query = f"{query} repo:{repo_full_name}"
|
|
98
|
+
|
|
99
|
+
# Perform the search
|
|
100
|
+
code_results = self._github.search_code(
|
|
101
|
+
query=query, per_page=config.get("code_search_max_hits"))
|
|
102
|
+
|
|
103
|
+
results_with_index = []
|
|
104
|
+
with ThreadPoolExecutor(max_workers=config.get("max_workers")) as executor:
|
|
105
|
+
# Concurrently fetch the file content for each code search result
|
|
106
|
+
future_to_index = {executor.submit(
|
|
107
|
+
self._get_file_content_through_repository, code_result): index for index, code_result in enumerate(code_results)}
|
|
108
|
+
for future in as_completed(future_to_index):
|
|
109
|
+
index = future_to_index[future]
|
|
110
|
+
code_result = code_results[index]
|
|
111
|
+
try:
|
|
112
|
+
repository_obj, file_content = future.result()
|
|
113
|
+
if repository_obj and file_content:
|
|
114
|
+
results_with_index.append({
|
|
115
|
+
'index': index,
|
|
116
|
+
'name': code_result['name'],
|
|
117
|
+
'path': code_result['path'],
|
|
118
|
+
'repository_full_name': code_result['repository']['full_name'],
|
|
119
|
+
'url': code_result['html_url'],
|
|
120
|
+
'content': file_content,
|
|
121
|
+
'stargazers_count': repository_obj.stargazers_count,
|
|
122
|
+
'watchers_count': repository_obj.watchers_count,
|
|
123
|
+
'language': repository_obj.language,
|
|
124
|
+
'description': repository_obj.description,
|
|
125
|
+
'updated_at': repository_obj.updated_at,
|
|
126
|
+
})
|
|
127
|
+
except Exception as e:
|
|
128
|
+
logger.exception(
|
|
129
|
+
f"{code_result['name']} generated an exception:")
|
|
130
|
+
|
|
131
|
+
# Sort the results by index to maintain the original order
|
|
132
|
+
sorted_results = sorted(
|
|
133
|
+
results_with_index, key=lambda x: x['index'])
|
|
134
|
+
logger.debug(
|
|
135
|
+
f"Code search retrieved successfully with {len(sorted_results)} results.")
|
|
136
|
+
return sorted_results
|
|
137
|
+
except GithubException as e:
|
|
138
|
+
logger.exception(f"Error searching code with query '{query}':")
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
def _get_issue_content_through_repository(self, issue):
|
|
142
|
+
"""
|
|
143
|
+
Helper method to get issue content through issue url.
|
|
144
|
+
|
|
145
|
+
:param code_result: A single code search result.
|
|
146
|
+
:return: Tuple containing the Repository object and the file content.
|
|
147
|
+
"""
|
|
148
|
+
# Assuming RepositoryPool is accessible and initialized somewhere in this clas
|
|
149
|
+
issue_content = ''
|
|
150
|
+
issue_url = issue['url']
|
|
151
|
+
# Use regular expressions to extract repo_full_name and issue_number
|
|
152
|
+
match = re.search(
|
|
153
|
+
r'https://api.github.com/repos/([^/]+/[^/]+)/issues/(\d+)', issue_url)
|
|
154
|
+
if match:
|
|
155
|
+
repo_full_name = match.group(1)
|
|
156
|
+
issue_number = int(match.group(2))
|
|
157
|
+
repository_obj = self.get_repository(repo_full_name)
|
|
158
|
+
issue_content = repository_obj.get_issue_content(
|
|
159
|
+
number=issue_number, issue=issue)
|
|
160
|
+
else:
|
|
161
|
+
logger.warning(
|
|
162
|
+
f"Failed to extract repo_full_name and issue_number from issue url: {issue_url}")
|
|
163
|
+
return issue_content
|
|
164
|
+
|
|
165
|
+
def search_issues(self, query, repo_full_name=None):
|
|
166
|
+
"""
|
|
167
|
+
Searches for issues on GitHub based on a query, optionally within a specific repository.
|
|
168
|
+
|
|
169
|
+
:param query: The search query string.
|
|
170
|
+
:param repo_full_name: Optional. The full name of the repository (e.g., 'octocat/Hello-World') to restrict the search to.
|
|
171
|
+
:return: A list of issue search results or None if an error occurs.
|
|
172
|
+
"""
|
|
173
|
+
try:
|
|
174
|
+
logger.debug(f"Searching issue with query '{query}'...")
|
|
175
|
+
# If a repository full name is provided, include it in the query
|
|
176
|
+
if repo_full_name:
|
|
177
|
+
query = f"{query} repo:{repo_full_name}"
|
|
178
|
+
|
|
179
|
+
# Perform the search
|
|
180
|
+
issue_results = self._github.search_issues(
|
|
181
|
+
query=query, per_page=config.get("issue_search_max_hits"))
|
|
182
|
+
|
|
183
|
+
issue_results = [issue for issue in issue_results if issue['body']
|
|
184
|
+
is not None and issue['body'] != 'null']
|
|
185
|
+
|
|
186
|
+
results_with_index = []
|
|
187
|
+
with ThreadPoolExecutor(max_workers=config.get("max_workers")) as executor:
|
|
188
|
+
# Concurrently fetch the issue content for each issue search result
|
|
189
|
+
future_to_index = {executor.submit(
|
|
190
|
+
self._get_issue_content_through_repository, issue): index for index, issue in enumerate(issue_results)}
|
|
191
|
+
for future in as_completed(future_to_index):
|
|
192
|
+
index = future_to_index[future]
|
|
193
|
+
issue_result = issue_results[index]
|
|
194
|
+
try:
|
|
195
|
+
issue_content = future.result()
|
|
196
|
+
results_with_index.append({
|
|
197
|
+
'index': index,
|
|
198
|
+
'url': issue_result['url'],
|
|
199
|
+
'created_at': issue_result['created_at'],
|
|
200
|
+
'updated_at': issue_result['updated_at'],
|
|
201
|
+
'issue_content': issue_content,
|
|
202
|
+
})
|
|
203
|
+
except Exception as e:
|
|
204
|
+
logger.exception(
|
|
205
|
+
f"{issue_result['url']} generated an exception:")
|
|
206
|
+
|
|
207
|
+
# Sort the results by index to maintain the original order
|
|
208
|
+
sorted_results = sorted(
|
|
209
|
+
results_with_index, key=lambda x: x['index'])
|
|
210
|
+
logger.debug(
|
|
211
|
+
f"Issue search retrieved successfully with {len(sorted_results)} results.")
|
|
212
|
+
return sorted_results
|
|
213
|
+
except GithubException as e:
|
|
214
|
+
logger.exception(f"Error searching issue with query '{query}':")
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
def _categorize_github_url(url):
|
|
218
|
+
repo_pattern = r'^https://github\.com/[^/]+/[^/]+$'
|
|
219
|
+
issue_pattern = r'^https://github\.com/[^/]+/[^/]+/issues/\d+$'
|
|
220
|
+
repo_file_pattern = r'^https://github\.com/[^/]+/[^/]+/(?:blob|tree)/[^/]+/.+$'
|
|
221
|
+
readme_pattern = r'^https://github\.com/[^/]+/[^/]+#readme$'
|
|
222
|
+
|
|
223
|
+
if re.match(repo_pattern, url):
|
|
224
|
+
return "repo"
|
|
225
|
+
elif re.match(issue_pattern, url):
|
|
226
|
+
return "issue"
|
|
227
|
+
elif re.match(repo_file_pattern, url):
|
|
228
|
+
return "file"
|
|
229
|
+
elif re.match(readme_pattern, url):
|
|
230
|
+
return "readme"
|
|
231
|
+
else:
|
|
232
|
+
return "other"
|
|
233
|
+
|
|
234
|
+
def get_github_url_content(self, url):
|
|
235
|
+
"""
|
|
236
|
+
Retrieves the content of a GitHub URL.
|
|
237
|
+
|
|
238
|
+
:param url: The GitHub URL to retrieve content from.
|
|
239
|
+
:return: The content of the URL or None if an error occurs.
|
|
240
|
+
"""
|
|
241
|
+
try:
|
|
242
|
+
logger.debug(f"Retrieving content from GitHub URL '{url}'...")
|
|
243
|
+
content = None
|
|
244
|
+
category = GitHubAPIHandler._categorize_github_url(url)
|
|
245
|
+
if category == "repo":
|
|
246
|
+
# Extract the repository full name from the URL
|
|
247
|
+
match = re.search(r'https://github\.com/([^/]+/[^/]+)', url)
|
|
248
|
+
if match:
|
|
249
|
+
repo_full_name = match.group(1)
|
|
250
|
+
repository_obj = self.get_repository(repo_full_name)
|
|
251
|
+
content = repository_obj.get_readme()
|
|
252
|
+
else:
|
|
253
|
+
logger.warning(
|
|
254
|
+
f"Failed to extract repository full name from URL: {url}")
|
|
255
|
+
elif category == "issue":
|
|
256
|
+
# Use regular expressions to extract repo_full_name and issue_number
|
|
257
|
+
match = re.search(
|
|
258
|
+
r'https://github\.com/([^/]+/[^/]+)/issues/(\d+)', url)
|
|
259
|
+
if match:
|
|
260
|
+
repo_full_name = match.group(1)
|
|
261
|
+
issue_number = int(match.group(2))
|
|
262
|
+
repository_obj = self.get_repository(repo_full_name)
|
|
263
|
+
content = repository_obj.get_issue_content(
|
|
264
|
+
number=issue_number)
|
|
265
|
+
else:
|
|
266
|
+
logger.warning(
|
|
267
|
+
f"Failed to extract repo_full_name and issue_number from URL: {url}")
|
|
268
|
+
elif category == "file":
|
|
269
|
+
# Extract the repository full name and file path from the URL
|
|
270
|
+
match = re.search(
|
|
271
|
+
r'https://github\.com/([^/]+/[^/]+)/(?:blob|tree)/([^/]+)/(.+)', url)
|
|
272
|
+
if match:
|
|
273
|
+
repo_full_name = match.group(1)
|
|
274
|
+
file_path = match.group(3)
|
|
275
|
+
repository_obj = self.get_repository(repo_full_name)
|
|
276
|
+
content = repository_obj.get_file_content(
|
|
277
|
+
file_path)
|
|
278
|
+
else:
|
|
279
|
+
logger.warning(
|
|
280
|
+
f"Failed to extract repository full name and file path from URL: {url}")
|
|
281
|
+
elif category == "readme":
|
|
282
|
+
# Extract the repository full name from the URL
|
|
283
|
+
match = re.search(r'https://github\.com/([^/]+/[^/]+)#readme', url)
|
|
284
|
+
if match:
|
|
285
|
+
repo_full_name = match.group(1)
|
|
286
|
+
repository_obj = self.get_repository(repo_full_name)
|
|
287
|
+
content = repository_obj.get_readme()
|
|
288
|
+
else:
|
|
289
|
+
logger.warning(
|
|
290
|
+
f"Failed to extract repository full name from URL: {url}")
|
|
291
|
+
else:
|
|
292
|
+
logger.warning(f"Unsupported GitHub URL category: {category}")
|
|
293
|
+
return content
|
|
294
|
+
except GithubException as e:
|
|
295
|
+
logger.exception(f"Error retrieving content from GitHub URL '{url}':")
|
|
296
|
+
return None
|