fix: final dead-owner refs -> gitea / gitea push helper
This commit is contained in:
+57
-75
@@ -1,85 +1,67 @@
|
|||||||
"""Push viktor-autoreg to GitHub via Git Data API (no git-remote-https on this machine)."""
|
"""Push viktor-autoreg files to Gitea via Git Data API.
|
||||||
import json, base64, os, glob, urllib.request, urllib.error
|
|
||||||
|
|
||||||
TOK = open(os.path.expanduser("~/tmp/viktor_reg/ghtok.txt")).read().strip()
|
Token: env GITEA_TOKEN, then ~/.gitea_token, then hermes scratch gitea_tok.txt.
|
||||||
OWNER = "gbonnet65923"
|
Usage: python push_repo.py [--apply]
|
||||||
REPO = "viktor-autoreg"
|
"""
|
||||||
API = "https://api.github.com"
|
import base64, glob, json, os, pathlib, urllib.error, urllib.request
|
||||||
|
|
||||||
def req(method, path, data=None, raw=False):
|
OWNER, REPO, BRANCH = "reform", "viktor-autoreg", "main"
|
||||||
|
API = f"https://git.reformboss.com/api/v1/repos/{OWNER}/{REPO}"
|
||||||
|
APPLY = "--apply" in os.sys.argv
|
||||||
|
|
||||||
|
|
||||||
|
def load_tok():
|
||||||
|
t = os.environ.get("GITEA_TOKEN", "").strip()
|
||||||
|
if t:
|
||||||
|
return t
|
||||||
|
for p in (pathlib.Path.home() / ".gitea_token",
|
||||||
|
pathlib.Path(r"C:/Users/User/AppData/Local/hermes/cache/scratch/gitea_tok.txt")):
|
||||||
|
if p.exists():
|
||||||
|
t = p.read_text(encoding="utf-8").strip()
|
||||||
|
if t:
|
||||||
|
return t
|
||||||
|
raise SystemExit("no gitea token")
|
||||||
|
|
||||||
|
|
||||||
|
TOK = load_tok()
|
||||||
|
|
||||||
|
|
||||||
|
def req(method, path, data=None):
|
||||||
r = urllib.request.Request(API + path, method=method,
|
r = urllib.request.Request(API + path, method=method,
|
||||||
data=json.dumps(data).encode() if data else None,
|
data=json.dumps(data).encode() if data is not None else None,
|
||||||
headers={"Authorization": f"token {TOK}", "User-Agent": "eni",
|
headers={"Authorization": "token " + TOK, "User-Agent": "eni",
|
||||||
"Accept": "application/vnd.github+json",
|
"Accept": "application/json", "Content-Type": "application/json"})
|
||||||
**({"Content-Type": "application/json"} if data else {})})
|
|
||||||
try:
|
try:
|
||||||
resp = urllib.request.urlopen(r, timeout=60)
|
with urllib.request.urlopen(r, timeout=60) as resp:
|
||||||
body = resp.read()
|
return json.loads(resp.read().decode() or "{}")
|
||||||
return json.loads(body) if not raw else body
|
|
||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError as e:
|
||||||
detail = e.read().decode()[:300]
|
print(f"HTTP {e.code} {method} {path}: {e.read().decode()[:200]}")
|
||||||
print(f"HTTP {e.code} on {method} {path}: {detail}")
|
|
||||||
if e.code in (409, 422) and "already exists" in detail:
|
|
||||||
return {"full_name": f"{OWNER}/{REPO}", "exists": True}
|
|
||||||
raise
|
raise
|
||||||
|
|
||||||
# 1. create repo
|
|
||||||
try:
|
|
||||||
repo = req("POST", "/user/repos", {"name": REPO, "description": "Viktor.com reverse API + signup door analysis + autoreg tooling", "private": False, "auto_init": False})
|
|
||||||
print("repo created:", repo["full_name"])
|
|
||||||
except urllib.error.HTTPError as e:
|
|
||||||
err = e.read().decode()
|
|
||||||
if "already exists" in err:
|
|
||||||
print("repo exists, continuing")
|
|
||||||
else:
|
|
||||||
raise
|
|
||||||
BR = "main"
|
|
||||||
# 2a. seed empty repo with initial commit (blob API requires non-empty repo)
|
|
||||||
readme_b64 = base64.b64encode(open(os.path.expanduser("~/tmp/viktor_reg/README.md"), "rb").read()).decode()
|
|
||||||
try:
|
|
||||||
c = req("PUT", f"/repos/{OWNER}/{REPO}/contents/README.md", {"message": "init", "content": readme_b64, "branch": BR})
|
|
||||||
print("seeded README:", c["commit"]["sha"][:10])
|
|
||||||
except urllib.error.HTTPError as e:
|
|
||||||
detail = e.read().decode()[:200]
|
|
||||||
if "already exists" in detail:
|
|
||||||
print("README already there")
|
|
||||||
else:
|
|
||||||
print("seed err:", e.code, detail); raise
|
|
||||||
|
|
||||||
# get base tree/commit for update
|
def main():
|
||||||
head = req("GET", f"/repos/{OWNER}/{REPO}/git/refs/heads/{BR}")
|
br = req("GET", f"/branches/{BRANCH}")
|
||||||
base_commit = head["object"]["sha"]
|
head = br["commit"]["id"]
|
||||||
base_tree = req("GET", f"/repos/{OWNER}/{REPO}/git/commits/{base_commit}")["tree"]["sha"]
|
base_tree = req("GET", f"/git/commits/{head}")["commit"]["tree"]["sha"]
|
||||||
print("base:", base_commit[:10], "tree:", base_tree[:10])
|
files = [p for p in glob.glob("**/*", recursive=True) if os.path.isfile(p) and ".git" not in p]
|
||||||
|
entries = []
|
||||||
|
for fp in files:
|
||||||
|
if APPLY:
|
||||||
|
blob = req("POST", "/git/blobs",
|
||||||
|
{"content": base64.b64encode(open(fp, "rb").read()).decode(), "encoding": "base64"})
|
||||||
|
sha = blob["sha"]
|
||||||
|
else:
|
||||||
|
sha = ""
|
||||||
|
entries.append({"path": fp.replace(os.sep, "/"), "mode": "100644", "type": "blob", "sha": sha})
|
||||||
|
print(("blob " if APPLY else "plan ") + fp)
|
||||||
|
print(len(entries), "files, apply=", APPLY)
|
||||||
|
if not APPLY or not entries:
|
||||||
|
return
|
||||||
|
tree = req("POST", "/git/trees", {"base_tree": base_tree, "tree": entries})
|
||||||
|
nc = req("POST", "/git/commits", {"message": "sync from local tree", "tree": tree["sha"], "parents": [head]})
|
||||||
|
req("PATCH", f"/git/refs/heads/{BRANCH}", {"sha": nc["sha"]})
|
||||||
|
print("pushed", nc["sha"][:10])
|
||||||
|
|
||||||
# 2. create blobs on top of seeded repo
|
|
||||||
files = []
|
|
||||||
for f in glob.glob(os.path.expanduser("~/tmp/viktor_reg/**/*"), recursive=True):
|
|
||||||
if os.path.isfile(f) and not f.endswith("ghtok.txt"):
|
|
||||||
files.append(f)
|
|
||||||
print("files:", [f.split("viktor_reg")[-1].replace(os.sep, "/") for f in files])
|
|
||||||
|
|
||||||
sha_cache = {}
|
if __name__ == "__main__":
|
||||||
for f in files:
|
main()
|
||||||
rel = f.split("viktor_reg")[-1].replace(os.sep, "/").lstrip("/")
|
|
||||||
content = base64.b64encode(open(f, "rb").read()).decode()
|
|
||||||
blob = req("POST", f"/repos/{OWNER}/{REPO}/git/blobs", {"content": content, "encoding": "base64"})
|
|
||||||
sha_cache[rel] = blob["sha"]
|
|
||||||
print("blob:", rel, blob["sha"][:10])
|
|
||||||
|
|
||||||
tree = req("POST", f"/repos/{OWNER}/{REPO}/git/trees", {
|
|
||||||
"base_tree": base_tree,
|
|
||||||
"tree": [{"path": p, "mode": "100644", "type": "blob", "sha": s} for p, s in sha_cache.items()]})
|
|
||||||
print("tree:", tree["sha"][:10])
|
|
||||||
|
|
||||||
commit = req("POST", f"/repos/{OWNER}/{REPO}/git/commits", {
|
|
||||||
"message": "viktor.com reverse API + signup doors + autoreg tools", "tree": tree["sha"], "parents": [base_commit]})
|
|
||||||
print("commit:", commit["sha"][:10])
|
|
||||||
|
|
||||||
try:
|
|
||||||
ref = req("POST", f"/repos/{OWNER}/{REPO}/git/refs", {"ref": f"refs/heads/{BR}", "sha": commit["sha"]})
|
|
||||||
print("ref created:", ref["object"]["sha"][:10])
|
|
||||||
except urllib.error.HTTPError:
|
|
||||||
ref = req("PATCH", f"/repos/{OWNER}/{REPO}/git/refs/heads/{BR}", {"sha": commit["sha"], "force": True})
|
|
||||||
print("ref updated:", ref["object"]["sha"][:10])
|
|
||||||
print("URL: https://github.com/%s/%s" % (OWNER, REPO))
|
|
||||||
|
|||||||
Reference in New Issue
Block a user