68 lines
2.5 KiB
Python
68 lines
2.5 KiB
Python
"""Push viktor-autoreg files to Gitea via Git Data API.
|
|
|
|
Token: env GITEA_TOKEN, then ~/.gitea_token, then hermes scratch gitea_tok.txt.
|
|
Usage: python push_repo.py [--apply]
|
|
"""
|
|
import base64, glob, json, os, pathlib, urllib.error, urllib.request
|
|
|
|
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,
|
|
data=json.dumps(data).encode() if data is not None else None,
|
|
headers={"Authorization": "token " + TOK, "User-Agent": "eni",
|
|
"Accept": "application/json", "Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(r, timeout=60) as resp:
|
|
return json.loads(resp.read().decode() or "{}")
|
|
except urllib.error.HTTPError as e:
|
|
print(f"HTTP {e.code} {method} {path}: {e.read().decode()[:200]}")
|
|
raise
|
|
|
|
|
|
def main():
|
|
br = req("GET", f"/branches/{BRANCH}")
|
|
head = br["commit"]["id"]
|
|
base_tree = req("GET", f"/git/commits/{head}")["commit"]["tree"]["sha"]
|
|
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])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|