Spaces:
Running
Running
Upload 2 files
Browse files- app.py +66 -0
- github-repo-analyzer.py +681 -0
app.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import time
|
4 |
+
import markdown
|
5 |
+
from github_repo_analyzer import main as analyze_repo, get_repo_info
|
6 |
+
|
7 |
+
# Emojis and fun statements for progress updates
|
8 |
+
PROGRESS_STEPS = [
|
9 |
+
("🕵️♂️", "Investigating the GitHub realm..."),
|
10 |
+
("🧬", "Decoding repository DNA..."),
|
11 |
+
("🐛", "Hunting for bugs and features..."),
|
12 |
+
("🔍", "Examining pull request tea leaves..."),
|
13 |
+
("🧠", "Activating AI brain cells..."),
|
14 |
+
("📝", "Crafting the legendary report..."),
|
15 |
+
]
|
16 |
+
|
17 |
+
def analyze_github_repo(repo_input, github_token=None):
|
18 |
+
if github_token:
|
19 |
+
os.environ["GITHUB_TOKEN"] = github_token
|
20 |
+
|
21 |
+
progress_html = ""
|
22 |
+
yield progress_html, "" # Initial empty output
|
23 |
+
|
24 |
+
for emoji, message in PROGRESS_STEPS:
|
25 |
+
progress_html += f"<p>{emoji} {message}</p>"
|
26 |
+
yield progress_html, ""
|
27 |
+
time.sleep(1) # Simulate work being done
|
28 |
+
|
29 |
+
try:
|
30 |
+
owner, repo_name = get_repo_info(repo_input)
|
31 |
+
max_issues = 10
|
32 |
+
max_prs = 10
|
33 |
+
|
34 |
+
report = analyze_repo(repo_input, max_issues, max_prs)
|
35 |
+
|
36 |
+
# Convert markdown to HTML
|
37 |
+
html_report = markdown.markdown(report)
|
38 |
+
|
39 |
+
return progress_html + "<p>✅ Analysis complete!</p>", html_report
|
40 |
+
except Exception as e:
|
41 |
+
error_message = f"<p>❌ An error occurred: {str(e)}</p>"
|
42 |
+
return progress_html + error_message, ""
|
43 |
+
|
44 |
+
# Define the Gradio interface
|
45 |
+
with gr.Blocks() as app:
|
46 |
+
gr.Markdown("# GitHub Repository Analyzer")
|
47 |
+
|
48 |
+
repo_input = gr.Textbox(label="Enter GitHub Repository Slug or URL")
|
49 |
+
|
50 |
+
with gr.Accordion("Advanced Settings", open=False):
|
51 |
+
github_token = gr.Textbox(label="GitHub Token (optional)", type="password")
|
52 |
+
|
53 |
+
analyze_button = gr.Button("Analyze Repository")
|
54 |
+
|
55 |
+
progress_output = gr.HTML(label="Progress")
|
56 |
+
report_output = gr.HTML(label="Analysis Report")
|
57 |
+
|
58 |
+
analyze_button.click(
|
59 |
+
analyze_github_repo,
|
60 |
+
inputs=[repo_input, github_token],
|
61 |
+
outputs=[progress_output, report_output],
|
62 |
+
)
|
63 |
+
|
64 |
+
# Launch the app
|
65 |
+
if __name__ == "__main__":
|
66 |
+
app.launch()
|
github-repo-analyzer.py
ADDED
@@ -0,0 +1,681 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import tempfile
|
4 |
+
import shutil
|
5 |
+
from urllib.parse import urlparse
|
6 |
+
import requests
|
7 |
+
from github import Github
|
8 |
+
from git import Repo
|
9 |
+
import anthropic
|
10 |
+
from collections import defaultdict
|
11 |
+
import time
|
12 |
+
import numpy as np
|
13 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
14 |
+
from sklearn.cluster import KMeans
|
15 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
16 |
+
import subprocess
|
17 |
+
import json
|
18 |
+
from pathlib import Path
|
19 |
+
import traceback
|
20 |
+
import argparse
|
21 |
+
|
22 |
+
def run_semgrep(repo_path):
|
23 |
+
try:
|
24 |
+
result = subprocess.run(
|
25 |
+
["semgrep", "--config", "auto", "--json", repo_path],
|
26 |
+
capture_output=True,
|
27 |
+
text=True,
|
28 |
+
check=True
|
29 |
+
)
|
30 |
+
return json.loads(result.stdout)
|
31 |
+
except subprocess.CalledProcessError as e:
|
32 |
+
print(f"Semgrep error: {e}")
|
33 |
+
return None
|
34 |
+
except json.JSONDecodeError:
|
35 |
+
print("Failed to parse Semgrep output")
|
36 |
+
return None
|
37 |
+
|
38 |
+
def parse_llm_response(response):
|
39 |
+
try:
|
40 |
+
return json.loads(response)
|
41 |
+
except json.JSONDecodeError:
|
42 |
+
print(f"Warning: Failed to parse LLM response as JSON. Response: {response[:100]}...")
|
43 |
+
return []
|
44 |
+
|
45 |
+
def get_repo_info(input_str):
|
46 |
+
if input_str.startswith("http") or input_str.startswith("https"):
|
47 |
+
parsed_url = urlparse(input_str)
|
48 |
+
path_parts = parsed_url.path.strip("/").split("/")
|
49 |
+
return path_parts[0], path_parts[1]
|
50 |
+
else:
|
51 |
+
return input_str.split("/")
|
52 |
+
|
53 |
+
def clone_repo(owner, repo_name, temp_dir):
|
54 |
+
repo_url = f"https://github.com/{owner}/{repo_name}.git"
|
55 |
+
Repo.clone_from(repo_url, temp_dir)
|
56 |
+
return temp_dir
|
57 |
+
|
58 |
+
def analyze_code(repo_path):
|
59 |
+
file_types = defaultdict(int)
|
60 |
+
file_contents = {}
|
61 |
+
for root, _, files in os.walk(repo_path):
|
62 |
+
for file in files:
|
63 |
+
file_path = os.path.join(root, file)
|
64 |
+
_, ext = os.path.splitext(file)
|
65 |
+
file_types[ext] += 1
|
66 |
+
|
67 |
+
if ext in ['.py', '.js', '.java', '.cpp', '.cs', '.go', '.rb', '.php', 'ts', 'tsx', 'jsx']:
|
68 |
+
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
|
69 |
+
file_contents[file_path] = f.read()
|
70 |
+
|
71 |
+
semgrep_results = run_semgrep(repo_path)
|
72 |
+
|
73 |
+
return {
|
74 |
+
"file_types": dict(file_types),
|
75 |
+
"file_contents": file_contents,
|
76 |
+
"semgrep_results": semgrep_results
|
77 |
+
}
|
78 |
+
|
79 |
+
def analyze_issues(github_repo, max_issues):
|
80 |
+
closed_issues = []
|
81 |
+
open_issues = []
|
82 |
+
for issue in github_repo.get_issues(state="all")[:max_issues]:
|
83 |
+
issue_data = {
|
84 |
+
"number": issue.number,
|
85 |
+
"title": issue.title,
|
86 |
+
"body": issue.body,
|
87 |
+
"state": issue.state,
|
88 |
+
"created_at": issue.created_at.isoformat(),
|
89 |
+
"closed_at": issue.closed_at.isoformat() if issue.closed_at else None,
|
90 |
+
"comments": []
|
91 |
+
}
|
92 |
+
for comment in issue.get_comments():
|
93 |
+
issue_data["comments"].append({
|
94 |
+
"body": comment.body,
|
95 |
+
"created_at": comment.created_at.isoformat()
|
96 |
+
})
|
97 |
+
if issue.state == "closed":
|
98 |
+
closed_issues.append(issue_data)
|
99 |
+
else:
|
100 |
+
open_issues.append(issue_data)
|
101 |
+
time.sleep(0.5) # Rate limiting
|
102 |
+
|
103 |
+
# Cluster and filter closed issues
|
104 |
+
if closed_issues:
|
105 |
+
filtered_closed_issues = cluster_and_filter_items(closed_issues, n_clusters=min(5, len(closed_issues)), n_items=min(10, len(closed_issues)))
|
106 |
+
else:
|
107 |
+
filtered_closed_issues = []
|
108 |
+
|
109 |
+
return {
|
110 |
+
'closed_issues': closed_issues,
|
111 |
+
'open_issues': open_issues,
|
112 |
+
'filtered_closed_issues': filtered_closed_issues
|
113 |
+
}
|
114 |
+
|
115 |
+
def analyze_pull_requests(github_repo, max_prs):
|
116 |
+
closed_prs = []
|
117 |
+
open_prs = []
|
118 |
+
for pr in github_repo.get_pulls(state="all")[:max_prs]:
|
119 |
+
pr_data = {
|
120 |
+
"number": pr.number,
|
121 |
+
"title": pr.title,
|
122 |
+
"body": pr.body,
|
123 |
+
"state": pr.state,
|
124 |
+
"created_at": pr.created_at.isoformat(),
|
125 |
+
"closed_at": pr.closed_at.isoformat() if pr.closed_at else None,
|
126 |
+
"comments": [],
|
127 |
+
"diff": pr.get_files()
|
128 |
+
}
|
129 |
+
for comment in pr.get_comments():
|
130 |
+
pr_data["comments"].append({
|
131 |
+
"body": comment.body,
|
132 |
+
"created_at": comment.created_at.isoformat()
|
133 |
+
})
|
134 |
+
if pr.state == "closed":
|
135 |
+
closed_prs.append(pr_data)
|
136 |
+
else:
|
137 |
+
open_prs.append(pr_data)
|
138 |
+
time.sleep(0.5) # Rate limiting
|
139 |
+
|
140 |
+
# Cluster and filter closed PRs
|
141 |
+
if closed_prs:
|
142 |
+
filtered_closed_prs = cluster_and_filter_items(closed_prs, n_clusters=min(5, len(closed_prs)), n_items=min(10, len(closed_prs)))
|
143 |
+
else:
|
144 |
+
filtered_closed_prs = []
|
145 |
+
|
146 |
+
return {
|
147 |
+
'closed_prs': closed_prs,
|
148 |
+
'open_prs': open_prs,
|
149 |
+
'filtered_closed_prs': filtered_closed_prs
|
150 |
+
}
|
151 |
+
|
152 |
+
def call_llm(client, prompt, model="claude-3-5-sonnet-20240620", max_tokens=4096):
|
153 |
+
message = client.messages.create(
|
154 |
+
max_tokens=max_tokens,
|
155 |
+
model=model,
|
156 |
+
messages=[
|
157 |
+
{"role": "user", "content": prompt}
|
158 |
+
]
|
159 |
+
)
|
160 |
+
return message.content[0].text
|
161 |
+
|
162 |
+
def safe_call_llm(client, prompt, retries=3):
|
163 |
+
for attempt in range(retries):
|
164 |
+
try:
|
165 |
+
response = call_llm(client, prompt)
|
166 |
+
return parse_llm_response(response)
|
167 |
+
except Exception as e:
|
168 |
+
print(f"Error in LLM call (attempt {attempt + 1}/{retries}): {str(e)}")
|
169 |
+
if attempt == retries - 1:
|
170 |
+
print("All retries failed. Returning empty list.")
|
171 |
+
return []
|
172 |
+
return []
|
173 |
+
|
174 |
+
def parse_llm_response(response):
|
175 |
+
try:
|
176 |
+
# First, try to parse the entire response as JSON
|
177 |
+
return json.loads(response)
|
178 |
+
except json.JSONDecodeError:
|
179 |
+
# If that fails, try to extract JSON from the response
|
180 |
+
try:
|
181 |
+
start = response.index('[')
|
182 |
+
end = response.rindex(']') + 1
|
183 |
+
json_str = response[start:end]
|
184 |
+
return json.loads(json_str)
|
185 |
+
except (ValueError, json.JSONDecodeError):
|
186 |
+
print(f"Warning: Failed to parse LLM response as JSON. Response: {response[:100]}...")
|
187 |
+
return []
|
188 |
+
|
189 |
+
def cluster_and_filter_items(items, n_clusters=5, n_items=10):
|
190 |
+
# Combine title and body for text analysis
|
191 |
+
texts = [f"{item['title']} {item['body']}" for item in items]
|
192 |
+
|
193 |
+
# Create TF-IDF vectors
|
194 |
+
vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
|
195 |
+
tfidf_matrix = vectorizer.fit_transform(texts)
|
196 |
+
|
197 |
+
# Perform clustering
|
198 |
+
kmeans = KMeans(n_clusters=min(n_clusters, len(items)))
|
199 |
+
kmeans.fit(tfidf_matrix)
|
200 |
+
|
201 |
+
# Get cluster centers
|
202 |
+
cluster_centers = kmeans.cluster_centers_
|
203 |
+
|
204 |
+
# Find items closest to cluster centers
|
205 |
+
filtered_items = []
|
206 |
+
for i in range(min(n_clusters, len(items))):
|
207 |
+
cluster_items = [item for item, label in zip(items, kmeans.labels_) if label == i]
|
208 |
+
cluster_vectors = tfidf_matrix[kmeans.labels_ == i]
|
209 |
+
|
210 |
+
# Calculate similarities to cluster center
|
211 |
+
similarities = cosine_similarity(cluster_vectors, cluster_centers[i].reshape(1, -1)).flatten()
|
212 |
+
|
213 |
+
# Sort items by similarity and select top ones
|
214 |
+
sorted_items = [x for _, x in sorted(zip(similarities, cluster_items), key=lambda pair: pair[0], reverse=True)]
|
215 |
+
filtered_items.extend(sorted_items[:min(n_items // n_clusters, len(sorted_items))])
|
216 |
+
|
217 |
+
return filtered_items
|
218 |
+
|
219 |
+
def safe_filter_open_items(open_items, closed_patterns, n_items=10):
|
220 |
+
try:
|
221 |
+
# Combine title and body for text analysis
|
222 |
+
open_texts = [f"{item.get('title', '')} {item.get('body', '')}" for item in open_items]
|
223 |
+
pattern_texts = [f"{pattern.get('theme', '')} {pattern.get('description', '')}" for pattern in closed_patterns]
|
224 |
+
|
225 |
+
if not open_texts or not pattern_texts:
|
226 |
+
print("Warning: No open items or closed patterns to analyze.")
|
227 |
+
return []
|
228 |
+
|
229 |
+
# Create TF-IDF vectors
|
230 |
+
vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
|
231 |
+
tfidf_matrix = vectorizer.fit_transform(open_texts + pattern_texts)
|
232 |
+
|
233 |
+
# Split the matrix into open items and patterns
|
234 |
+
open_vectors = tfidf_matrix[:len(open_items)]
|
235 |
+
pattern_vectors = tfidf_matrix[len(open_items):]
|
236 |
+
|
237 |
+
# Calculate similarities between open items and patterns
|
238 |
+
similarities = cosine_similarity(open_vectors, pattern_vectors)
|
239 |
+
|
240 |
+
# Calculate the average similarity for each open item
|
241 |
+
avg_similarities = np.mean(similarities, axis=1)
|
242 |
+
|
243 |
+
# Sort open items by average similarity and select top ones
|
244 |
+
sorted_items = [x for _, x in sorted(zip(avg_similarities, open_items), key=lambda pair: pair[0], reverse=True)]
|
245 |
+
|
246 |
+
return sorted_items[:n_items]
|
247 |
+
except Exception as e:
|
248 |
+
print(f"Error in filtering open items: {str(e)}")
|
249 |
+
traceback.print_exc()
|
250 |
+
return open_items[:n_items] # Return first n_items if filtering fails
|
251 |
+
|
252 |
+
def filter_open_items(open_items, closed_patterns, n_items=10):
|
253 |
+
# Combine title and body for text analysis
|
254 |
+
open_texts = [f"{item['title']} {item['body']}" for item in open_items]
|
255 |
+
pattern_texts = [f"{pattern.get('theme', '')} {pattern.get('description', '')}" for pattern in closed_patterns]
|
256 |
+
|
257 |
+
# Create TF-IDF vectors
|
258 |
+
vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
|
259 |
+
tfidf_matrix = vectorizer.fit_transform(open_texts + pattern_texts)
|
260 |
+
|
261 |
+
# Split the matrix into open items and patterns
|
262 |
+
open_vectors = tfidf_matrix[:len(open_items)]
|
263 |
+
pattern_vectors = tfidf_matrix[len(open_items):]
|
264 |
+
|
265 |
+
# Calculate similarities between open items and patterns
|
266 |
+
similarities = cosine_similarity(open_vectors, pattern_vectors)
|
267 |
+
|
268 |
+
# Calculate the average similarity for each open item
|
269 |
+
avg_similarities = np.mean(similarities, axis=1)
|
270 |
+
|
271 |
+
# Sort open items by average similarity and select top ones
|
272 |
+
sorted_items = [x for _, x in sorted(zip(avg_similarities, open_items), key=lambda pair: pair[0], reverse=True)]
|
273 |
+
|
274 |
+
return sorted_items[:n_items]
|
275 |
+
|
276 |
+
def llm_analyze_closed_items(client, items, item_type):
|
277 |
+
prompt = f"""
|
278 |
+
Analyze the following closed GitHub {item_type}:
|
279 |
+
|
280 |
+
{items}
|
281 |
+
|
282 |
+
Based on these closed {item_type}, identify:
|
283 |
+
1. Common themes or recurring patterns
|
284 |
+
2. Areas where automation could streamline {item_type} management
|
285 |
+
3. Potential LLM-assisted workflows to improve the {item_type} process
|
286 |
+
4. Do not return anything other than the expected JSON object
|
287 |
+
|
288 |
+
For each identified pattern or theme, provide:
|
289 |
+
- A short title or theme name
|
290 |
+
- A brief description of the pattern
|
291 |
+
- Potential LLM-assisted solutions or workflows
|
292 |
+
|
293 |
+
Format your response as a list of JSON objects, like this:
|
294 |
+
[
|
295 |
+
{{
|
296 |
+
"theme": "Theme name",
|
297 |
+
"description": "Brief description of the pattern",
|
298 |
+
"llm_solution": "Potential LLM-assisted solution or workflow"
|
299 |
+
}},
|
300 |
+
...
|
301 |
+
]
|
302 |
+
"""
|
303 |
+
|
304 |
+
return safe_call_llm(client, prompt)
|
305 |
+
|
306 |
+
def llm_analyze_open_items(client, open_items, closed_patterns, item_type, repo_url):
|
307 |
+
prompt = f"""
|
308 |
+
Consider the following patterns identified in closed {item_type}:
|
309 |
+
|
310 |
+
{closed_patterns}
|
311 |
+
|
312 |
+
Now, analyze these open {item_type} in light of the above patterns:
|
313 |
+
|
314 |
+
{open_items}
|
315 |
+
|
316 |
+
For each open {item_type}:
|
317 |
+
1. Identify which pattern(s) it most closely matches
|
318 |
+
2. Suggest specific LLM-assisted workflows or automations that could be applied, based on the matched patterns
|
319 |
+
3. Explain how the suggested workflow would improve the handling of this {item_type}
|
320 |
+
4. Include the {item_type} number in your response
|
321 |
+
5. Do not return anything other than the expected JSON object
|
322 |
+
|
323 |
+
Format your response as a list of JSON objects, like this:
|
324 |
+
[
|
325 |
+
{{
|
326 |
+
"number": {item_type} number,
|
327 |
+
"matched_patterns": ["Pattern 1", "Pattern 2"],
|
328 |
+
"suggested_workflow": "Description of the suggested LLM-assisted workflow",
|
329 |
+
"expected_improvement": "Explanation of how this would improve the {item_type} handling"
|
330 |
+
}},
|
331 |
+
...
|
332 |
+
]
|
333 |
+
"""
|
334 |
+
|
335 |
+
return safe_call_llm(client, prompt)
|
336 |
+
|
337 |
+
def llm_analyze_issues(client, issues_data, repo_url):
|
338 |
+
filtered_closed_issues = issues_data['filtered_closed_issues']
|
339 |
+
all_closed_issues = issues_data['closed_issues']
|
340 |
+
open_issues = issues_data['open_issues']
|
341 |
+
|
342 |
+
closed_patterns = llm_analyze_closed_items(client, filtered_closed_issues, "issues")
|
343 |
+
relevant_open_issues = safe_filter_open_items(open_issues, closed_patterns, n_items=10)
|
344 |
+
open_issues_analysis = llm_analyze_open_items(client, relevant_open_issues, closed_patterns, "issues", repo_url)
|
345 |
+
|
346 |
+
summary_prompt = f"""
|
347 |
+
Summarize the analysis of closed and open issues:
|
348 |
+
|
349 |
+
Closed Issues Patterns:
|
350 |
+
{closed_patterns}
|
351 |
+
|
352 |
+
Open Issues Analysis:
|
353 |
+
{open_issues_analysis}
|
354 |
+
|
355 |
+
Provide a concise summary of:
|
356 |
+
1. Key patterns identified in closed issues
|
357 |
+
2. Most promising LLM-assisted workflows for handling open issues
|
358 |
+
3. Overall recommendations for improving issue management in this repository
|
359 |
+
4. For each suggested workflow, include the number of an open issue where it could be applied
|
360 |
+
5. Do not return anything other than the expected JSON object
|
361 |
+
|
362 |
+
Format your response as a JSON object with the following structure:
|
363 |
+
{{
|
364 |
+
"key_patterns": ["pattern1", "pattern2", ...],
|
365 |
+
"promising_workflows": [
|
366 |
+
{{
|
367 |
+
"workflow": "Description of the workflow",
|
368 |
+
"applicable_issue": issue_number
|
369 |
+
}},
|
370 |
+
...
|
371 |
+
],
|
372 |
+
"overall_recommendations": ["recommendation1", "recommendation2", ...]
|
373 |
+
}}
|
374 |
+
|
375 |
+
Total number of closed issues analyzed: {len(all_closed_issues)}
|
376 |
+
Total number of open issues: {len(open_issues)}
|
377 |
+
"""
|
378 |
+
|
379 |
+
summary = safe_call_llm(client, summary_prompt)
|
380 |
+
|
381 |
+
return {
|
382 |
+
'closed_patterns': closed_patterns,
|
383 |
+
'open_issues_analysis': open_issues_analysis,
|
384 |
+
'summary': summary
|
385 |
+
}
|
386 |
+
|
387 |
+
def llm_analyze_prs(client, prs_data, repo_url):
|
388 |
+
filtered_closed_prs = prs_data['filtered_closed_prs']
|
389 |
+
all_closed_prs = prs_data['closed_prs']
|
390 |
+
open_prs = prs_data['open_prs']
|
391 |
+
|
392 |
+
closed_patterns = llm_analyze_closed_items(client, filtered_closed_prs, "pull requests")
|
393 |
+
relevant_open_prs = safe_filter_open_items(open_prs, closed_patterns, n_items=10)
|
394 |
+
open_prs_analysis = llm_analyze_open_items(client, relevant_open_prs, closed_patterns, "pull requests", repo_url)
|
395 |
+
|
396 |
+
summary_prompt = f"""
|
397 |
+
Summarize the analysis of closed and open pull requests:
|
398 |
+
|
399 |
+
Closed PRs Patterns:
|
400 |
+
{closed_patterns}
|
401 |
+
|
402 |
+
Open PRs Analysis:
|
403 |
+
{open_prs_analysis}
|
404 |
+
|
405 |
+
Provide a concise summary of:
|
406 |
+
1. Key patterns identified in closed pull requests
|
407 |
+
2. Most promising LLM-assisted workflows for handling open pull requests
|
408 |
+
3. Overall recommendations for improving the PR process in this repository
|
409 |
+
4. For each suggested workflow, include the number of an open PR where it could be applied
|
410 |
+
5. Do not return anything other than the expected JSON object
|
411 |
+
|
412 |
+
Format your response as a JSON object with the following structure:
|
413 |
+
{{
|
414 |
+
"key_patterns": ["pattern1", "pattern2", ...],
|
415 |
+
"promising_workflows": [
|
416 |
+
{{
|
417 |
+
"workflow": "Description of the workflow",
|
418 |
+
"applicable_pr": pr_number
|
419 |
+
}},
|
420 |
+
...
|
421 |
+
],
|
422 |
+
"overall_recommendations": ["recommendation1", "recommendation2", ...]
|
423 |
+
}}
|
424 |
+
|
425 |
+
Total number of closed pull requests analyzed: {len(all_closed_prs)}
|
426 |
+
Total number of open pull requests: {len(open_prs)}
|
427 |
+
"""
|
428 |
+
|
429 |
+
summary = safe_call_llm(client, summary_prompt)
|
430 |
+
|
431 |
+
return {
|
432 |
+
'closed_patterns': closed_patterns,
|
433 |
+
'open_prs_analysis': open_prs_analysis,
|
434 |
+
'summary': summary
|
435 |
+
}
|
436 |
+
|
437 |
+
def llm_analyze_code(client, code_analysis):
|
438 |
+
semgrep_summary = "No Semgrep results available."
|
439 |
+
if code_analysis['semgrep_results']:
|
440 |
+
findings = code_analysis['semgrep_results'].get('results', [])
|
441 |
+
semgrep_summary = f"Semgrep found {len(findings)} potential issues:"
|
442 |
+
for finding in findings[:10]: # Limit to 10 findings to avoid token limits
|
443 |
+
semgrep_summary += f"\n- {finding['check_id']} in {finding['path']}: {finding['extra']['message']}"
|
444 |
+
|
445 |
+
file_contents_summary = ""
|
446 |
+
for file_path, content in code_analysis['file_contents'].items():
|
447 |
+
file_contents_summary += f"\n\nFile: {file_path}\nContent:\n{content[:1000]}..." # Limit content to avoid token limits
|
448 |
+
|
449 |
+
prompt = f"""
|
450 |
+
Analyze the following code structure, content, and Semgrep results:
|
451 |
+
|
452 |
+
File types: {code_analysis['file_types']}
|
453 |
+
|
454 |
+
Semgrep Analysis:
|
455 |
+
{semgrep_summary}
|
456 |
+
|
457 |
+
File Contents Summary:
|
458 |
+
{file_contents_summary}
|
459 |
+
|
460 |
+
Based on this information, provide an analysis covering:
|
461 |
+
1. Patterns in the codebase
|
462 |
+
2. Best practices being followed or missing
|
463 |
+
3. Areas for improvement
|
464 |
+
4. Potential security vulnerabilities or bugs (based on Semgrep results)
|
465 |
+
5. Opportunities for LLM-assisted automation in coding tasks
|
466 |
+
|
467 |
+
For LLM-assisted opportunities, consider tasks like code review, bug fixing, test generation, or documentation.
|
468 |
+
|
469 |
+
Respond ONLY with a JSON object in the following format:
|
470 |
+
{{
|
471 |
+
"patterns": ["pattern1", "pattern2", ...],
|
472 |
+
"best_practices": {{
|
473 |
+
"followed": ["practice1", "practice2", ...],
|
474 |
+
"missing": ["practice1", "practice2", ...]
|
475 |
+
}},
|
476 |
+
"areas_for_improvement": ["area1", "area2", ...],
|
477 |
+
"potential_vulnerabilities": [
|
478 |
+
{{
|
479 |
+
"description": "Description of the vulnerability",
|
480 |
+
"file_path": "Path to the affected file",
|
481 |
+
"severity": "High/Medium/Low"
|
482 |
+
}},
|
483 |
+
...
|
484 |
+
],
|
485 |
+
"llm_opportunities": [
|
486 |
+
{{
|
487 |
+
"task": "Description of the LLM-assisted task",
|
488 |
+
"file_path": "Path to the relevant file",
|
489 |
+
"improvement": "How LLM assistance would help"
|
490 |
+
}},
|
491 |
+
...
|
492 |
+
]
|
493 |
+
}}
|
494 |
+
|
495 |
+
Ensure your response is a valid JSON object and nothing else.
|
496 |
+
"""
|
497 |
+
|
498 |
+
return safe_call_llm(client, prompt)
|
499 |
+
|
500 |
+
def llm_synthesize_findings(client, code_analysis, issues_analysis, pr_analysis):
|
501 |
+
prompt = f"""
|
502 |
+
Synthesize the following analyses of a GitHub repository:
|
503 |
+
|
504 |
+
Code Analysis:
|
505 |
+
{code_analysis}
|
506 |
+
|
507 |
+
Issues Analysis:
|
508 |
+
{issues_analysis}
|
509 |
+
|
510 |
+
Pull Requests Analysis:
|
511 |
+
{pr_analysis}
|
512 |
+
|
513 |
+
Based on these analyses:
|
514 |
+
1. Summarize the key findings across all areas (code, issues, and PRs)
|
515 |
+
2. Identify the top 3-5 most promising opportunities for LLM-assisted workflows
|
516 |
+
3. For each opportunity, provide a specific example of how it could be implemented and the potential benefits
|
517 |
+
4. Suggest any additional areas of investigation or analysis that could provide further insights
|
518 |
+
"""
|
519 |
+
|
520 |
+
return call_llm(client, prompt, max_tokens=8192)
|
521 |
+
|
522 |
+
def generate_report(repo_info, code_analysis, issues_analysis, pr_analysis, final_analysis):
|
523 |
+
repo_url = f"https://github.com/{repo_info['owner']}/{repo_info['repo_name']}"
|
524 |
+
|
525 |
+
report = f"""# LLM-Assisted Workflow Analysis for {repo_info['owner']}/{repo_info['repo_name']}
|
526 |
+
|
527 |
+
## Repository Overview
|
528 |
+
- Owner: {repo_info['owner']}
|
529 |
+
- Repository: {repo_info['repo_name']}
|
530 |
+
- URL: {repo_url}
|
531 |
+
- File types: {code_analysis.get('file_types', 'N/A')}
|
532 |
+
|
533 |
+
## Code Analysis
|
534 |
+
"""
|
535 |
+
|
536 |
+
if isinstance(code_analysis.get('llm_analysis'), dict):
|
537 |
+
code_llm_analysis = code_analysis['llm_analysis']
|
538 |
+
|
539 |
+
report += "### Patterns Identified\n"
|
540 |
+
for pattern in code_llm_analysis.get('patterns', []):
|
541 |
+
report += f"- {pattern}\n"
|
542 |
+
|
543 |
+
report += "\n### Best Practices\n"
|
544 |
+
report += "#### Followed:\n"
|
545 |
+
for practice in code_llm_analysis.get('best_practices', {}).get('followed', []):
|
546 |
+
report += f"- {practice}\n"
|
547 |
+
report += "\n#### Missing:\n"
|
548 |
+
for practice in code_llm_analysis.get('best_practices', {}).get('missing', []):
|
549 |
+
report += f"- {practice}\n"
|
550 |
+
|
551 |
+
report += "\n### Areas for Improvement\n"
|
552 |
+
for area in code_llm_analysis.get('areas_for_improvement', []):
|
553 |
+
report += f"- {area}\n"
|
554 |
+
|
555 |
+
report += "\n### Potential Vulnerabilities\n"
|
556 |
+
for vuln in code_llm_analysis.get('potential_vulnerabilities', []):
|
557 |
+
report += f"- {vuln['description']} in `{vuln['file_path']}` (Severity: {vuln['severity']})\n"
|
558 |
+
|
559 |
+
report += "\n### LLM-Assisted Coding Opportunities\n"
|
560 |
+
for opp in code_llm_analysis.get('llm_opportunities', []):
|
561 |
+
report += f"- **Task:** {opp['task']}\n"
|
562 |
+
report += f" - **File:** `{opp['file_path']}`\n"
|
563 |
+
report += f" - **Improvement:** {opp['improvement']}\n\n"
|
564 |
+
else:
|
565 |
+
report += "No structured code analysis available.\n"
|
566 |
+
|
567 |
+
report += "\n## Issues Analysis\n"
|
568 |
+
|
569 |
+
if isinstance(issues_analysis.get('summary'), dict):
|
570 |
+
report += "### Key Patterns in Issues\n"
|
571 |
+
for pattern in issues_analysis['summary'].get('key_patterns', ['No key patterns identified.']):
|
572 |
+
report += f"- {pattern}\n"
|
573 |
+
|
574 |
+
report += "\n### Promising LLM-Assisted Workflows for Issues\n"
|
575 |
+
for workflow in issues_analysis['summary'].get('promising_workflows', []):
|
576 |
+
report += f"- **Workflow:** {workflow['workflow']}\n"
|
577 |
+
report += f" - **Example Issue:** [{workflow['applicable_issue']}]({repo_url}/issues/{workflow['applicable_issue']})\n\n"
|
578 |
+
|
579 |
+
report += "### Overall Recommendations for Issue Management\n"
|
580 |
+
for rec in issues_analysis['summary'].get('overall_recommendations', ['No recommendations available.']):
|
581 |
+
report += f"- {rec}\n"
|
582 |
+
else:
|
583 |
+
report += "No structured issues analysis available.\n"
|
584 |
+
|
585 |
+
report += "\n## Pull Requests Analysis\n"
|
586 |
+
|
587 |
+
if isinstance(pr_analysis.get('summary'), dict):
|
588 |
+
report += "### Key Patterns in Pull Requests\n"
|
589 |
+
for pattern in pr_analysis['summary'].get('key_patterns', ['No key patterns identified.']):
|
590 |
+
report += f"- {pattern}\n"
|
591 |
+
|
592 |
+
report += "\n### Promising LLM-Assisted Workflows for Pull Requests\n"
|
593 |
+
for workflow in pr_analysis['summary'].get('promising_workflows', []):
|
594 |
+
report += f"- **Workflow:** {workflow['workflow']}\n"
|
595 |
+
report += f" - **Example PR:** [{workflow['applicable_pr']}]({repo_url}/pull/{workflow['applicable_pr']})\n\n"
|
596 |
+
|
597 |
+
report += "### Overall Recommendations for PR Process\n"
|
598 |
+
for rec in pr_analysis['summary'].get('overall_recommendations', ['No recommendations available.']):
|
599 |
+
report += f"- {rec}\n"
|
600 |
+
else:
|
601 |
+
report += "No structured pull requests analysis available.\n"
|
602 |
+
|
603 |
+
report += f"\n## Synthesis and Recommendations\n{final_analysis}\n"
|
604 |
+
|
605 |
+
return report
|
606 |
+
|
607 |
+
def main(repo_input, max_issues, max_prs):
|
608 |
+
github_token = os.environ.get("GITHUB_TOKEN")
|
609 |
+
if not github_token:
|
610 |
+
print("Error: GITHUB_TOKEN environment variable not set.")
|
611 |
+
sys.exit(1)
|
612 |
+
|
613 |
+
anthropic_api_key = os.environ.get("ANTHROPIC_API_KEY")
|
614 |
+
if not anthropic_api_key:
|
615 |
+
print("Error: ANTHROPIC_API_KEY environment variable not set.")
|
616 |
+
sys.exit(1)
|
617 |
+
|
618 |
+
owner, repo_name = get_repo_info(repo_input)
|
619 |
+
repo_url = f"https://github.com/{owner}/{repo_name}"
|
620 |
+
|
621 |
+
g = Github(github_token)
|
622 |
+
github_repo = g.get_repo(f"{owner}/{repo_name}")
|
623 |
+
|
624 |
+
client = anthropic.Anthropic(api_key=anthropic_api_key)
|
625 |
+
|
626 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
627 |
+
try:
|
628 |
+
print(f"Cloning repository {owner}/{repo_name}...")
|
629 |
+
repo_path = clone_repo(owner, repo_name, temp_dir)
|
630 |
+
|
631 |
+
print("Analyzing code...")
|
632 |
+
code_analysis = analyze_code(repo_path)
|
633 |
+
code_analysis['llm_analysis'] = llm_analyze_code(client, code_analysis)
|
634 |
+
|
635 |
+
print(f"Analyzing issues (max {max_issues})...")
|
636 |
+
issues_data = analyze_issues(github_repo, max_issues)
|
637 |
+
issues_analysis = llm_analyze_issues(client, issues_data, repo_url)
|
638 |
+
|
639 |
+
print(f"Analyzing pull requests (max {max_prs})...")
|
640 |
+
prs_data = analyze_pull_requests(github_repo, max_prs)
|
641 |
+
pr_analysis = llm_analyze_prs(client, prs_data, repo_url)
|
642 |
+
|
643 |
+
print("Synthesizing findings...")
|
644 |
+
final_analysis = llm_synthesize_findings(
|
645 |
+
client,
|
646 |
+
code_analysis.get('llm_analysis', ''),
|
647 |
+
issues_analysis.get('summary', ''),
|
648 |
+
pr_analysis.get('summary', '')
|
649 |
+
)
|
650 |
+
|
651 |
+
repo_info = {
|
652 |
+
"owner": owner,
|
653 |
+
"repo_name": repo_name,
|
654 |
+
}
|
655 |
+
|
656 |
+
print("Generating report...")
|
657 |
+
report = generate_report(repo_info, code_analysis, issues_analysis, pr_analysis, final_analysis)
|
658 |
+
|
659 |
+
print("\nAnalysis Report:")
|
660 |
+
print(report)
|
661 |
+
|
662 |
+
# Save the report to a file
|
663 |
+
with open(f"{owner}_{repo_name}_analysis.md", "w") as f:
|
664 |
+
f.write(report)
|
665 |
+
print(f"\nReport saved to {owner}_{repo_name}_analysis.md")
|
666 |
+
|
667 |
+
except Exception as e:
|
668 |
+
print(f"An error occurred: {str(e)}")
|
669 |
+
traceback.print_exc()
|
670 |
+
finally:
|
671 |
+
print("Cleaning up...")
|
672 |
+
|
673 |
+
if __name__ == "__main__":
|
674 |
+
parser = argparse.ArgumentParser(description="Analyze a GitHub repository with limits on issues and PRs.")
|
675 |
+
parser.add_argument("repo", help="Repository slug (owner/repo) or URL")
|
676 |
+
parser.add_argument("--max_issues", type=int, default=10, help="Maximum number of issues to analyze")
|
677 |
+
parser.add_argument("--max_prs", type=int, default=10, help="Maximum number of pull requests to analyze")
|
678 |
+
|
679 |
+
args = parser.parse_args()
|
680 |
+
|
681 |
+
main(args.repo, args.max_issues, args.max_prs)
|