-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
210 lines (181 loc) · 7.34 KB
/
Copy pathapp.py
File metadata and controls
210 lines (181 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# =============================================================================
# app.py — Flask frontend with full token‑based GitHub automation
# =============================================================================
from flask import Flask, render_template, request, jsonify
import requests
from datetime import datetime
import os
from urllib.parse import urlparse
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", os.urandom(32))
# FastAPI backend base URL
API_BASE = os.environ.get("API_BASE", "http://localhost:8000")
# Duplicated method: Consider moving to separate Helper file
# -------------------------------------------------------------------------
# Helper: parse GitHub URL into (owner, repo, kind, number)
# -------------------------------------------------------------------------
def parse_github_url(url: str):
try:
path = urlparse(url).path.strip("/").split("/")
if len(path) < 4:
raise ValueError("URL path too short")
owner, repo, kind, number = path[0], path[1], path[2], path[3]
if kind not in ("pull", "pulls", "issues"):
raise ValueError(f"URL kind '{kind}' is not pull or issues")
api_kind = "pulls" if kind in ("pull", "pulls") else "issues"
return owner, repo, api_kind, int(number)
except Exception as e:
raise ValueError(f"Invalid GitHub URL: {e}")
# -------------------------------------------------------------------------
# Proxy helper that forwards the token header
# -------------------------------------------------------------------------
def _forward_to_backend(method, endpoint, token=None, json_data=None):
headers = {}
if token:
headers["X-GitHub-Token"] = token
url = f"{API_BASE}{endpoint}"
resp = requests.request(
method=method,
url=url,
headers=headers,
json=json_data,
timeout=30
)
# Forward the exact status code and error details
if not resp.ok:
try:
detail = resp.json().get("detail", resp.text)
except Exception:
detail = resp.text
return jsonify({"error": detail}), resp.status_code
return jsonify(resp.json())
# ------ ROUTES -----------
@app.route("/")
def index():
return render_template("index.html")
@app.route("/analyze", methods=["POST"])
def analyze():
try:
data = request.get_json()
flow = data.get("flow")
# ── Flow A: GitHub URL ────────────────────────────────────
if flow == "A":
pr_url = data.get("pr_url", "").strip()
if not pr_url:
return jsonify({"error": "Please enter a GitHub URL."}), 400
if "github.com" not in pr_url:
return jsonify({"error": "URL must be a github.com link."}), 400
if "/pull/" not in pr_url and "/issues/" not in pr_url:
return jsonify(
{"error": "URL must point to a PR (/pull/) or Issue (/issues/)."}
), 400
resp = requests.post(
f"{API_BASE}/predict-url",
json={"url": pr_url},
timeout=30,
)
resp.raise_for_status()
result = resp.json()
# ── Flow B: Manual entry ──────────────────────────────────
else:
title = data.get("title", "").strip()
if not title:
return jsonify({"error": "PR Title is required."}), 400
resp = requests.post(
f"{API_BASE}/predict",
json={
"title": title,
"body": data.get("body", ""),
},
timeout=30,
)
resp.raise_for_status()
result = resp.json()
# Manual flow: inject title so the card renders it
result["title"] = title
result["input_mode"] = "Manual"
result["pr_url"] = ""
# ── Shared metadata ───────────────────────────────────────
result["timestamp"] = datetime.now().strftime("%d %b %Y, %H:%M")
result["input_mode"] = "URL" if flow == "A" else "Manual"
raw_title = result.get("title", "PR Analysis")
result["display_title"] = (
raw_title[:85] + ("…" if len(raw_title) > 85 else "")
)
return jsonify(result)
except requests.exceptions.ConnectionError:
return jsonify(
{"error": "Cannot reach the backend. Is the FastAPI server running on port 8000?"}
), 503
except requests.exceptions.HTTPError as e:
# Forward backend error message to the UI
try:
detail = e.response.json().get("detail", str(e))
except Exception:
detail = str(e)
return jsonify({"error": detail}), e.response.status_code
except Exception as e:
return jsonify({"error": str(e)}), 500
# ------- NEW Endpoints ----------
# ----- Token‑based fetch (private repos) -----
@app.route("/fetch-issue", methods=["POST"])
def fetch_issue():
data = request.get_json()
url = data.get("url", "").strip()
token = data.get("token", "")
if not url or "github.com" not in url:
return jsonify({"error": "Valid GitHub URL required."}), 400
if not token:
return jsonify({"error": "GitHub token required for private repos."}), 401
try:
owner, repo, kind, number = parse_github_url(url)
except ValueError as e:
return jsonify({"error": str(e)}), 400
# Prepare request body for FastAPI /api/fetch-issue
repo_str = f"{owner}/{repo}"
payload = {
"repo": repo_str,
"number": number,
"kind": "auto"
}
return _forward_to_backend("POST", "/api/fetch-issue", token, payload)
# ----- Apply predicted labels to an issue/PR -----
@app.route("/apply-labels", methods=["POST"])
def apply_labels():
data = request.get_json()
repo = data.get("repo", "").strip()
number = data.get("number")
labels = data.get("labels", [])
token = data.get("token", "")
if not repo or not number or not labels:
return jsonify({"error": "Missing repo, number or labels."}), 400
if not token:
return jsonify({"error": "GitHub token required."}), 401
payload = {
"repo": repo,
"number": int(number),
"labels": labels
}
return _forward_to_backend("POST", "/api/apply-labels", token, payload)
# ----- Create a new issue with predicted labels -----
@app.route("/create-issue", methods=["POST"])
def create_issue():
data = request.get_json()
repo = data.get("repo", "").strip()
title = data.get("title", "").strip()
body = data.get("body", "")
labels = data.get("labels", [])
token = data.get("token", "")
if not repo or not title:
return jsonify({"error": "Repository and title are required."}), 400
if not token:
return jsonify({"error": "GitHub token required."}), 401
payload = {
"repo": repo,
"title": title,
"body": body,
"labels": labels
}
return _forward_to_backend("POST", "/api/create-issue", token, payload)
if __name__ == "__main__":
app.run(debug=True, port=5000)