Spaces:
Sleeping
Sleeping
Download ccpu_parser/github_sync.py from chouchouvs/ccpu: direct link, hf CLI and curl.
- Browser
- Download file 45.5 kB
-
https://huggingface.co/spaces/chouchouvs/ccpu/resolve/main/ccpu_parser/github_sync.py
- Command line
-
hf download hf://spaces/chouchouvs/ccpu/ccpu_parser/github_sync.py
-
curl -L -o github_sync.py https://huggingface.co/spaces/chouchouvs/ccpu/resolve/main/ccpu_parser/github_sync.py
45.5 kB
# ccpu_parser/github_sync.py
# -*- coding: utf-8 -*-
"""
github_sync.py — Synchronisation du dépôt Hugging Face Space vers un dépôt GitHub
=================================================================================
Ce que fait ce fichier
----------------------
- Fournit une brique de synchronisation Git robuste pour pousser le dépôt courant
du Space Hugging Face vers un dépôt GitHub distant via HTTPS.
- Utilise un token GitHub injecté via variable d'environnement / secret HF.
- N'enregistre jamais le token dans le remote Git local.
- Réalise un pré-contrôle GitHub avant le push pour faciliter le diagnostic.
- Gère plusieurs stratégies de push pour couvrir le cas classique où le dépôt
GitHub a déjà un commit initial (README, .gitignore...) qui diverge du repo HF.
- Corrige explicitement le cas `--force-with-lease` + push vers URL directe en
utilisant une lease explicite basée sur le SHA réellement fetché du ref distant.
- Ajoute un fallback "snapshot repo" : si le dépôt local HF présente des objets
Git manquants/incohérents au moment du push (`index-pack failed`, `did not receive
expected object`, etc.), on reconstruit un dépôt Git temporaire propre à partir
du working tree courant, puis on pousse ce snapshot vers GitHub.
Pourquoi ce fichier existe
--------------------------
- Permet de mirrorer progressivement le code du Space vers GitHub.
- Prépare une migration douce vers Coolify / serveur perso.
- Evite les manipulations manuelles répétitives de git add / commit / push.
- Rend le diagnostic beaucoup plus lisible dans les logs Hugging Face.
Variables d'environnement supportées
------------------------------------
- GITHUB_TOKEN : token GitHub utilisé pour le push HTTPS.
- GITHUB_REPO : repo cible au format "owner/repository".
- GITHUB_BRANCH : branche cible GitHub (défaut: branche courante ou "main").
- GITHUB_REMOTE_NAME : nom logique du remote local (défaut: "github").
- GITHUB_COMMITTER_NAME : nom de commit Git (défaut: "HF Space Sync Bot").
- GITHUB_COMMITTER_EMAIL : email de commit Git (défaut: "hf-space-sync@example.com").
- GITHUB_PUSH_MODE : stratégie de push :
* "auto" -> push normal, puis fallback --force-with-lease si divergence
* "fast_forward_only" -> push normal uniquement
* "force_with_lease" -> push direct avec --force-with-lease explicite
* "force" -> push direct avec --force
- GITHUB_ALLOW_SNAPSHOT_FALLBACK : "1"/"true"/"yes" pour autoriser le fallback snapshot
en cas de dépôt local incomplet/corrompu (défaut: "1").
Fonctions principales
---------------------
- sync_repo_to_github(...)
Point d'entrée haut niveau. Vérifie la conf, prépare le remote, détecte les
changements, commit si nécessaire, puis pousse vers GitHub.
- push_to_github(...)
Exécute le push HTTPS authentifié vers GitHub sans persister le token.
- github_preflight_check(...)
Valide le token, le repo cible et l'état de la branche distante autant que possible.
- commit_all_if_needed(...)
Stage + commit les changements si le working tree n'est pas propre.
- ensure_clean_github_remote(...)
Crée ou met à jour un remote local propre, sans secret dans son URL.
- get_repo_root(...)
Détecte la racine du dépôt courant.
- has_worktree_changes(...)
Indique si le dépôt contient des changements non commités.
- git_fetch_remote_branch(...)
Récupère la branche distante en local.
- get_ref_sha(...)
Lit le SHA d'une ref git locale.
- build_force_with_lease_arg(...)
Construit l'argument `--force-with-lease=refs/heads/<branch>:<sha>`.
- create_snapshot_repo_from_worktree(...)
Construit un dépôt Git temporaire neuf à partir du working tree courant.
- push_snapshot_repo_to_github(...)
Pousse le dépôt snapshot temporaire vers GitHub.
Notes de sécurité
-----------------
- Le token n'est jamais écrit dans "git remote -v".
- Le token n'est jamais loggé.
- L'URL authentifiée est construite de façon éphémère uniquement pour la commande push.
- Les sorties de commande sont nettoyées avant logging lorsqu'une URL potentiellement
sensible pourrait apparaître.
Dépendances
-----------
- Standard library uniquement.
- Nécessite que git soit présent dans l'environnement d'exécution.
"""
from __future__ import annotations
import json
import logging
import os
import shutil
import subprocess
import tempfile
import urllib.error
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional
LOGGER = logging.getLogger(__name__)
@dataclass
class GitHubSyncConfig:
"""
Porte la configuration de synchronisation GitHub.
Attributs
---------
repo : str
Dépôt cible GitHub au format "owner/repository".
token : str
Token GitHub utilisé pour le push HTTPS.
branch : str
Branche cible sur GitHub.
remote_name : str
Nom du remote local purement informatif.
committer_name : str
Nom d'auteur/committer utilisé pour les commits automatiques.
committer_email : str
Email d'auteur/committer utilisé pour les commits automatiques.
commit_message : str
Message de commit par défaut.
push_mode : str
Stratégie de push :
- auto
- fast_forward_only
- force_with_lease
- force
allow_snapshot_fallback : bool
Active le fallback qui reconstruit un dépôt snapshot propre si le dépôt
local HF a des objets Git manquants / incohérents.
"""
repo: str
token: str
branch: str
remote_name: str = "github"
committer_name: str = "HF Space Sync Bot"
committer_email: str = "hf-space-sync@example.com"
commit_message: str = "chore(sync): mirror Hugging Face Space to GitHub"
push_mode: str = "auto"
allow_snapshot_fallback: bool = True
class GitHubSyncError(RuntimeError):
"""
Exception métier pour la synchronisation GitHub.
"""
pass
class GitCommandError(GitHubSyncError):
"""
Exception détaillée pour les erreurs de commande git.
"""
def __init__(
self,
message: str,
command: List[str],
returncode: int,
stdout: str = "",
stderr: str = "",
) -> None:
self.command = command
self.returncode = returncode
self.stdout = stdout or ""
self.stderr = stderr or ""
details = [message, f"rc={returncode}"]
if self.stdout.strip():
details.append(f"stdout={self.stdout.strip()}")
if self.stderr.strip():
details.append(f"stderr={self.stderr.strip()}")
super().__init__(" | ".join(details))
def ensure_logger_configured(level: int = logging.INFO) -> None:
"""
Configure un logging minimal si rien n'est déjà configuré.
Paramètres
----------
level : int
Niveau de log standard logging.
"""
root = logging.getLogger()
if not root.handlers:
logging.basicConfig(
level=level,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
def _mask_token(value: str, token: Optional[str]) -> str:
"""
Masque le token dans une chaîne si présent.
"""
if not value:
return value
if token:
value = value.replace(token, "***GITHUB_TOKEN***")
return value
def _mask_sensitive_url(value: str) -> str:
"""
Masque une URL GitHub potentiellement authentifiée pour les logs.
"""
if "github.com" in value and "://" in value and "@" in value:
try:
prefix, suffix = value.split("://", 1)
if "@" in suffix:
_, host_path = suffix.split("@", 1)
return f"{prefix}://***@{host_path}"
except Exception:
return value
return value
def _sanitize_text(value: str, token: Optional[str]) -> str:
"""
Nettoie une chaîne pour logging / exceptions.
"""
cleaned = value or ""
cleaned = _mask_token(cleaned, token)
cleaned = _mask_sensitive_url(cleaned)
return cleaned
def _truthy_env(value: str) -> bool:
"""
Convertit une valeur de variable d'environnement en booléen.
"""
return value.strip().lower() in {"1", "true", "yes", "y", "on"}
def _build_base_env(extra_env: Optional[dict] = None) -> dict:
"""
Construit un environnement stable pour les commandes git dans HF.
Objectif :
- désactiver les prompts interactifs ;
- calmer les helpers de credentials qui peuvent générer des warnings
parasites dans certains conteneurs sans HOME/XDG standard.
"""
env = os.environ.copy()
env.setdefault("GIT_TERMINAL_PROMPT", "0")
env.setdefault("GCM_INTERACTIVE", "Never")
env.setdefault("XDG_CONFIG_HOME", "/tmp")
env.setdefault("HOME", "/tmp")
if extra_env:
env.update(extra_env)
return env
def run_cmd(
args: List[str],
cwd: Path,
token: Optional[str] = None,
check: bool = True,
env: Optional[dict] = None,
) -> subprocess.CompletedProcess:
"""
Exécute une commande shell de manière journalisée et sécurisée.
"""
safe_args = [_sanitize_text(str(a), token) for a in args]
LOGGER.info("[GITHUB_SYNC] RUN | cwd=%s | cmd=%s", cwd, " ".join(safe_args))
full_env = _build_base_env(env)
try:
result = subprocess.run(
args,
cwd=str(cwd),
env=full_env,
text=True,
capture_output=True,
check=False,
)
except FileNotFoundError as exc:
raise GitHubSyncError(
f"Commande introuvable: {args[0]}. Git est-il installé dans l'environnement ?"
) from exc
stdout_clean = _sanitize_text(result.stdout or "", token).strip()
stderr_clean = _sanitize_text(result.stderr or "", token).strip()
if stdout_clean:
LOGGER.info("[GITHUB_SYNC] STDOUT | %s", stdout_clean)
if stderr_clean:
LOGGER.warning("[GITHUB_SYNC] STDERR | %s", stderr_clean)
if check and result.returncode != 0:
raise GitCommandError(
message=f"Commande échouée: {' '.join(safe_args)}",
command=safe_args,
returncode=result.returncode,
stdout=stdout_clean,
stderr=stderr_clean,
)
return result
def ensure_git_available(cwd: Path) -> None:
"""
Vérifie que git est installé et exécutable.
"""
run_cmd(["git", "--version"], cwd=cwd, check=True)
LOGGER.info("[GITHUB_SYNC] Git détecté avec succès.")
def load_github_sync_config_from_env(
default_commit_message: str = "chore(sync): mirror Hugging Face Space to GitHub",
) -> GitHubSyncConfig:
"""
Charge la configuration depuis les variables d'environnement.
"""
repo = (os.getenv("GITHUB_REPO") or "").strip()
token = (os.getenv("GITHUB_TOKEN") or "").strip()
branch = (os.getenv("GITHUB_BRANCH") or "").strip()
remote_name = (os.getenv("GITHUB_REMOTE_NAME") or "github").strip() or "github"
committer_name = (os.getenv("GITHUB_COMMITTER_NAME") or "HF Space Sync Bot").strip()
committer_email = (os.getenv("GITHUB_COMMITTER_EMAIL") or "hf-space-sync@example.com").strip()
push_mode = (os.getenv("GITHUB_PUSH_MODE") or "auto").strip().lower()
allow_snapshot_fallback = _truthy_env(os.getenv("GITHUB_ALLOW_SNAPSHOT_FALLBACK", "1"))
allowed_modes = {"auto", "fast_forward_only", "force_with_lease", "force"}
if not repo:
raise GitHubSyncError(
"Variable d'environnement manquante: GITHUB_REPO (attendu: owner/repository)."
)
if not token:
raise GitHubSyncError("Variable d'environnement manquante: GITHUB_TOKEN.")
if not branch:
branch = "main"
if push_mode not in allowed_modes:
raise GitHubSyncError(
f"GITHUB_PUSH_MODE invalide: '{push_mode}'. "
f"Valeurs autorisées: {', '.join(sorted(allowed_modes))}"
)
return GitHubSyncConfig(
repo=repo,
token=token,
branch=branch,
remote_name=remote_name,
committer_name=committer_name,
committer_email=committer_email,
commit_message=default_commit_message,
push_mode=push_mode,
allow_snapshot_fallback=allow_snapshot_fallback,
)
def parse_repo_slug(repo: str) -> tuple[str, str]:
"""
Décompose un slug GitHub owner/repository.
"""
parts = [x.strip() for x in repo.split("/") if x.strip()]
if len(parts) != 2:
raise GitHubSyncError(
f"GITHUB_REPO invalide: '{repo}'. Format attendu: owner/repository"
)
return parts[0], parts[1]
def github_api_request(
path: str,
token: str,
method: str = "GET",
) -> tuple[int, Dict[str, Any], Dict[str, str]]:
"""
Exécute une requête simple sur l'API GitHub.
"""
url = f"https://api.github.com{path}"
req = urllib.request.Request(
url=url,
method=method,
headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "ccpu-hf-space-github-sync",
},
)
try:
with urllib.request.urlopen(req, timeout=20) as resp:
raw = resp.read().decode("utf-8", errors="replace")
data = json.loads(raw) if raw.strip() else {}
headers = {k: v for k, v in resp.headers.items()}
return resp.status, data, headers
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
try:
data = json.loads(raw) if raw.strip() else {}
except Exception:
data = {"message": raw}
headers = {k: v for k, v in exc.headers.items()} if exc.headers else {}
return exc.code, data, headers
except Exception as exc:
raise GitHubSyncError(f"Erreur réseau GitHub API sur {path}: {exc}") from exc
def github_preflight_check(repo: str, token: str, branch: str) -> dict:
"""
Valide le token GitHub, le dépôt cible et l'état général de la branche.
"""
owner, repo_name = parse_repo_slug(repo)
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | validation du token GitHub...")
st_user, user_payload, _ = github_api_request("/user", token=token)
if st_user != 200:
raise GitHubSyncError(
f"Préflight GitHub KO: token invalide ou refusé (GET /user -> {st_user}) | "
f"message={user_payload.get('message')}"
)
login = user_payload.get("login")
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | token valide | login=%s", login)
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | validation du repo cible %s...", repo)
st_repo, repo_payload, repo_headers = github_api_request(
f"/repos/{owner}/{repo_name}",
token=token,
)
if st_repo == 404:
raise GitHubSyncError(
f"Préflight GitHub KO: dépôt '{repo}' introuvable ou inaccessible avec ce token."
)
if st_repo != 200:
raise GitHubSyncError(
f"Préflight GitHub KO: GET /repos/{repo} -> {st_repo} | "
f"message={repo_payload.get('message')}"
)
default_branch = repo_payload.get("default_branch")
private = repo_payload.get("private")
permissions = repo_payload.get("permissions") or {}
can_push = permissions.get("push")
archived = bool(repo_payload.get("archived"))
disabled = bool(repo_payload.get("disabled"))
LOGGER.info(
"[GITHUB_SYNC] PREFLIGHT | repo_ok=%s | private=%s | default_branch=%s | can_push=%s | archived=%s | disabled=%s",
True, private, default_branch, can_push, archived, disabled
)
if archived:
raise GitHubSyncError(
f"Préflight GitHub KO: le dépôt '{repo}' est archivé, donc non pushable."
)
if disabled:
raise GitHubSyncError(
f"Préflight GitHub KO: le dépôt '{repo}' est désactivé."
)
if can_push is False:
raise GitHubSyncError(
f"Préflight GitHub KO: le token n'a pas le droit de push sur '{repo}'."
)
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | vérification branche distante '%s'...", branch)
st_branch, branch_payload, _ = github_api_request(
f"/repos/{owner}/{repo_name}/branches/{branch}",
token=token,
)
branch_exists = st_branch == 200
protected = False
if branch_exists:
protected = bool(branch_payload.get("protected"))
LOGGER.info(
"[GITHUB_SYNC] PREFLIGHT | branche distante existante=%s | protected=%s",
True, protected
)
elif st_branch == 404:
LOGGER.info(
"[GITHUB_SYNC] PREFLIGHT | branche distante '%s' absente pour l'instant (cas acceptable).",
branch
)
else:
LOGGER.warning(
"[GITHUB_SYNC] PREFLIGHT | impossible de lire la branche distante '%s' | status=%s | message=%s",
branch,
st_branch,
branch_payload.get("message"),
)
return {
"ok": True,
"token_login": login,
"repo": repo,
"private": private,
"default_branch": default_branch,
"branch": branch,
"branch_exists": branch_exists,
"branch_protected": protected,
"repo_permissions": permissions,
"accepted_permissions_hint": repo_headers.get("X-Accepted-GitHub-Permissions"),
}
def get_repo_root(cwd: Optional[Path] = None) -> Path:
"""
Détecte la racine du dépôt git courant.
"""
cwd = cwd or Path.cwd()
result = run_cmd(
["git", "rev-parse", "--show-toplevel"],
cwd=cwd,
check=True,
)
repo_root = Path((result.stdout or "").strip())
if not repo_root.exists():
raise GitHubSyncError(f"Racine git introuvable ou invalide: {repo_root}")
LOGGER.info("[GITHUB_SYNC] Repo root détecté: %s", repo_root)
return repo_root
def get_current_branch(repo_root: Path) -> str:
"""
Récupère la branche courante si possible.
"""
result = run_cmd(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
cwd=repo_root,
check=False,
)
branch = (result.stdout or "").strip()
if not branch or branch == "HEAD":
branch = "main"
LOGGER.info("[GITHUB_SYNC] Branche courante détectée: %s", branch)
return branch
def has_worktree_changes(repo_root: Path) -> bool:
"""
Indique si le dépôt contient des changements non commités.
"""
result = run_cmd(
["git", "status", "--porcelain"],
cwd=repo_root,
check=True,
)
dirty = bool((result.stdout or "").strip())
LOGGER.info("[GITHUB_SYNC] Working tree dirty=%s", dirty)
return dirty
def ensure_git_identity(repo_root: Path, name: str, email: str) -> None:
"""
Définit localement l'identité git si nécessaire.
"""
current_name = run_cmd(
["git", "config", "--get", "user.name"],
cwd=repo_root,
check=False,
)
current_email = run_cmd(
["git", "config", "--get", "user.email"],
cwd=repo_root,
check=False,
)
if not (current_name.stdout or "").strip():
run_cmd(["git", "config", "user.name", name], cwd=repo_root, check=True)
LOGGER.info("[GITHUB_SYNC] user.name configuré localement: %s", name)
if not (current_email.stdout or "").strip():
run_cmd(["git", "config", "user.email", email], cwd=repo_root, check=True)
LOGGER.info("[GITHUB_SYNC] user.email configuré localement: %s", email)
def ensure_clean_github_remote(repo_root: Path, remote_name: str, repo: str) -> str:
"""
Crée ou met à jour un remote local propre vers GitHub, sans secret.
"""
clean_url = f"https://github.com/{repo}.git"
existing = run_cmd(
["git", "remote"],
cwd=repo_root,
check=True,
)
remotes = {
line.strip()
for line in (existing.stdout or "").splitlines()
if line.strip()
}
if remote_name in remotes:
run_cmd(
["git", "remote", "set-url", remote_name, clean_url],
cwd=repo_root,
check=True,
)
LOGGER.info(
"[GITHUB_SYNC] Remote '%s' mis à jour vers %s",
remote_name,
clean_url,
)
else:
run_cmd(
["git", "remote", "add", remote_name, clean_url],
cwd=repo_root,
check=True,
)
LOGGER.info(
"[GITHUB_SYNC] Remote '%s' ajouté vers %s",
remote_name,
clean_url,
)
return clean_url
def build_authenticated_push_url(repo: str, token: str) -> str:
"""
Construit une URL HTTPS authentifiée éphémère pour le push.
"""
return f"https://x-access-token:{token}@github.com/{repo}.git"
def stage_all_changes(repo_root: Path) -> None:
"""
Stage l'ensemble des changements du dépôt.
"""
run_cmd(["git", "add", "-A"], cwd=repo_root, check=True)
LOGGER.info("[GITHUB_SYNC] Tous les changements ont été ajoutés à l'index.")
def commit_all_if_needed(
repo_root: Path,
commit_message: str,
committer_name: str,
committer_email: str,
) -> bool:
"""
Commit les changements si nécessaire.
"""
if not has_worktree_changes(repo_root):
LOGGER.info("[GITHUB_SYNC] Aucun changement à committer.")
return False
ensure_git_identity(repo_root, committer_name, committer_email)
stage_all_changes(repo_root)
result = run_cmd(
["git", "commit", "-m", commit_message],
cwd=repo_root,
check=False,
env={
"GIT_AUTHOR_NAME": committer_name,
"GIT_AUTHOR_EMAIL": committer_email,
"GIT_COMMITTER_NAME": committer_name,
"GIT_COMMITTER_EMAIL": committer_email,
},
)
stdout = (result.stdout or "") + "\n" + (result.stderr or "")
merged = stdout.lower()
if result.returncode == 0:
LOGGER.info("[GITHUB_SYNC] Commit créé avec succès.")
return True
if "nothing to commit" in merged or "nothing added to commit" in merged:
LOGGER.info("[GITHUB_SYNC] Rien à committer après stage.")
return False
raise GitCommandError(
message="Échec du commit Git",
command=["git", "commit", "-m", commit_message],
returncode=result.returncode,
stdout=_sanitize_text(result.stdout or "", None),
stderr=_sanitize_text(result.stderr or "", None),
)
def diagnose_push_failure(exc: GitCommandError) -> str:
"""
Produit un diagnostic métier lisible à partir d'une erreur de push Git.
"""
blob = f"{exc.stdout}\n{exc.stderr}".lower()
if "authentication failed" in blob or "could not read username" in blob:
return (
"Push GitHub refusé: authentification HTTPS en échec. "
"Vérifie GITHUB_TOKEN et son injection dans les secrets du Space."
)
if "repository not found" in blob:
return (
"Push GitHub refusé: dépôt introuvable ou non accessible. "
"Vérifie GITHUB_REPO (owner/repository) et les droits du token."
)
if "permission denied" in blob or "write access to repository not granted" in blob:
return (
"Push GitHub refusé: le token ne semble pas avoir l'accès en écriture au dépôt."
)
if "protected branch hook declined" in blob or "gh006" in blob:
return (
"Push GitHub refusé: la branche distante est protégée. "
"Pousse vers une autre branche ou ajuste la règle de protection."
)
if "push declined due to repository rule violations" in blob:
return (
"Push GitHub refusé par une règle de dépôt GitHub "
"(rulesets / policy / protection)."
)
if "push protection" in blob or "secret scanning" in blob or "blocked by" in blob:
return (
"Push GitHub bloqué par la détection de secrets ou une protection de sécurité. "
"Vérifie que tu ne commits pas de token, clé ou secret dans le repo."
)
if "stale info" in blob:
return (
"Push GitHub refusé car la lease force-with-lease n'est plus valide "
"par rapport à l'état distant attendu."
)
if "non-fast-forward" in blob or "fetch first" in blob or "[rejected]" in blob:
return (
"Push GitHub refusé car l'historique distant a divergé (non-fast-forward)."
)
if "did not receive expected object" in blob or "index-pack failed" in blob or "remote unpack failed" in blob:
return (
"Push GitHub refusé car le dépôt source semble avoir des objets Git manquants "
"ou un historique local incomplet/incohérent."
)
return (
"Push GitHub refusé. Consulte le stderr détaillé remonté dans l'exception/log pour "
"connaître le motif exact renvoyé par GitHub."
)
def is_non_fast_forward_error(exc: GitCommandError) -> bool:
"""
Détecte un rejet de type non-fast-forward / fetch first.
"""
blob = f"{exc.stdout}\n{exc.stderr}".lower()
return (
"non-fast-forward" in blob
or "fetch first" in blob
or "[rejected]" in blob
)
def is_missing_object_pack_error(exc: GitCommandError) -> bool:
"""
Détecte un rejet de type objets Git manquants / unpack distant échoué.
Cas typiques :
- did not receive expected object
- remote unpack failed: index-pack failed
- missing object / bad object
"""
blob = f"{exc.stdout}\n{exc.stderr}".lower()
return (
"did not receive expected object" in blob
or "index-pack failed" in blob
or "remote unpack failed" in blob
or "missing object" in blob
or "bad object" in blob
)
def git_fetch_remote_branch(
repo_root: Path,
repo: str,
branch: str,
token: str,
) -> None:
"""
Récupère la branche distante dans refs/remotes/github/<branch>.
"""
push_url = build_authenticated_push_url(repo, token)
run_cmd(
[
"git",
"-c", "credential.helper=",
"fetch",
"--prune",
push_url,
f"refs/heads/{branch}:refs/remotes/github/{branch}",
],
cwd=repo_root,
token=token,
check=True,
)
LOGGER.info(
"[GITHUB_SYNC] Fetch distante effectué pour préparer un éventuel force-with-lease."
)
def get_ref_sha(repo_root: Path, ref_name: str) -> str:
"""
Lit le SHA exact d'une ref git locale.
"""
result = run_cmd(
["git", "rev-parse", ref_name],
cwd=repo_root,
check=True,
)
sha = (result.stdout or "").strip()
if not sha:
raise GitHubSyncError(f"Impossible de résoudre le SHA de la ref '{ref_name}'.")
LOGGER.info("[GITHUB_SYNC] SHA résolu | ref=%s | sha=%s", ref_name, sha)
return sha
def build_force_with_lease_arg(branch: str, expected_remote_sha: str) -> str:
"""
Construit l'argument explicite force-with-lease pour la branche distante.
"""
return f"--force-with-lease=refs/heads/{branch}:{expected_remote_sha}"
def _build_push_command(
push_url: str,
branch: str,
mode: str,
lease_arg: Optional[str] = None,
no_thin: bool = False,
) -> List[str]:
"""
Construit la commande git push adaptée au mode choisi.
"""
base = [
"git",
"-c", "credential.helper=",
"push",
"--porcelain",
]
if no_thin:
base.append("--no-thin")
if mode == "force_with_lease":
if not lease_arg:
raise GitHubSyncError(
"Mode force_with_lease demandé sans lease_arg explicite."
)
base.append(lease_arg)
elif mode == "force":
base.append("--force")
elif mode != "fast_forward_only":
raise GitHubSyncError(f"Mode de push non supporté dans _build_push_command: {mode}")
base.extend([push_url, f"HEAD:refs/heads/{branch}"])
return base
def _execute_push_mode(
repo_root: Path,
repo: str,
branch: str,
token: str,
mode: str,
lease_arg: Optional[str] = None,
no_thin: bool = False,
) -> dict:
"""
Exécute réellement un push dans le mode demandé.
"""
push_url = build_authenticated_push_url(repo, token)
cmd = _build_push_command(
push_url=push_url,
branch=branch,
mode=mode,
lease_arg=lease_arg,
no_thin=no_thin,
)
LOGGER.info(
"[GITHUB_SYNC] Push GitHub | repo=%s | branch=%s | mode=%s | no_thin=%s",
repo,
branch,
mode,
no_thin,
)
if lease_arg:
LOGGER.info("[GITHUB_SYNC] Lease explicite utilisée | %s", lease_arg)
result = run_cmd(
cmd,
cwd=repo_root,
token=token,
check=True,
)
return {
"ok": True,
"mode_used": mode,
"returncode": result.returncode,
"stdout": _sanitize_text(result.stdout or "", token),
"stderr": _sanitize_text(result.stderr or "", token),
"lease_arg": lease_arg,
"no_thin": no_thin,
}
def _copy_worktree_to_snapshot_dir(source_repo_root: Path, dest_dir: Path) -> None:
"""
Copie le working tree courant dans un répertoire de snapshot en excluant `.git`
et quelques artefacts non utiles.
Paramètres
----------
source_repo_root : Path
Dépôt source.
dest_dir : Path
Répertoire destination vide.
"""
ignore_names = {
".git",
"__pycache__",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".cache",
".venv",
"venv",
}
for item in source_repo_root.iterdir():
if item.name in ignore_names:
continue
dest_item = dest_dir / item.name
if item.is_dir():
shutil.copytree(item, dest_item)
else:
shutil.copy2(item, dest_item)
LOGGER.info("[GITHUB_SYNC] Snapshot du working tree copié vers %s", dest_dir)
def create_snapshot_repo_from_worktree(
source_repo_root: Path,
committer_name: str,
committer_email: str,
commit_message: str,
) -> Path:
"""
Construit un dépôt Git temporaire neuf à partir du working tree courant.
Paramètres
----------
source_repo_root : Path
Dépôt source HF.
committer_name : str
Nom du committer.
committer_email : str
Email du committer.
commit_message : str
Message du commit snapshot.
Retour
------
Path
Répertoire du dépôt snapshot prêt à pousser.
Notes
-----
- Le repo créé ici est totalement indépendant de l'historique `.git` d'origine.
- Il sert de plan B quand le dépôt source contient des objets Git manquants
ou quand l'historique local HF n'est pas proprement pushable.
"""
temp_root = Path(tempfile.mkdtemp(prefix="ccpu_github_snapshot_"))
LOGGER.warning(
"[GITHUB_SYNC] Création d'un dépôt snapshot temporaire indépendant | path=%s",
temp_root,
)
_copy_worktree_to_snapshot_dir(source_repo_root, temp_root)
run_cmd(["git", "init", "-b", "main"], cwd=temp_root, check=True)
run_cmd(["git", "config", "user.name", committer_name], cwd=temp_root, check=True)
run_cmd(["git", "config", "user.email", committer_email], cwd=temp_root, check=True)
run_cmd(["git", "add", "-A"], cwd=temp_root, check=True)
snapshot_message = f"{commit_message} [snapshot-export]"
run_cmd(
["git", "commit", "-m", snapshot_message],
cwd=temp_root,
check=True,
env={
"GIT_AUTHOR_NAME": committer_name,
"GIT_AUTHOR_EMAIL": committer_email,
"GIT_COMMITTER_NAME": committer_name,
"GIT_COMMITTER_EMAIL": committer_email,
},
)
LOGGER.warning(
"[GITHUB_SYNC] Dépôt snapshot temporaire créé avec succès | path=%s",
temp_root,
)
return temp_root
def push_snapshot_repo_to_github(
snapshot_repo_root: Path,
repo: str,
branch: str,
token: str,
) -> dict:
"""
Pousse le dépôt snapshot temporaire vers GitHub.
Paramètres
----------
snapshot_repo_root : Path
Dépôt snapshot temporaire.
repo : str
Repo GitHub cible.
branch : str
Branche cible.
token : str
Token GitHub.
Retour
------
dict
Résumé du push snapshot.
Notes
-----
- On utilise ici `--force --no-thin` volontairement.
- `--force` car le snapshot n'a pas le même historique que le dépôt distant.
- `--no-thin` pour envoyer un pack auto-suffisant et éviter les hypothèses
sur des objets déjà présents côté distant.
"""
LOGGER.warning(
"[GITHUB_SYNC] Tentative de push via dépôt snapshot temporaire | repo=%s | branch=%s",
repo,
branch,
)
result = _execute_push_mode(
repo_root=snapshot_repo_root,
repo=repo,
branch=branch,
token=token,
mode="force",
lease_arg=None,
no_thin=True,
)
result["snapshot_fallback_used"] = True
result["snapshot_repo_root"] = str(snapshot_repo_root)
return result
def push_to_github(
repo_root: Path,
repo: str,
branch: str,
token: str,
push_mode: str,
preflight: Optional[dict] = None,
allow_snapshot_fallback: bool = True,
committer_name: str = "HF Space Sync Bot",
committer_email: str = "hf-space-sync@example.com",
commit_message: str = "chore(sync): mirror Hugging Face Space to GitHub",
) -> dict:
"""
Pousse la branche locale courante vers la branche cible GitHub.
Comportement
------------
- fast_forward_only : push simple uniquement
- force_with_lease : fetch du remote, lecture du SHA, puis push avec lease explicite
- force : push forcé direct
- auto : push simple, puis fallback force_with_lease explicite si divergence
et si la branche n'est pas protégée
Fallback snapshot
-----------------
Si un push échoue avec des symptômes d'objets Git manquants / unpack distant
échoué (`index-pack failed`, `did not receive expected object`, etc.), et si
`allow_snapshot_fallback=True`, alors on fabrique un dépôt snapshot temporaire
à partir du working tree courant et on pousse ce snapshot vers GitHub.
"""
branch_protected = bool((preflight or {}).get("branch_protected"))
def _maybe_snapshot_fallback(exc: GitCommandError) -> Optional[dict]:
if not allow_snapshot_fallback:
return None
if branch_protected:
LOGGER.warning(
"[GITHUB_SYNC] Snapshot fallback non tenté car la branche '%s' est protégée.",
branch,
)
return None
if not is_missing_object_pack_error(exc):
return None
LOGGER.warning(
"[GITHUB_SYNC] Détection d'un dépôt source possiblement incomplet/corrompu. "
"Activation du fallback snapshot."
)
snapshot_repo_root = create_snapshot_repo_from_worktree(
source_repo_root=repo_root,
committer_name=committer_name,
committer_email=committer_email,
commit_message=commit_message,
)
try:
return push_snapshot_repo_to_github(
snapshot_repo_root=snapshot_repo_root,
repo=repo,
branch=branch,
token=token,
)
finally:
try:
shutil.rmtree(snapshot_repo_root, ignore_errors=True)
LOGGER.info(
"[GITHUB_SYNC] Dépôt snapshot temporaire supprimé | path=%s",
snapshot_repo_root,
)
except Exception as cleanup_exc:
LOGGER.warning(
"[GITHUB_SYNC] Impossible de supprimer le dépôt snapshot temporaire: %s",
cleanup_exc,
)
if push_mode == "force" and branch_protected:
raise GitHubSyncError(
f"Refus local: la branche '{branch}' est protégée, "
f"un push --force a de fortes chances d'être bloqué."
)
if push_mode == "force_with_lease" and branch_protected:
raise GitHubSyncError(
f"Refus local: la branche '{branch}' est protégée, "
f"un push --force-with-lease a de fortes chances d'être bloqué."
)
if push_mode == "force":
try:
return _execute_push_mode(
repo_root=repo_root,
repo=repo,
branch=branch,
token=token,
mode="force",
no_thin=True,
)
except GitCommandError as exc:
snapshot_result = _maybe_snapshot_fallback(exc)
if snapshot_result is not None:
return snapshot_result
diagnostic = diagnose_push_failure(exc)
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
if push_mode == "force_with_lease":
try:
git_fetch_remote_branch(
repo_root=repo_root,
repo=repo,
branch=branch,
token=token,
)
expected_remote_sha = get_ref_sha(
repo_root=repo_root,
ref_name=f"refs/remotes/github/{branch}",
)
lease_arg = build_force_with_lease_arg(
branch=branch,
expected_remote_sha=expected_remote_sha,
)
return _execute_push_mode(
repo_root=repo_root,
repo=repo,
branch=branch,
token=token,
mode="force_with_lease",
lease_arg=lease_arg,
no_thin=True,
)
except GitCommandError as exc:
snapshot_result = _maybe_snapshot_fallback(exc)
if snapshot_result is not None:
return snapshot_result
diagnostic = diagnose_push_failure(exc)
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
if push_mode == "fast_forward_only":
try:
return _execute_push_mode(
repo_root=repo_root,
repo=repo,
branch=branch,
token=token,
mode="fast_forward_only",
)
except GitCommandError as exc:
snapshot_result = _maybe_snapshot_fallback(exc)
if snapshot_result is not None:
return snapshot_result
diagnostic = diagnose_push_failure(exc)
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
if push_mode != "auto":
raise GitHubSyncError(f"push_mode non supporté: {push_mode}")
try:
return _execute_push_mode(
repo_root=repo_root,
repo=repo,
branch=branch,
token=token,
mode="fast_forward_only",
)
except GitCommandError as exc:
if is_missing_object_pack_error(exc):
snapshot_result = _maybe_snapshot_fallback(exc)
if snapshot_result is not None:
return snapshot_result
if not is_non_fast_forward_error(exc):
diagnostic = diagnose_push_failure(exc)
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
LOGGER.warning(
"[GITHUB_SYNC] Divergence détectée sur la branche distante '%s'.",
branch,
)
if branch_protected:
diagnostic = (
f"Push GitHub refusé: la branche '{branch}' diverge déjà et elle est protégée. "
f"Le fallback automatique force_with_lease n'est pas tenté."
)
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
LOGGER.warning(
"[GITHUB_SYNC] Fallback automatique activé -> tentative force_with_lease explicite sur '%s'.",
branch,
)
try:
git_fetch_remote_branch(
repo_root=repo_root,
repo=repo,
branch=branch,
token=token,
)
expected_remote_sha = get_ref_sha(
repo_root=repo_root,
ref_name=f"refs/remotes/github/{branch}",
)
lease_arg = build_force_with_lease_arg(
branch=branch,
expected_remote_sha=expected_remote_sha,
)
return _execute_push_mode(
repo_root=repo_root,
repo=repo,
branch=branch,
token=token,
mode="force_with_lease",
lease_arg=lease_arg,
no_thin=True,
)
except GitCommandError as exc2:
snapshot_result = _maybe_snapshot_fallback(exc2)
if snapshot_result is not None:
return snapshot_result
diagnostic = diagnose_push_failure(exc2)
raise GitHubSyncError(
f"Echec du fallback auto force_with_lease explicite. {diagnostic} | {exc2}"
) from exc2
def sync_repo_to_github(
repo_root: Optional[Path] = None,
commit_message: Optional[str] = None,
branch: Optional[str] = None,
allow_empty_push: bool = True,
) -> dict:
"""
Point d'entrée haut niveau de la synchronisation GitHub.
"""
ensure_logger_configured(logging.INFO)
config = load_github_sync_config_from_env()
if commit_message:
config.commit_message = commit_message
repo_root = repo_root or get_repo_root()
ensure_git_available(repo_root)
if not branch:
current_branch = get_current_branch(repo_root)
branch = config.branch or current_branch or "main"
LOGGER.info(
"[GITHUB_SYNC] Démarrage synchronisation | repo_root=%s | github_repo=%s | branch=%s | push_mode=%s | allow_snapshot_fallback=%s",
repo_root,
config.repo,
branch,
config.push_mode,
config.allow_snapshot_fallback,
)
preflight = github_preflight_check(
repo=config.repo,
token=config.token,
branch=branch,
)
ensure_clean_github_remote(
repo_root=repo_root,
remote_name=config.remote_name,
repo=config.repo,
)
had_changes = has_worktree_changes(repo_root)
commit_created = commit_all_if_needed(
repo_root=repo_root,
commit_message=config.commit_message,
committer_name=config.committer_name,
committer_email=config.committer_email,
)
pushed = False
push_summary: dict[str, Any] = {
"ok": False,
"stdout": "",
"stderr": "",
"mode_used": None,
"lease_arg": None,
"no_thin": None,
"snapshot_fallback_used": False,
}
if commit_created or allow_empty_push:
push_summary = push_to_github(
repo_root=repo_root,
repo=config.repo,
branch=branch,
token=config.token,
push_mode=config.push_mode,
preflight=preflight,
allow_snapshot_fallback=config.allow_snapshot_fallback,
committer_name=config.committer_name,
committer_email=config.committer_email,
commit_message=config.commit_message,
)
pushed = True
else:
LOGGER.info(
"[GITHUB_SYNC] Aucun push exécuté car aucun commit nouveau et allow_empty_push=False."
)
result = {
"ok": True,
"repo_root": str(repo_root),
"github_repo": config.repo,
"branch": branch,
"remote_name": config.remote_name,
"had_changes": had_changes,
"commit_created": commit_created,
"pushed": pushed,
"message": "Synchronisation GitHub terminée avec succès.",
"push_mode_requested": config.push_mode,
"allow_snapshot_fallback": config.allow_snapshot_fallback,
"preflight": preflight,
"push": push_summary,
}
LOGGER.info("[GITHUB_SYNC] Résultat final: %s", result)
return result
if __name__ == "__main__":
"""
Exécution CLI simple pour test local / Space.
Exemple d'usage
---------------
Avec secrets / variables d'environnement définis :
python -m ccpu_parser.github_sync
"""
try:
summary = sync_repo_to_github()
print(json.dumps(summary, ensure_ascii=False, indent=2))
except Exception as exc:
ensure_logger_configured(logging.INFO)
LOGGER.exception("[GITHUB_SYNC] Echec global: %s", exc)
raise
# ccpu_parser/github_sync.py
# -*- coding: utf-8 -*-
"""
github_sync.py — Synchronisation du dépôt Hugging Face Space vers un dépôt GitHub
=================================================================================
Ce que fait ce fichier
----------------------
- Fournit une brique de synchronisation Git robuste pour pousser le dépôt courant
du Space Hugging Face vers un dépôt GitHub distant via HTTPS.
- Utilise un token GitHub injecté via variable d'environnement / secret HF.
- N'enregistre jamais le token dans le remote Git local.
- Réalise un pré-contrôle GitHub avant le push pour faciliter le diagnostic.
- Gère plusieurs stratégies de push pour couvrir le cas classique où le dépôt
GitHub a déjà un commit initial (README, .gitignore...) qui diverge du repo HF.
- Corrige explicitement le cas `--force-with-lease` + push vers URL directe en
utilisant une lease explicite basée sur le SHA réellement fetché du ref distant.
- Ajoute un fallback "snapshot repo" : si le dépôt local HF présente des objets
Git manquants/incohérents au moment du push (`index-pack failed`, `did not receive
expected object`, etc.), on reconstruit un dépôt Git temporaire propre à partir
du working tree courant, puis on pousse ce snapshot vers GitHub.
Pourquoi ce fichier existe
--------------------------
- Permet de mirrorer progressivement le code du Space vers GitHub.
- Prépare une migration douce vers Coolify / serveur perso.
- Evite les manipulations manuelles répétitives de git add / commit / push.
- Rend le diagnostic beaucoup plus lisible dans les logs Hugging Face.
Variables d'environnement supportées
------------------------------------
- GITHUB_TOKEN : token GitHub utilisé pour le push HTTPS.
- GITHUB_REPO : repo cible au format "owner/repository".
- GITHUB_BRANCH : branche cible GitHub (défaut: branche courante ou "main").
- GITHUB_REMOTE_NAME : nom logique du remote local (défaut: "github").
- GITHUB_COMMITTER_NAME : nom de commit Git (défaut: "HF Space Sync Bot").
- GITHUB_COMMITTER_EMAIL : email de commit Git (défaut: "hf-space-sync@example.com").
- GITHUB_PUSH_MODE : stratégie de push :
* "auto" -> push normal, puis fallback --force-with-lease si divergence
* "fast_forward_only" -> push normal uniquement
* "force_with_lease" -> push direct avec --force-with-lease explicite
* "force" -> push direct avec --force
- GITHUB_ALLOW_SNAPSHOT_FALLBACK : "1"/"true"/"yes" pour autoriser le fallback snapshot
en cas de dépôt local incomplet/corrompu (défaut: "1").
Fonctions principales
---------------------
- sync_repo_to_github(...)
Point d'entrée haut niveau. Vérifie la conf, prépare le remote, détecte les
changements, commit si nécessaire, puis pousse vers GitHub.
- push_to_github(...)
Exécute le push HTTPS authentifié vers GitHub sans persister le token.
- github_preflight_check(...)
Valide le token, le repo cible et l'état de la branche distante autant que possible.
- commit_all_if_needed(...)
Stage + commit les changements si le working tree n'est pas propre.
- ensure_clean_github_remote(...)
Crée ou met à jour un remote local propre, sans secret dans son URL.
- get_repo_root(...)
Détecte la racine du dépôt courant.
- has_worktree_changes(...)
Indique si le dépôt contient des changements non commités.
- git_fetch_remote_branch(...)
Récupère la branche distante en local.
- get_ref_sha(...)
Lit le SHA d'une ref git locale.
- build_force_with_lease_arg(...)
Construit l'argument `--force-with-lease=refs/heads/<branch>:<sha>`.
- create_snapshot_repo_from_worktree(...)
Construit un dépôt Git temporaire neuf à partir du working tree courant.
- push_snapshot_repo_to_github(...)
Pousse le dépôt snapshot temporaire vers GitHub.
Notes de sécurité
-----------------
- Le token n'est jamais écrit dans "git remote -v".
- Le token n'est jamais loggé.
- L'URL authentifiée est construite de façon éphémère uniquement pour la commande push.
- Les sorties de commande sont nettoyées avant logging lorsqu'une URL potentiellement
sensible pourrait apparaître.
Dépendances
-----------
- Standard library uniquement.
- Nécessite que git soit présent dans l'environnement d'exécution.
"""
from __future__ import annotations
import json
import logging
import os
import shutil
import subprocess
import tempfile
import urllib.error
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional