Repository navigation
Expand file tree
/
Copy pathgithub_sync_engine.py
More file actions
192 lines (164 loc) · 6.84 KB
/
Copy pathgithub_sync_engine.py
File metadata and controls
192 lines (164 loc) · 6.84 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
# =============================================================================
# github_sync_engine.py - Differential GitHub REST API Folder Sync Engine
# Designed and programmed by Mr.T
# =============================================================================
import base64
import hashlib
from pathlib import Path
from typing import Callable
from urllib.parse import quote
import requests
from sync_security import (
collect_local_files,
redact_secrets,
sanitize_branch_name,
sanitize_remote_prefix,
sanitize_repo_slug,
)
GITHUB_API_BASE = "https://api.github.com"
MAX_GITHUB_FILE_BYTES = 95 * 1024 * 1024
REQUEST_TIMEOUT = (15, 60)
def compute_git_blob_sha1(file_path: Path) -> str:
file_size = file_path.stat().st_size
hasher = hashlib.sha1()
hasher.update(f"blob {file_size}\0".encode("utf-8"))
with file_path.open("rb") as fh:
while True:
chunk = fh.read(262144)
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest()
def _fetch_remote_tree(
session: requests.Session,
owner: str,
repo: str,
branch: str,
) -> dict[str, str]:
encoded_branch = quote(branch, safe="")
ref_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/git/ref/heads/{encoded_branch}"
ref_resp = session.get(ref_url, timeout=REQUEST_TIMEOUT)
if ref_resp.status_code in (404, 409):
return {}
if ref_resp.status_code == 401:
raise RuntimeError("GitHub authentication failed (401 Unauthorized). Check your token.")
if ref_resp.status_code == 403:
raise RuntimeError("GitHub access denied or rate-limited (403 Forbidden).")
ref_resp.raise_for_status()
commit_sha = ref_resp.json().get("object", {}).get("sha", "")
if not commit_sha:
return {}
commit_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/git/commits/{commit_sha}"
commit_resp = session.get(commit_url, timeout=REQUEST_TIMEOUT)
commit_resp.raise_for_status()
tree_sha = commit_resp.json().get("tree", {}).get("sha", "")
if not tree_sha:
return {}
tree_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/git/trees/{tree_sha}?recursive=1"
tree_resp = session.get(tree_url, timeout=REQUEST_TIMEOUT)
tree_resp.raise_for_status()
remote_blobs: dict[str, str] = {}
for entry in tree_resp.json().get("tree", []):
if entry.get("type") == "blob" and entry.get("path") and entry.get("sha"):
remote_blobs[entry["path"]] = entry["sha"]
return remote_blobs
def run_folder_upload(
local_folder: str,
owner: str,
repo: str,
token: str,
branch: str = "main",
remote_prefix: str = "",
on_progress: Callable[[int, int, str], None] | None = None,
excluded_files: set[Path] | None = None,
) -> dict:
counts = {"created": 0, "updated": 0, "skipped": 0, "failed": 0}
logs: list[str] = []
def emit(current: int, total: int, line: str):
safe_line = redact_secrets(line, [token, (token or "").strip()])
logs.append(safe_line)
if callable(on_progress):
on_progress(current, total, safe_line)
try:
clean_owner = sanitize_repo_slug(owner, "Repo Owner")
clean_repo = sanitize_repo_slug(repo, "Repo Name")
clean_branch = sanitize_branch_name(branch)
clean_prefix = sanitize_remote_prefix(remote_prefix)
clean_token = (token or "").strip()
if not clean_token:
raise ValueError("GitHub access token is required.")
_root, file_items, sec_logs = collect_local_files(local_folder, excluded_files)
for s_log in sec_logs:
emit(0, max(len(file_items), 1), s_log)
except Exception as exc:
counts["failed"] += 1
emit(1, 1, f"[ERROR] {exc}")
return {"counts": counts, "logs": logs}
total = len(file_items)
if total == 0:
emit(0, 0, "[INFO] No eligible files found to sync.")
return {"counts": counts, "logs": logs}
session = requests.Session()
session.headers.update(
{
"Authorization": f"Bearer {clean_token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "GitSync-MultiCloud-MrT/1.2.0",
}
)
try:
emit(0, total, f"[INFO] Fetching remote tree for {clean_owner}/{clean_repo} ({clean_branch})...")
remote_blobs = _fetch_remote_tree(session, clean_owner, clean_repo, clean_branch)
except Exception as exc:
counts["failed"] = total
emit(total, total, f"[ERROR] {exc}")
return {"counts": counts, "logs": logs}
for idx, (abs_path, rel_posix) in enumerate(file_items, start=1):
remote_path = f"{clean_prefix}/{rel_posix}" if clean_prefix else rel_posix
try:
file_size = abs_path.stat().st_size
if file_size > MAX_GITHUB_FILE_BYTES:
counts["failed"] += 1
emit(
idx,
total,
f"[FAILED] {remote_path} (exceeds 95 MB GitHub API limit; use Drive/OneDrive)",
)
continue
local_sha = compute_git_blob_sha1(abs_path)
remote_sha = remote_blobs.get(remote_path)
if remote_sha and remote_sha == local_sha:
counts["skipped"] += 1
emit(idx, total, f"[SKIP] {remote_path} (unchanged)")
continue
encoded_b64 = base64.b64encode(abs_path.read_bytes()).decode("ascii")
encoded_remote = "/".join(quote(seg, safe="") for seg in remote_path.split("/"))
put_url = f"{GITHUB_API_BASE}/repos/{clean_owner}/{clean_repo}/contents/{encoded_remote}"
payload: dict = {
"message": f"{'Update' if remote_sha else 'Add'} {remote_path} via GitSync",
"content": encoded_b64,
"branch": clean_branch,
}
if remote_sha:
payload["sha"] = remote_sha
resp = session.put(put_url, json=payload, timeout=REQUEST_TIMEOUT)
if resp.status_code in (200, 201):
if remote_sha or resp.status_code == 200:
counts["updated"] += 1
emit(idx, total, f"[UPDATED] {remote_path}")
else:
counts["created"] += 1
emit(idx, total, f"[CREATED] {remote_path}")
else:
counts["failed"] += 1
err_msg = ""
try:
err_msg = resp.json().get("message", "")
except Exception:
err_msg = resp.text[:140]
emit(idx, total, f"[FAILED] {remote_path} (HTTP {resp.status_code}: {err_msg})")
except Exception as exc:
counts["failed"] += 1
emit(idx, total, f"[FAILED] {remote_path} ({exc})")
return {"counts": counts, "logs": logs}