Repository navigation
Expand file tree
/
Copy pathleetcode_to_github.py
More file actions
320 lines (257 loc) · 10.4 KB
/
Copy pathleetcode_to_github.py
File metadata and controls
320 lines (257 loc) · 10.4 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#!/usr/bin/env python3
"""
leetcode_to_github.py
======================
Automates:
1. Fetching your solved LeetCode problems (with full solution code)
2. Computing stats (by difficulty)
3. Building a folder structure: Difficulty/Topic/problem.ext
4. Generating a README.md with stats + a problems table
5. Pushing everything to GitHub (new or existing repo)
Usage:
python leetcode_to_github.py
Requires a .env file (copy from .env.example) filled with:
LEETCODE_SESSION=...
LEETCODE_CSRF_TOKEN=...
GITHUB_TOKEN=...
GITHUB_USERNAME=...
REPO_NAME=leetcode-solutions
"""
import os
import re
import sys
import time
import subprocess
from pathlib import Path
import requests
from dotenv import load_dotenv
from colorama import init, Fore, Style
init(autoreset=True)
load_dotenv()
LEETCODE_SESSION = os.getenv("LEETCODE_SESSION")
LEETCODE_CSRF_TOKEN = os.getenv("LEETCODE_CSRF_TOKEN")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
GITHUB_USERNAME = os.getenv("GITHUB_USERNAME")
REPO_NAME = os.getenv("REPO_NAME", "leetcode-solutions")
OUTPUT_DIR = Path(os.getenv("OUTPUT_DIR", "./" + REPO_NAME))
GRAPHQL_URL = "https://leetcode.com/graphql"
ALL_PROBLEMS_URL = "https://leetcode.com/api/problems/all/"
HEADERS = {
"Content-Type": "application/json",
"Referer": "https://leetcode.com",
"User-Agent": "Mozilla/5.0",
"x-csrftoken": LEETCODE_CSRF_TOKEN or "",
}
COOKIES = {
"LEETCODE_SESSION": LEETCODE_SESSION or "",
"csrftoken": LEETCODE_CSRF_TOKEN or "",
}
DIFFICULTY_MAP = {1: "Easy", 2: "Medium", 3: "Hard"}
LANG_EXT = {
"python3": "py", "python": "py", "java": "java", "cpp": "cpp",
"c": "c", "javascript": "js", "typescript": "ts", "csharp": "cs",
"golang": "go", "kotlin": "kt", "swift": "swift", "rust": "rs",
"ruby": "rb", "scala": "scala", "php": "php",
}
# ---------- helpers: colored logging ----------
def log_step(msg):
print(f"{Fore.CYAN}{Style.BRIGHT}{msg}{Style.RESET_ALL}")
def log_info(msg):
print(f"{Fore.WHITE} -> {msg}{Style.RESET_ALL}")
def log_success(msg):
print(f"{Fore.GREEN}{Style.BRIGHT}{msg}{Style.RESET_ALL}")
def log_warn(msg):
print(f"{Fore.YELLOW} -> {msg}{Style.RESET_ALL}")
def log_error(msg):
print(f"{Fore.RED}{Style.BRIGHT}{msg}{Style.RESET_ALL}")
def check_config():
missing = [k for k, v in {
"LEETCODE_SESSION": LEETCODE_SESSION,
"LEETCODE_CSRF_TOKEN": LEETCODE_CSRF_TOKEN,
"GITHUB_TOKEN": GITHUB_TOKEN,
"GITHUB_USERNAME": GITHUB_USERNAME,
}.items() if not v]
if missing:
log_error(f"[!] Missing required variables in .env: {', '.join(missing)}")
sys.exit(1)
# ---------- STEP 1: fetch solved problems ----------
def fetch_solved_problems():
log_step("[1/5] Fetching solved problems from LeetCode...")
resp = requests.get(ALL_PROBLEMS_URL, headers=HEADERS, cookies=COOKIES)
resp.raise_for_status()
data = resp.json()
solved = []
for item in data.get("stat_status_pairs", []):
if item.get("status") == "ac":
stat = item["stat"]
solved.append({
"id": stat["frontend_question_id"],
"title": stat["question__title"],
"slug": stat["question__title_slug"],
"difficulty": DIFFICULTY_MAP.get(item["difficulty"]["level"], "Unknown"),
})
log_info(f"Found {len(solved)} solved problems.")
return solved
def fetch_topics(slug):
query = {
"query": """
query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
topicTags { name }
}
}""",
"variables": {"titleSlug": slug},
}
r = requests.post(GRAPHQL_URL, headers=HEADERS, cookies=COOKIES, json=query)
if r.status_code != 200:
return ["Uncategorized"]
tags = r.json().get("data", {}).get("question", {}).get("topicTags", [])
return [t["name"] for t in tags] or ["Uncategorized"]
def fetch_latest_accepted(slug):
query = {
"query": """
query submissionList($offset: Int!, $limit: Int!, $questionSlug: String!) {
submissionList(offset: $offset, limit: $limit, questionSlug: $questionSlug) {
submissions { id statusDisplay lang timestamp }
}
}""",
"variables": {"offset": 0, "limit": 20, "questionSlug": slug},
}
r = requests.post(GRAPHQL_URL, headers=HEADERS, cookies=COOKIES, json=query)
if r.status_code != 200:
return None
subs = r.json().get("data", {}).get("submissionList", {}).get("submissions", [])
accepted = [s for s in subs if s["statusDisplay"] == "Accepted"]
if not accepted:
return None
latest = max(accepted, key=lambda s: int(s["timestamp"]))
detail_query = {
"query": """
query submissionDetails($submissionId: Int!) {
submissionDetails(submissionId: $submissionId) {
code
lang { name }
}
}""",
"variables": {"submissionId": int(latest["id"])},
}
r2 = requests.post(GRAPHQL_URL, headers=HEADERS, cookies=COOKIES, json=detail_query)
if r2.status_code != 200:
return None
detail = r2.json().get("data", {}).get("submissionDetails")
if not detail:
return None
return {"code": detail["code"], "lang": detail["lang"]["name"].lower().replace(" ", "")}
def enrich_problems(solved):
log_step("[1/5] Fetching topics and code for each problem (this may take a while)...")
enriched = []
for i, p in enumerate(solved, 1):
p["topics"] = fetch_topics(p["slug"])
sub = fetch_latest_accepted(p["slug"])
p["code"] = sub["code"] if sub else None
p["lang"] = sub["lang"] if sub else "python3"
enriched.append(p)
if i % 10 == 0 or i == len(solved):
log_info(f"{i}/{len(solved)}")
time.sleep(0.4) # avoid getting rate-limited
return enriched
# ---------- STEP 2: stats ----------
def build_stats(problems):
log_step("[2/5] Building stats...")
stats = {"Easy": 0, "Medium": 0, "Hard": 0, "Total": len(problems)}
for p in problems:
stats[p["difficulty"]] = stats.get(p["difficulty"], 0) + 1
return stats
# ---------- STEP 3: folder structure ----------
def slugify_folder(name):
return re.sub(r"[^a-zA-Z0-9\-]+", "-", name.strip()).strip("-")
def create_folder_structure(problems):
log_step("[4/5] Building folder structure (Difficulty/Topic)...")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
for p in problems:
primary_topic = slugify_folder(p["topics"][0]) if p["topics"] else "Uncategorized"
folder = OUTPUT_DIR / p["difficulty"] / primary_topic
folder.mkdir(parents=True, exist_ok=True)
ext = LANG_EXT.get(p["lang"], "txt")
filename = f"{p['id']:04d}-{slugify_folder(p['title']).lower()}.{ext}"
code = p["code"] or f"# TODO: add the solution code for {p['title']} manually\n"
(folder / filename).write_text(code, encoding="utf-8")
log_info(f"Folders created in {OUTPUT_DIR}")
# ---------- STEP 4: README ----------
def build_readme(problems, stats):
log_step("[3/5] Building README.md...")
lines = []
lines.append(f"# LeetCode Solutions — {GITHUB_USERNAME}\n")
lines.append("Automated sync from LeetCode to GitHub using Python.\n")
lines.append("## 📊 Stats\n")
lines.append(f"- **Total solved:** {stats['Total']}")
lines.append(f"- 🟢 Easy: {stats.get('Easy', 0)}")
lines.append(f"- 🟡 Medium: {stats.get('Medium', 0)}")
lines.append(f"- 🔴 Hard: {stats.get('Hard', 0)}\n")
lines.append("## 📁 Structure\n")
lines.append("```")
lines.append("Easy|Medium|Hard/")
lines.append(" └── Topic/")
lines.append(" └── 0001-two-sum.py")
lines.append("```\n")
lines.append("## ✅ Problems\n")
lines.append("| # | Title | Difficulty | Topics |")
lines.append("|---|-------|-----------|--------|")
for p in sorted(problems, key=lambda x: x["id"]):
link = f"https://leetcode.com/problems/{p['slug']}/"
topics = ", ".join(p["topics"])
lines.append(f"| {p['id']} | [{p['title']}]({link}) | {p['difficulty']} | {topics} |")
readme_path = OUTPUT_DIR / "README.md"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
readme_path.write_text("\n".join(lines), encoding="utf-8")
log_info(f"README written to {readme_path}")
# ---------- STEP 5: push to GitHub ----------
def ensure_github_repo():
r = requests.get(
f"https://api.github.com/repos/{GITHUB_USERNAME}/{REPO_NAME}",
headers={"Authorization": f"token {GITHUB_TOKEN}"},
)
if r.status_code == 200:
return
log_warn("Repo does not exist yet, creating it...")
r = requests.post(
"https://api.github.com/user/repos",
headers={"Authorization": f"token {GITHUB_TOKEN}"},
json={"name": REPO_NAME, "description": "Automated LeetCode solutions sync", "private": False},
)
r.raise_for_status()
def push_to_github():
log_step("[5/5] Pushing to GitHub...")
ensure_github_repo()
remote_url = f"https://{GITHUB_TOKEN}@github.com/{GITHUB_USERNAME}/{REPO_NAME}.git"
def run(cmd):
subprocess.run(cmd, cwd=OUTPUT_DIR, check=True)
if not (OUTPUT_DIR / ".git").exists():
run(["git", "init"])
run(["git", "checkout", "-b", "main"])
run(["git", "add", "."])
result = subprocess.run(["git", "diff", "--cached", "--quiet"], cwd=OUTPUT_DIR)
if result.returncode == 0:
log_warn("Nothing new to commit locally (will still push any pending local commits).")
else:
run(["git", "commit", "-m", f"sync: {len(list(OUTPUT_DIR.rglob('*.py')))} solutions updated"])
run(["git", "remote", "remove", "origin"]) if subprocess.run(
["git", "remote"], cwd=OUTPUT_DIR, capture_output=True, text=True
).stdout.strip() else None
run(["git", "remote", "add", "origin", remote_url])
run(["git", "push", "-u", "origin", "main", "--force"])
log_info(f"Pushed to https://github.com/{GITHUB_USERNAME}/{REPO_NAME}")
def main():
check_config()
solved = fetch_solved_problems()
if not solved:
log_error("[!] No solved problems found. Check your LEETCODE_SESSION.")
sys.exit(1)
problems = enrich_problems(solved)
stats = build_stats(problems)
build_readme(problems, stats)
create_folder_structure(problems)
push_to_github()
log_success("\n✅ Done, everything synced successfully!")
if __name__ == "__main__":
main()