Spaces:
Sleeping
Sleeping
Update ccpu_parser/github_sync.py
Browse files- ccpu_parser/github_sync.py +424 -25
ccpu_parser/github_sync.py
CHANGED
|
@@ -13,6 +13,8 @@ Ce que fait ce fichier
|
|
| 13 |
- Réalise un pré-contrôle GitHub avant le push pour faciliter le diagnostic.
|
| 14 |
- Gère plusieurs stratégies de push pour couvrir le cas classique où le dépôt
|
| 15 |
GitHub a déjà un commit initial (README, .gitignore...) qui diverge du repo HF.
|
|
|
|
|
|
|
| 16 |
|
| 17 |
Pourquoi ce fichier existe
|
| 18 |
--------------------------
|
|
@@ -31,7 +33,7 @@ Variables d'environnement supportées
|
|
| 31 |
- GITHUB_PUSH_MODE : stratégie de push :
|
| 32 |
* "auto" -> push normal, puis fallback --force-with-lease si divergence
|
| 33 |
* "fast_forward_only" -> push normal uniquement
|
| 34 |
-
* "force_with_lease" -> push direct avec --force-with-lease
|
| 35 |
* "force" -> push direct avec --force
|
| 36 |
|
| 37 |
Fonctions principales
|
|
@@ -48,9 +50,15 @@ Fonctions principales
|
|
| 48 |
- ensure_clean_github_remote(...)
|
| 49 |
Crée ou met à jour un remote local propre, sans secret dans son URL.
|
| 50 |
- get_repo_root(...)
|
| 51 |
-
Détecte la racine
|
| 52 |
- has_worktree_changes(...)
|
| 53 |
Indique si le dépôt contient des changements non commités.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
Notes de sécurité
|
| 56 |
-----------------
|
|
@@ -174,6 +182,18 @@ def ensure_logger_configured(level: int = logging.INFO) -> None:
|
|
| 174 |
def _mask_token(value: str, token: Optional[str]) -> str:
|
| 175 |
"""
|
| 176 |
Masque le token dans une chaîne si présent.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
"""
|
| 178 |
if not value:
|
| 179 |
return value
|
|
@@ -185,6 +205,16 @@ def _mask_token(value: str, token: Optional[str]) -> str:
|
|
| 185 |
def _mask_sensitive_url(value: str) -> str:
|
| 186 |
"""
|
| 187 |
Masque une URL GitHub potentiellement authentifiée pour les logs.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
"""
|
| 189 |
if "github.com" in value and "://" in value and "@" in value:
|
| 190 |
try:
|
|
@@ -200,6 +230,18 @@ def _mask_sensitive_url(value: str) -> str:
|
|
| 200 |
def _sanitize_text(value: str, token: Optional[str]) -> str:
|
| 201 |
"""
|
| 202 |
Nettoie une chaîne pour logging / exceptions.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
"""
|
| 204 |
cleaned = value or ""
|
| 205 |
cleaned = _mask_token(cleaned, token)
|
|
@@ -263,6 +305,13 @@ def run_cmd(
|
|
| 263 |
------
|
| 264 |
subprocess.CompletedProcess
|
| 265 |
Résultat d'exécution.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
"""
|
| 267 |
safe_args = [_sanitize_text(str(a), token) for a in args]
|
| 268 |
LOGGER.info("[GITHUB_SYNC] RUN | cwd=%s | cmd=%s", cwd, " ".join(safe_args))
|
|
@@ -306,6 +355,11 @@ def run_cmd(
|
|
| 306 |
def ensure_git_available(cwd: Path) -> None:
|
| 307 |
"""
|
| 308 |
Vérifie que git est installé et exécutable.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
"""
|
| 310 |
run_cmd(["git", "--version"], cwd=cwd, check=True)
|
| 311 |
LOGGER.info("[GITHUB_SYNC] Git détecté avec succès.")
|
|
@@ -316,6 +370,21 @@ def load_github_sync_config_from_env(
|
|
| 316 |
) -> GitHubSyncConfig:
|
| 317 |
"""
|
| 318 |
Charge la configuration depuis les variables d'environnement.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
"""
|
| 320 |
repo = (os.getenv("GITHUB_REPO") or "").strip()
|
| 321 |
token = (os.getenv("GITHUB_TOKEN") or "").strip()
|
|
@@ -332,9 +401,7 @@ def load_github_sync_config_from_env(
|
|
| 332 |
"Variable d'environnement manquante: GITHUB_REPO (attendu: owner/repository)."
|
| 333 |
)
|
| 334 |
if not token:
|
| 335 |
-
raise GitHubSyncError(
|
| 336 |
-
"Variable d'environnement manquante: GITHUB_TOKEN."
|
| 337 |
-
)
|
| 338 |
if not branch:
|
| 339 |
branch = "main"
|
| 340 |
if push_mode not in allowed_modes:
|
|
@@ -358,6 +425,21 @@ def load_github_sync_config_from_env(
|
|
| 358 |
def parse_repo_slug(repo: str) -> tuple[str, str]:
|
| 359 |
"""
|
| 360 |
Décompose un slug GitHub owner/repository.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
"""
|
| 362 |
parts = [x.strip() for x in repo.split("/") if x.strip()]
|
| 363 |
if len(parts) != 2:
|
|
@@ -374,6 +456,25 @@ def github_api_request(
|
|
| 374 |
) -> tuple[int, Dict[str, Any], Dict[str, str]]:
|
| 375 |
"""
|
| 376 |
Exécute une requête simple sur l'API GitHub.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
"""
|
| 378 |
url = f"https://api.github.com{path}"
|
| 379 |
req = urllib.request.Request(
|
|
@@ -408,6 +509,25 @@ def github_api_request(
|
|
| 408 |
def github_preflight_check(repo: str, token: str, branch: str) -> dict:
|
| 409 |
"""
|
| 410 |
Valide le token GitHub, le dépôt cible et l'état général de la branche.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
"""
|
| 412 |
owner, repo_name = parse_repo_slug(repo)
|
| 413 |
|
|
@@ -423,7 +543,10 @@ def github_preflight_check(repo: str, token: str, branch: str) -> dict:
|
|
| 423 |
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | token valide | login=%s", login)
|
| 424 |
|
| 425 |
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | validation du repo cible %s...", repo)
|
| 426 |
-
st_repo, repo_payload, repo_headers = github_api_request(
|
|
|
|
|
|
|
|
|
|
| 427 |
if st_repo == 404:
|
| 428 |
raise GitHubSyncError(
|
| 429 |
f"Préflight GitHub KO: dépôt '{repo}' introuvable ou inaccessible avec ce token."
|
|
@@ -504,6 +627,21 @@ def github_preflight_check(repo: str, token: str, branch: str) -> dict:
|
|
| 504 |
def get_repo_root(cwd: Optional[Path] = None) -> Path:
|
| 505 |
"""
|
| 506 |
Détecte la racine du dépôt git courant.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
"""
|
| 508 |
cwd = cwd or Path.cwd()
|
| 509 |
result = run_cmd(
|
|
@@ -522,6 +660,16 @@ def get_repo_root(cwd: Optional[Path] = None) -> Path:
|
|
| 522 |
def get_current_branch(repo_root: Path) -> str:
|
| 523 |
"""
|
| 524 |
Récupère la branche courante si possible.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 525 |
"""
|
| 526 |
result = run_cmd(
|
| 527 |
["git", "rev-parse", "--abbrev-ref", "HEAD"],
|
|
@@ -538,6 +686,16 @@ def get_current_branch(repo_root: Path) -> str:
|
|
| 538 |
def has_worktree_changes(repo_root: Path) -> bool:
|
| 539 |
"""
|
| 540 |
Indique si le dépôt contient des changements non commités.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 541 |
"""
|
| 542 |
result = run_cmd(
|
| 543 |
["git", "status", "--porcelain"],
|
|
@@ -552,6 +710,15 @@ def has_worktree_changes(repo_root: Path) -> bool:
|
|
| 552 |
def ensure_git_identity(repo_root: Path, name: str, email: str) -> None:
|
| 553 |
"""
|
| 554 |
Définit localement l'identité git si nécessaire.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 555 |
"""
|
| 556 |
current_name = run_cmd(
|
| 557 |
["git", "config", "--get", "user.name"],
|
|
@@ -576,6 +743,20 @@ def ensure_git_identity(repo_root: Path, name: str, email: str) -> None:
|
|
| 576 |
def ensure_clean_github_remote(repo_root: Path, remote_name: str, repo: str) -> str:
|
| 577 |
"""
|
| 578 |
Crée ou met à jour un remote local propre vers GitHub, sans secret.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
"""
|
| 580 |
clean_url = f"https://github.com/{repo}.git"
|
| 581 |
|
|
@@ -619,6 +800,18 @@ def ensure_clean_github_remote(repo_root: Path, remote_name: str, repo: str) ->
|
|
| 619 |
def build_authenticated_push_url(repo: str, token: str) -> str:
|
| 620 |
"""
|
| 621 |
Construit une URL HTTPS authentifiée éphémère pour le push.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
"""
|
| 623 |
return f"https://x-access-token:{token}@github.com/{repo}.git"
|
| 624 |
|
|
@@ -626,6 +819,11 @@ def build_authenticated_push_url(repo: str, token: str) -> str:
|
|
| 626 |
def stage_all_changes(repo_root: Path) -> None:
|
| 627 |
"""
|
| 628 |
Stage l'ensemble des changements du dépôt.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 629 |
"""
|
| 630 |
run_cmd(["git", "add", "-A"], cwd=repo_root, check=True)
|
| 631 |
LOGGER.info("[GITHUB_SYNC] Tous les changements ont été ajoutés à l'index.")
|
|
@@ -639,6 +837,22 @@ def commit_all_if_needed(
|
|
| 639 |
) -> bool:
|
| 640 |
"""
|
| 641 |
Commit les changements si nécessaire.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
"""
|
| 643 |
if not has_worktree_changes(repo_root):
|
| 644 |
LOGGER.info("[GITHUB_SYNC] Aucun changement à committer.")
|
|
@@ -682,6 +896,16 @@ def commit_all_if_needed(
|
|
| 682 |
def diagnose_push_failure(exc: GitCommandError) -> str:
|
| 683 |
"""
|
| 684 |
Produit un diagnostic métier lisible à partir d'une erreur de push Git.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
"""
|
| 686 |
blob = f"{exc.stdout}\n{exc.stderr}".lower()
|
| 687 |
|
|
@@ -725,6 +949,12 @@ def diagnose_push_failure(exc: GitCommandError) -> str:
|
|
| 725 |
"Push GitHub refusé car l'historique distant a divergé (non-fast-forward)."
|
| 726 |
)
|
| 727 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 728 |
return (
|
| 729 |
"Push GitHub refusé. Consulte le stderr détaillé remonté dans l'exception/log pour "
|
| 730 |
"connaître le motif exact renvoyé par GitHub."
|
|
@@ -734,6 +964,16 @@ def diagnose_push_failure(exc: GitCommandError) -> str:
|
|
| 734 |
def is_non_fast_forward_error(exc: GitCommandError) -> bool:
|
| 735 |
"""
|
| 736 |
Détecte un rejet de type non-fast-forward / fetch first.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
"""
|
| 738 |
blob = f"{exc.stdout}\n{exc.stderr}".lower()
|
| 739 |
return (
|
|
@@ -750,8 +990,19 @@ def git_fetch_remote_branch(
|
|
| 750 |
token: str,
|
| 751 |
) -> None:
|
| 752 |
"""
|
| 753 |
-
Récupère la branche distante dans refs/remotes/<
|
| 754 |
-
d'une vision actualisée avant un éventuel --force-with-lease.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 755 |
"""
|
| 756 |
push_url = build_authenticated_push_url(repo, token)
|
| 757 |
run_cmd(
|
|
@@ -772,7 +1023,65 @@ def git_fetch_remote_branch(
|
|
| 772 |
)
|
| 773 |
|
| 774 |
|
| 775 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 776 |
"""
|
| 777 |
Construit la commande git push adaptée au mode choisi.
|
| 778 |
|
|
@@ -784,11 +1093,18 @@ def _build_push_command(push_url: str, branch: str, mode: str) -> List[str]:
|
|
| 784 |
Branche cible.
|
| 785 |
mode : str
|
| 786 |
fast_forward_only / force_with_lease / force
|
|
|
|
|
|
|
| 787 |
|
| 788 |
Retour
|
| 789 |
------
|
| 790 |
List[str]
|
| 791 |
Commande complète.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 792 |
"""
|
| 793 |
base = [
|
| 794 |
"git",
|
|
@@ -798,7 +1114,11 @@ def _build_push_command(push_url: str, branch: str, mode: str) -> List[str]:
|
|
| 798 |
]
|
| 799 |
|
| 800 |
if mode == "force_with_lease":
|
| 801 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 802 |
elif mode == "force":
|
| 803 |
base.append("--force")
|
| 804 |
elif mode != "fast_forward_only":
|
|
@@ -814,12 +1134,38 @@ def _execute_push_mode(
|
|
| 814 |
branch: str,
|
| 815 |
token: str,
|
| 816 |
mode: str,
|
|
|
|
| 817 |
) -> dict:
|
| 818 |
"""
|
| 819 |
Exécute réellement un push dans le mode demandé.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 820 |
"""
|
| 821 |
push_url = build_authenticated_push_url(repo, token)
|
| 822 |
-
cmd = _build_push_command(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
|
| 824 |
LOGGER.info(
|
| 825 |
"[GITHUB_SYNC] Push GitHub | repo=%s | branch=%s | mode=%s",
|
|
@@ -828,6 +1174,9 @@ def _execute_push_mode(
|
|
| 828 |
mode,
|
| 829 |
)
|
| 830 |
|
|
|
|
|
|
|
|
|
|
| 831 |
result = run_cmd(
|
| 832 |
cmd,
|
| 833 |
cwd=repo_root,
|
|
@@ -841,6 +1190,7 @@ def _execute_push_mode(
|
|
| 841 |
"returncode": result.returncode,
|
| 842 |
"stdout": _sanitize_text(result.stdout or "", token),
|
| 843 |
"stderr": _sanitize_text(result.stderr or "", token),
|
|
|
|
| 844 |
}
|
| 845 |
|
| 846 |
|
|
@@ -878,9 +1228,9 @@ def push_to_github(
|
|
| 878 |
Comportement
|
| 879 |
------------
|
| 880 |
- fast_forward_only : push simple uniquement
|
| 881 |
-
- force_with_lease : push
|
| 882 |
- force : push forcé direct
|
| 883 |
-
- auto : push simple, puis fallback
|
| 884 |
et si la branche n'est pas protégée
|
| 885 |
"""
|
| 886 |
branch_protected = bool((preflight or {}).get("branch_protected"))
|
|
@@ -897,21 +1247,55 @@ def push_to_github(
|
|
| 897 |
f"un push --force-with-lease a de fortes chances d'être bloqué."
|
| 898 |
)
|
| 899 |
|
| 900 |
-
if push_mode
|
| 901 |
try:
|
| 902 |
-
if push_mode == "force_with_lease":
|
| 903 |
-
git_fetch_remote_branch(
|
| 904 |
-
repo_root=repo_root,
|
| 905 |
-
repo=repo,
|
| 906 |
-
branch=branch,
|
| 907 |
-
token=token,
|
| 908 |
-
)
|
| 909 |
return _execute_push_mode(
|
| 910 |
repo_root=repo_root,
|
| 911 |
repo=repo,
|
| 912 |
branch=branch,
|
| 913 |
token=token,
|
| 914 |
-
mode=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 915 |
)
|
| 916 |
except GitCommandError as exc:
|
| 917 |
diagnostic = diagnose_push_failure(exc)
|
|
@@ -941,12 +1325,12 @@ def push_to_github(
|
|
| 941 |
if branch_protected:
|
| 942 |
diagnostic = (
|
| 943 |
f"Push GitHub refusé: la branche '{branch}' diverge déjà et elle est protégée. "
|
| 944 |
-
f"Le fallback automatique
|
| 945 |
)
|
| 946 |
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
|
| 947 |
|
| 948 |
LOGGER.warning(
|
| 949 |
-
"[GITHUB_SYNC] Fallback automatique activé -> tentative
|
| 950 |
branch,
|
| 951 |
)
|
| 952 |
|
|
@@ -957,17 +1341,26 @@ def push_to_github(
|
|
| 957 |
branch=branch,
|
| 958 |
token=token,
|
| 959 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 960 |
return _execute_push_mode(
|
| 961 |
repo_root=repo_root,
|
| 962 |
repo=repo,
|
| 963 |
branch=branch,
|
| 964 |
token=token,
|
| 965 |
mode="force_with_lease",
|
|
|
|
| 966 |
)
|
| 967 |
except GitCommandError as exc2:
|
| 968 |
diagnostic = diagnose_push_failure(exc2)
|
| 969 |
raise GitHubSyncError(
|
| 970 |
-
f"Echec du fallback auto
|
| 971 |
) from exc2
|
| 972 |
|
| 973 |
|
|
@@ -996,6 +1389,11 @@ def sync_repo_to_github(
|
|
| 996 |
------
|
| 997 |
dict
|
| 998 |
Résumé de synchronisation exploitable par l'appelant.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 999 |
"""
|
| 1000 |
ensure_logger_configured(logging.INFO)
|
| 1001 |
|
|
@@ -1044,6 +1442,7 @@ def sync_repo_to_github(
|
|
| 1044 |
"stdout": "",
|
| 1045 |
"stderr": "",
|
| 1046 |
"mode_used": None,
|
|
|
|
| 1047 |
}
|
| 1048 |
|
| 1049 |
if commit_created or allow_empty_push:
|
|
|
|
| 13 |
- Réalise un pré-contrôle GitHub avant le push pour faciliter le diagnostic.
|
| 14 |
- Gère plusieurs stratégies de push pour couvrir le cas classique où le dépôt
|
| 15 |
GitHub a déjà un commit initial (README, .gitignore...) qui diverge du repo HF.
|
| 16 |
+
- Corrige explicitement le cas `--force-with-lease` + push vers URL directe en
|
| 17 |
+
utilisant une lease explicite basée sur le SHA réellement fetché du ref distant.
|
| 18 |
|
| 19 |
Pourquoi ce fichier existe
|
| 20 |
--------------------------
|
|
|
|
| 33 |
- GITHUB_PUSH_MODE : stratégie de push :
|
| 34 |
* "auto" -> push normal, puis fallback --force-with-lease si divergence
|
| 35 |
* "fast_forward_only" -> push normal uniquement
|
| 36 |
+
* "force_with_lease" -> push direct avec --force-with-lease explicite
|
| 37 |
* "force" -> push direct avec --force
|
| 38 |
|
| 39 |
Fonctions principales
|
|
|
|
| 50 |
- ensure_clean_github_remote(...)
|
| 51 |
Crée ou met à jour un remote local propre, sans secret dans son URL.
|
| 52 |
- get_repo_root(...)
|
| 53 |
+
Détecte la racine du dépôt courant.
|
| 54 |
- has_worktree_changes(...)
|
| 55 |
Indique si le dépôt contient des changements non commités.
|
| 56 |
+
- git_fetch_remote_branch(...)
|
| 57 |
+
Récupère la branche distante en local.
|
| 58 |
+
- get_ref_sha(...)
|
| 59 |
+
Lit le SHA d'une ref git locale.
|
| 60 |
+
- build_force_with_lease_arg(...)
|
| 61 |
+
Construit l'argument `--force-with-lease=refs/heads/<branch>:<sha>`.
|
| 62 |
|
| 63 |
Notes de sécurité
|
| 64 |
-----------------
|
|
|
|
| 182 |
def _mask_token(value: str, token: Optional[str]) -> str:
|
| 183 |
"""
|
| 184 |
Masque le token dans une chaîne si présent.
|
| 185 |
+
|
| 186 |
+
Paramètres
|
| 187 |
+
----------
|
| 188 |
+
value : str
|
| 189 |
+
Chaîne à nettoyer.
|
| 190 |
+
token : Optional[str]
|
| 191 |
+
Token sensible éventuel.
|
| 192 |
+
|
| 193 |
+
Retour
|
| 194 |
+
------
|
| 195 |
+
str
|
| 196 |
+
Chaîne nettoyée.
|
| 197 |
"""
|
| 198 |
if not value:
|
| 199 |
return value
|
|
|
|
| 205 |
def _mask_sensitive_url(value: str) -> str:
|
| 206 |
"""
|
| 207 |
Masque une URL GitHub potentiellement authentifiée pour les logs.
|
| 208 |
+
|
| 209 |
+
Paramètres
|
| 210 |
+
----------
|
| 211 |
+
value : str
|
| 212 |
+
Chaîne éventuelle contenant une URL.
|
| 213 |
+
|
| 214 |
+
Retour
|
| 215 |
+
------
|
| 216 |
+
str
|
| 217 |
+
Chaîne nettoyée.
|
| 218 |
"""
|
| 219 |
if "github.com" in value and "://" in value and "@" in value:
|
| 220 |
try:
|
|
|
|
| 230 |
def _sanitize_text(value: str, token: Optional[str]) -> str:
|
| 231 |
"""
|
| 232 |
Nettoie une chaîne pour logging / exceptions.
|
| 233 |
+
|
| 234 |
+
Paramètres
|
| 235 |
+
----------
|
| 236 |
+
value : str
|
| 237 |
+
Chaîne brute.
|
| 238 |
+
token : Optional[str]
|
| 239 |
+
Token à masquer si présent.
|
| 240 |
+
|
| 241 |
+
Retour
|
| 242 |
+
------
|
| 243 |
+
str
|
| 244 |
+
Texte nettoyé.
|
| 245 |
"""
|
| 246 |
cleaned = value or ""
|
| 247 |
cleaned = _mask_token(cleaned, token)
|
|
|
|
| 305 |
------
|
| 306 |
subprocess.CompletedProcess
|
| 307 |
Résultat d'exécution.
|
| 308 |
+
|
| 309 |
+
Exceptions
|
| 310 |
+
----------
|
| 311 |
+
GitCommandError
|
| 312 |
+
Si la commande échoue et check=True.
|
| 313 |
+
GitHubSyncError
|
| 314 |
+
Si la commande n'est pas trouvée.
|
| 315 |
"""
|
| 316 |
safe_args = [_sanitize_text(str(a), token) for a in args]
|
| 317 |
LOGGER.info("[GITHUB_SYNC] RUN | cwd=%s | cmd=%s", cwd, " ".join(safe_args))
|
|
|
|
| 355 |
def ensure_git_available(cwd: Path) -> None:
|
| 356 |
"""
|
| 357 |
Vérifie que git est installé et exécutable.
|
| 358 |
+
|
| 359 |
+
Paramètres
|
| 360 |
+
----------
|
| 361 |
+
cwd : Path
|
| 362 |
+
Répertoire d'exécution.
|
| 363 |
"""
|
| 364 |
run_cmd(["git", "--version"], cwd=cwd, check=True)
|
| 365 |
LOGGER.info("[GITHUB_SYNC] Git détecté avec succès.")
|
|
|
|
| 370 |
) -> GitHubSyncConfig:
|
| 371 |
"""
|
| 372 |
Charge la configuration depuis les variables d'environnement.
|
| 373 |
+
|
| 374 |
+
Paramètres
|
| 375 |
+
----------
|
| 376 |
+
default_commit_message : str
|
| 377 |
+
Message de commit par défaut si aucun message n'est fourni ensuite.
|
| 378 |
+
|
| 379 |
+
Retour
|
| 380 |
+
------
|
| 381 |
+
GitHubSyncConfig
|
| 382 |
+
Configuration prête à l'emploi.
|
| 383 |
+
|
| 384 |
+
Exceptions
|
| 385 |
+
----------
|
| 386 |
+
GitHubSyncError
|
| 387 |
+
Si des variables obligatoires sont absentes ou invalides.
|
| 388 |
"""
|
| 389 |
repo = (os.getenv("GITHUB_REPO") or "").strip()
|
| 390 |
token = (os.getenv("GITHUB_TOKEN") or "").strip()
|
|
|
|
| 401 |
"Variable d'environnement manquante: GITHUB_REPO (attendu: owner/repository)."
|
| 402 |
)
|
| 403 |
if not token:
|
| 404 |
+
raise GitHubSyncError("Variable d'environnement manquante: GITHUB_TOKEN.")
|
|
|
|
|
|
|
| 405 |
if not branch:
|
| 406 |
branch = "main"
|
| 407 |
if push_mode not in allowed_modes:
|
|
|
|
| 425 |
def parse_repo_slug(repo: str) -> tuple[str, str]:
|
| 426 |
"""
|
| 427 |
Décompose un slug GitHub owner/repository.
|
| 428 |
+
|
| 429 |
+
Paramètres
|
| 430 |
+
----------
|
| 431 |
+
repo : str
|
| 432 |
+
Repo au format owner/repository.
|
| 433 |
+
|
| 434 |
+
Retour
|
| 435 |
+
------
|
| 436 |
+
tuple[str, str]
|
| 437 |
+
owner, repository
|
| 438 |
+
|
| 439 |
+
Exceptions
|
| 440 |
+
----------
|
| 441 |
+
GitHubSyncError
|
| 442 |
+
Si le format est invalide.
|
| 443 |
"""
|
| 444 |
parts = [x.strip() for x in repo.split("/") if x.strip()]
|
| 445 |
if len(parts) != 2:
|
|
|
|
| 456 |
) -> tuple[int, Dict[str, Any], Dict[str, str]]:
|
| 457 |
"""
|
| 458 |
Exécute une requête simple sur l'API GitHub.
|
| 459 |
+
|
| 460 |
+
Paramètres
|
| 461 |
+
----------
|
| 462 |
+
path : str
|
| 463 |
+
Chemin API, ex. '/user' ou '/repos/owner/repo'
|
| 464 |
+
token : str
|
| 465 |
+
Token GitHub.
|
| 466 |
+
method : str
|
| 467 |
+
Méthode HTTP.
|
| 468 |
+
|
| 469 |
+
Retour
|
| 470 |
+
------
|
| 471 |
+
tuple[int, Dict[str, Any], Dict[str, str]]
|
| 472 |
+
status_code, payload_json, headers
|
| 473 |
+
|
| 474 |
+
Exceptions
|
| 475 |
+
----------
|
| 476 |
+
GitHubSyncError
|
| 477 |
+
En cas d'erreur réseau non HTTP.
|
| 478 |
"""
|
| 479 |
url = f"https://api.github.com{path}"
|
| 480 |
req = urllib.request.Request(
|
|
|
|
| 509 |
def github_preflight_check(repo: str, token: str, branch: str) -> dict:
|
| 510 |
"""
|
| 511 |
Valide le token GitHub, le dépôt cible et l'état général de la branche.
|
| 512 |
+
|
| 513 |
+
Paramètres
|
| 514 |
+
----------
|
| 515 |
+
repo : str
|
| 516 |
+
Repo cible au format owner/repository.
|
| 517 |
+
token : str
|
| 518 |
+
Token GitHub.
|
| 519 |
+
branch : str
|
| 520 |
+
Branche cible.
|
| 521 |
+
|
| 522 |
+
Retour
|
| 523 |
+
------
|
| 524 |
+
dict
|
| 525 |
+
Résumé de préflight.
|
| 526 |
+
|
| 527 |
+
Exceptions
|
| 528 |
+
----------
|
| 529 |
+
GitHubSyncError
|
| 530 |
+
Si le token ou le repo ne sont pas exploitables.
|
| 531 |
"""
|
| 532 |
owner, repo_name = parse_repo_slug(repo)
|
| 533 |
|
|
|
|
| 543 |
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | token valide | login=%s", login)
|
| 544 |
|
| 545 |
LOGGER.info("[GITHUB_SYNC] PREFLIGHT | validation du repo cible %s...", repo)
|
| 546 |
+
st_repo, repo_payload, repo_headers = github_api_request(
|
| 547 |
+
f"/repos/{owner}/{repo_name}",
|
| 548 |
+
token=token,
|
| 549 |
+
)
|
| 550 |
if st_repo == 404:
|
| 551 |
raise GitHubSyncError(
|
| 552 |
f"Préflight GitHub KO: dépôt '{repo}' introuvable ou inaccessible avec ce token."
|
|
|
|
| 627 |
def get_repo_root(cwd: Optional[Path] = None) -> Path:
|
| 628 |
"""
|
| 629 |
Détecte la racine du dépôt git courant.
|
| 630 |
+
|
| 631 |
+
Paramètres
|
| 632 |
+
----------
|
| 633 |
+
cwd : Optional[Path]
|
| 634 |
+
Répertoire de départ. Si None, répertoire courant du process.
|
| 635 |
+
|
| 636 |
+
Retour
|
| 637 |
+
------
|
| 638 |
+
Path
|
| 639 |
+
Racine du dépôt.
|
| 640 |
+
|
| 641 |
+
Exceptions
|
| 642 |
+
----------
|
| 643 |
+
GitHubSyncError
|
| 644 |
+
Si le répertoire courant n'est pas un dépôt git.
|
| 645 |
"""
|
| 646 |
cwd = cwd or Path.cwd()
|
| 647 |
result = run_cmd(
|
|
|
|
| 660 |
def get_current_branch(repo_root: Path) -> str:
|
| 661 |
"""
|
| 662 |
Récupère la branche courante si possible.
|
| 663 |
+
|
| 664 |
+
Paramètres
|
| 665 |
+
----------
|
| 666 |
+
repo_root : Path
|
| 667 |
+
Racine du dépôt git.
|
| 668 |
+
|
| 669 |
+
Retour
|
| 670 |
+
------
|
| 671 |
+
str
|
| 672 |
+
Nom de branche ou 'main' en fallback.
|
| 673 |
"""
|
| 674 |
result = run_cmd(
|
| 675 |
["git", "rev-parse", "--abbrev-ref", "HEAD"],
|
|
|
|
| 686 |
def has_worktree_changes(repo_root: Path) -> bool:
|
| 687 |
"""
|
| 688 |
Indique si le dépôt contient des changements non commités.
|
| 689 |
+
|
| 690 |
+
Paramètres
|
| 691 |
+
----------
|
| 692 |
+
repo_root : Path
|
| 693 |
+
Racine du dépôt git.
|
| 694 |
+
|
| 695 |
+
Retour
|
| 696 |
+
------
|
| 697 |
+
bool
|
| 698 |
+
True si le working tree ou l'index contient des changements.
|
| 699 |
"""
|
| 700 |
result = run_cmd(
|
| 701 |
["git", "status", "--porcelain"],
|
|
|
|
| 710 |
def ensure_git_identity(repo_root: Path, name: str, email: str) -> None:
|
| 711 |
"""
|
| 712 |
Définit localement l'identité git si nécessaire.
|
| 713 |
+
|
| 714 |
+
Paramètres
|
| 715 |
+
----------
|
| 716 |
+
repo_root : Path
|
| 717 |
+
Racine du dépôt.
|
| 718 |
+
name : str
|
| 719 |
+
Nom Git.
|
| 720 |
+
email : str
|
| 721 |
+
Email Git.
|
| 722 |
"""
|
| 723 |
current_name = run_cmd(
|
| 724 |
["git", "config", "--get", "user.name"],
|
|
|
|
| 743 |
def ensure_clean_github_remote(repo_root: Path, remote_name: str, repo: str) -> str:
|
| 744 |
"""
|
| 745 |
Crée ou met à jour un remote local propre vers GitHub, sans secret.
|
| 746 |
+
|
| 747 |
+
Paramètres
|
| 748 |
+
----------
|
| 749 |
+
repo_root : Path
|
| 750 |
+
Racine du dépôt.
|
| 751 |
+
remote_name : str
|
| 752 |
+
Nom du remote local.
|
| 753 |
+
repo : str
|
| 754 |
+
Repo GitHub au format owner/repository.
|
| 755 |
+
|
| 756 |
+
Retour
|
| 757 |
+
------
|
| 758 |
+
str
|
| 759 |
+
URL HTTPS propre du dépôt GitHub.
|
| 760 |
"""
|
| 761 |
clean_url = f"https://github.com/{repo}.git"
|
| 762 |
|
|
|
|
| 800 |
def build_authenticated_push_url(repo: str, token: str) -> str:
|
| 801 |
"""
|
| 802 |
Construit une URL HTTPS authentifiée éphémère pour le push.
|
| 803 |
+
|
| 804 |
+
Paramètres
|
| 805 |
+
----------
|
| 806 |
+
repo : str
|
| 807 |
+
Repo GitHub au format owner/repository.
|
| 808 |
+
token : str
|
| 809 |
+
Token GitHub.
|
| 810 |
+
|
| 811 |
+
Retour
|
| 812 |
+
------
|
| 813 |
+
str
|
| 814 |
+
URL HTTPS authentifiée.
|
| 815 |
"""
|
| 816 |
return f"https://x-access-token:{token}@github.com/{repo}.git"
|
| 817 |
|
|
|
|
| 819 |
def stage_all_changes(repo_root: Path) -> None:
|
| 820 |
"""
|
| 821 |
Stage l'ensemble des changements du dépôt.
|
| 822 |
+
|
| 823 |
+
Paramètres
|
| 824 |
+
----------
|
| 825 |
+
repo_root : Path
|
| 826 |
+
Racine du dépôt.
|
| 827 |
"""
|
| 828 |
run_cmd(["git", "add", "-A"], cwd=repo_root, check=True)
|
| 829 |
LOGGER.info("[GITHUB_SYNC] Tous les changements ont été ajoutés à l'index.")
|
|
|
|
| 837 |
) -> bool:
|
| 838 |
"""
|
| 839 |
Commit les changements si nécessaire.
|
| 840 |
+
|
| 841 |
+
Paramètres
|
| 842 |
+
----------
|
| 843 |
+
repo_root : Path
|
| 844 |
+
Racine du dépôt.
|
| 845 |
+
commit_message : str
|
| 846 |
+
Message de commit.
|
| 847 |
+
committer_name : str
|
| 848 |
+
Nom du committer.
|
| 849 |
+
committer_email : str
|
| 850 |
+
Email du committer.
|
| 851 |
+
|
| 852 |
+
Retour
|
| 853 |
+
------
|
| 854 |
+
bool
|
| 855 |
+
True si un commit a été créé, sinon False.
|
| 856 |
"""
|
| 857 |
if not has_worktree_changes(repo_root):
|
| 858 |
LOGGER.info("[GITHUB_SYNC] Aucun changement à committer.")
|
|
|
|
| 896 |
def diagnose_push_failure(exc: GitCommandError) -> str:
|
| 897 |
"""
|
| 898 |
Produit un diagnostic métier lisible à partir d'une erreur de push Git.
|
| 899 |
+
|
| 900 |
+
Paramètres
|
| 901 |
+
----------
|
| 902 |
+
exc : GitCommandError
|
| 903 |
+
Exception détaillée de push.
|
| 904 |
+
|
| 905 |
+
Retour
|
| 906 |
+
------
|
| 907 |
+
str
|
| 908 |
+
Message de diagnostic enrichi.
|
| 909 |
"""
|
| 910 |
blob = f"{exc.stdout}\n{exc.stderr}".lower()
|
| 911 |
|
|
|
|
| 949 |
"Push GitHub refusé car l'historique distant a divergé (non-fast-forward)."
|
| 950 |
)
|
| 951 |
|
| 952 |
+
if "stale info" in blob:
|
| 953 |
+
return (
|
| 954 |
+
"Push GitHub refusé car la lease `force-with-lease` n'est plus valide "
|
| 955 |
+
"par rapport à l'état distant attendu."
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
return (
|
| 959 |
"Push GitHub refusé. Consulte le stderr détaillé remonté dans l'exception/log pour "
|
| 960 |
"connaître le motif exact renvoyé par GitHub."
|
|
|
|
| 964 |
def is_non_fast_forward_error(exc: GitCommandError) -> bool:
|
| 965 |
"""
|
| 966 |
Détecte un rejet de type non-fast-forward / fetch first.
|
| 967 |
+
|
| 968 |
+
Paramètres
|
| 969 |
+
----------
|
| 970 |
+
exc : GitCommandError
|
| 971 |
+
Exception git.
|
| 972 |
+
|
| 973 |
+
Retour
|
| 974 |
+
------
|
| 975 |
+
bool
|
| 976 |
+
True si le rejet correspond à une divergence distante.
|
| 977 |
"""
|
| 978 |
blob = f"{exc.stdout}\n{exc.stderr}".lower()
|
| 979 |
return (
|
|
|
|
| 990 |
token: str,
|
| 991 |
) -> None:
|
| 992 |
"""
|
| 993 |
+
Récupère la branche distante dans refs/remotes/github/<branch> pour disposer
|
| 994 |
+
d'une vision actualisée avant un éventuel --force-with-lease explicite.
|
| 995 |
+
|
| 996 |
+
Paramètres
|
| 997 |
+
----------
|
| 998 |
+
repo_root : Path
|
| 999 |
+
Racine du dépôt.
|
| 1000 |
+
repo : str
|
| 1001 |
+
Repo GitHub au format owner/repository.
|
| 1002 |
+
branch : str
|
| 1003 |
+
Branche distante.
|
| 1004 |
+
token : str
|
| 1005 |
+
Token GitHub.
|
| 1006 |
"""
|
| 1007 |
push_url = build_authenticated_push_url(repo, token)
|
| 1008 |
run_cmd(
|
|
|
|
| 1023 |
)
|
| 1024 |
|
| 1025 |
|
| 1026 |
+
def get_ref_sha(repo_root: Path, ref_name: str) -> str:
|
| 1027 |
+
"""
|
| 1028 |
+
Lit le SHA exact d'une ref git locale.
|
| 1029 |
+
|
| 1030 |
+
Paramètres
|
| 1031 |
+
----------
|
| 1032 |
+
repo_root : Path
|
| 1033 |
+
Racine du dépôt.
|
| 1034 |
+
ref_name : str
|
| 1035 |
+
Référence git, ex. refs/remotes/github/main
|
| 1036 |
+
|
| 1037 |
+
Retour
|
| 1038 |
+
------
|
| 1039 |
+
str
|
| 1040 |
+
SHA complet de la ref.
|
| 1041 |
+
|
| 1042 |
+
Exceptions
|
| 1043 |
+
----------
|
| 1044 |
+
GitHubSyncError
|
| 1045 |
+
Si la ref n'existe pas ou ne peut pas être résolue.
|
| 1046 |
+
"""
|
| 1047 |
+
result = run_cmd(
|
| 1048 |
+
["git", "rev-parse", ref_name],
|
| 1049 |
+
cwd=repo_root,
|
| 1050 |
+
check=True,
|
| 1051 |
+
)
|
| 1052 |
+
sha = (result.stdout or "").strip()
|
| 1053 |
+
if not sha:
|
| 1054 |
+
raise GitHubSyncError(f"Impossible de résoudre le SHA de la ref '{ref_name}'.")
|
| 1055 |
+
LOGGER.info("[GITHUB_SYNC] SHA résolu | ref=%s | sha=%s", ref_name, sha)
|
| 1056 |
+
return sha
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
def build_force_with_lease_arg(branch: str, expected_remote_sha: str) -> str:
|
| 1060 |
+
"""
|
| 1061 |
+
Construit l'argument explicite force-with-lease pour la branche distante.
|
| 1062 |
+
|
| 1063 |
+
Paramètres
|
| 1064 |
+
----------
|
| 1065 |
+
branch : str
|
| 1066 |
+
Nom de branche distante.
|
| 1067 |
+
expected_remote_sha : str
|
| 1068 |
+
SHA exact attendu actuellement sur la branche distante.
|
| 1069 |
+
|
| 1070 |
+
Retour
|
| 1071 |
+
------
|
| 1072 |
+
str
|
| 1073 |
+
Argument du style :
|
| 1074 |
+
--force-with-lease=refs/heads/main:<sha>
|
| 1075 |
+
"""
|
| 1076 |
+
return f"--force-with-lease=refs/heads/{branch}:{expected_remote_sha}"
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
def _build_push_command(
|
| 1080 |
+
push_url: str,
|
| 1081 |
+
branch: str,
|
| 1082 |
+
mode: str,
|
| 1083 |
+
lease_arg: Optional[str] = None,
|
| 1084 |
+
) -> List[str]:
|
| 1085 |
"""
|
| 1086 |
Construit la commande git push adaptée au mode choisi.
|
| 1087 |
|
|
|
|
| 1093 |
Branche cible.
|
| 1094 |
mode : str
|
| 1095 |
fast_forward_only / force_with_lease / force
|
| 1096 |
+
lease_arg : Optional[str]
|
| 1097 |
+
Argument explicite `--force-with-lease=...` si mode=force_with_lease.
|
| 1098 |
|
| 1099 |
Retour
|
| 1100 |
------
|
| 1101 |
List[str]
|
| 1102 |
Commande complète.
|
| 1103 |
+
|
| 1104 |
+
Exceptions
|
| 1105 |
+
----------
|
| 1106 |
+
GitHubSyncError
|
| 1107 |
+
Si la combinaison d'arguments est invalide.
|
| 1108 |
"""
|
| 1109 |
base = [
|
| 1110 |
"git",
|
|
|
|
| 1114 |
]
|
| 1115 |
|
| 1116 |
if mode == "force_with_lease":
|
| 1117 |
+
if not lease_arg:
|
| 1118 |
+
raise GitHubSyncError(
|
| 1119 |
+
"Mode force_with_lease demandé sans lease_arg explicite."
|
| 1120 |
+
)
|
| 1121 |
+
base.append(lease_arg)
|
| 1122 |
elif mode == "force":
|
| 1123 |
base.append("--force")
|
| 1124 |
elif mode != "fast_forward_only":
|
|
|
|
| 1134 |
branch: str,
|
| 1135 |
token: str,
|
| 1136 |
mode: str,
|
| 1137 |
+
lease_arg: Optional[str] = None,
|
| 1138 |
) -> dict:
|
| 1139 |
"""
|
| 1140 |
Exécute réellement un push dans le mode demandé.
|
| 1141 |
+
|
| 1142 |
+
Paramètres
|
| 1143 |
+
----------
|
| 1144 |
+
repo_root : Path
|
| 1145 |
+
Racine du dépôt.
|
| 1146 |
+
repo : str
|
| 1147 |
+
Repo GitHub au format owner/repository.
|
| 1148 |
+
branch : str
|
| 1149 |
+
Branche cible.
|
| 1150 |
+
token : str
|
| 1151 |
+
Token GitHub.
|
| 1152 |
+
mode : str
|
| 1153 |
+
fast_forward_only / force_with_lease / force
|
| 1154 |
+
lease_arg : Optional[str]
|
| 1155 |
+
Argument explicite de lease si mode=force_with_lease.
|
| 1156 |
+
|
| 1157 |
+
Retour
|
| 1158 |
+
------
|
| 1159 |
+
dict
|
| 1160 |
+
Résumé d'exécution du push.
|
| 1161 |
"""
|
| 1162 |
push_url = build_authenticated_push_url(repo, token)
|
| 1163 |
+
cmd = _build_push_command(
|
| 1164 |
+
push_url=push_url,
|
| 1165 |
+
branch=branch,
|
| 1166 |
+
mode=mode,
|
| 1167 |
+
lease_arg=lease_arg,
|
| 1168 |
+
)
|
| 1169 |
|
| 1170 |
LOGGER.info(
|
| 1171 |
"[GITHUB_SYNC] Push GitHub | repo=%s | branch=%s | mode=%s",
|
|
|
|
| 1174 |
mode,
|
| 1175 |
)
|
| 1176 |
|
| 1177 |
+
if lease_arg:
|
| 1178 |
+
LOGGER.info("[GITHUB_SYNC] Lease explicite utilisée | %s", lease_arg)
|
| 1179 |
+
|
| 1180 |
result = run_cmd(
|
| 1181 |
cmd,
|
| 1182 |
cwd=repo_root,
|
|
|
|
| 1190 |
"returncode": result.returncode,
|
| 1191 |
"stdout": _sanitize_text(result.stdout or "", token),
|
| 1192 |
"stderr": _sanitize_text(result.stderr or "", token),
|
| 1193 |
+
"lease_arg": lease_arg,
|
| 1194 |
}
|
| 1195 |
|
| 1196 |
|
|
|
|
| 1228 |
Comportement
|
| 1229 |
------------
|
| 1230 |
- fast_forward_only : push simple uniquement
|
| 1231 |
+
- force_with_lease : fetch du remote, lecture du SHA, puis push avec lease explicite
|
| 1232 |
- force : push forcé direct
|
| 1233 |
+
- auto : push simple, puis fallback force_with_lease explicite si divergence
|
| 1234 |
et si la branche n'est pas protégée
|
| 1235 |
"""
|
| 1236 |
branch_protected = bool((preflight or {}).get("branch_protected"))
|
|
|
|
| 1247 |
f"un push --force-with-lease a de fortes chances d'être bloqué."
|
| 1248 |
)
|
| 1249 |
|
| 1250 |
+
if push_mode == "force":
|
| 1251 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1252 |
return _execute_push_mode(
|
| 1253 |
repo_root=repo_root,
|
| 1254 |
repo=repo,
|
| 1255 |
branch=branch,
|
| 1256 |
token=token,
|
| 1257 |
+
mode="force",
|
| 1258 |
+
)
|
| 1259 |
+
except GitCommandError as exc:
|
| 1260 |
+
diagnostic = diagnose_push_failure(exc)
|
| 1261 |
+
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
|
| 1262 |
+
|
| 1263 |
+
if push_mode == "force_with_lease":
|
| 1264 |
+
try:
|
| 1265 |
+
git_fetch_remote_branch(
|
| 1266 |
+
repo_root=repo_root,
|
| 1267 |
+
repo=repo,
|
| 1268 |
+
branch=branch,
|
| 1269 |
+
token=token,
|
| 1270 |
+
)
|
| 1271 |
+
expected_remote_sha = get_ref_sha(
|
| 1272 |
+
repo_root=repo_root,
|
| 1273 |
+
ref_name=f"refs/remotes/github/{branch}",
|
| 1274 |
+
)
|
| 1275 |
+
lease_arg = build_force_with_lease_arg(
|
| 1276 |
+
branch=branch,
|
| 1277 |
+
expected_remote_sha=expected_remote_sha,
|
| 1278 |
+
)
|
| 1279 |
+
return _execute_push_mode(
|
| 1280 |
+
repo_root=repo_root,
|
| 1281 |
+
repo=repo,
|
| 1282 |
+
branch=branch,
|
| 1283 |
+
token=token,
|
| 1284 |
+
mode="force_with_lease",
|
| 1285 |
+
lease_arg=lease_arg,
|
| 1286 |
+
)
|
| 1287 |
+
except GitCommandError as exc:
|
| 1288 |
+
diagnostic = diagnose_push_failure(exc)
|
| 1289 |
+
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
|
| 1290 |
+
|
| 1291 |
+
if push_mode == "fast_forward_only":
|
| 1292 |
+
try:
|
| 1293 |
+
return _execute_push_mode(
|
| 1294 |
+
repo_root=repo_root,
|
| 1295 |
+
repo=repo,
|
| 1296 |
+
branch=branch,
|
| 1297 |
+
token=token,
|
| 1298 |
+
mode="fast_forward_only",
|
| 1299 |
)
|
| 1300 |
except GitCommandError as exc:
|
| 1301 |
diagnostic = diagnose_push_failure(exc)
|
|
|
|
| 1325 |
if branch_protected:
|
| 1326 |
diagnostic = (
|
| 1327 |
f"Push GitHub refusé: la branche '{branch}' diverge déjà et elle est protégée. "
|
| 1328 |
+
f"Le fallback automatique force_with_lease n'est pas tenté."
|
| 1329 |
)
|
| 1330 |
raise GitHubSyncError(f"{diagnostic} | {exc}") from exc
|
| 1331 |
|
| 1332 |
LOGGER.warning(
|
| 1333 |
+
"[GITHUB_SYNC] Fallback automatique activé -> tentative force_with_lease explicite sur '%s'.",
|
| 1334 |
branch,
|
| 1335 |
)
|
| 1336 |
|
|
|
|
| 1341 |
branch=branch,
|
| 1342 |
token=token,
|
| 1343 |
)
|
| 1344 |
+
expected_remote_sha = get_ref_sha(
|
| 1345 |
+
repo_root=repo_root,
|
| 1346 |
+
ref_name=f"refs/remotes/github/{branch}",
|
| 1347 |
+
)
|
| 1348 |
+
lease_arg = build_force_with_lease_arg(
|
| 1349 |
+
branch=branch,
|
| 1350 |
+
expected_remote_sha=expected_remote_sha,
|
| 1351 |
+
)
|
| 1352 |
return _execute_push_mode(
|
| 1353 |
repo_root=repo_root,
|
| 1354 |
repo=repo,
|
| 1355 |
branch=branch,
|
| 1356 |
token=token,
|
| 1357 |
mode="force_with_lease",
|
| 1358 |
+
lease_arg=lease_arg,
|
| 1359 |
)
|
| 1360 |
except GitCommandError as exc2:
|
| 1361 |
diagnostic = diagnose_push_failure(exc2)
|
| 1362 |
raise GitHubSyncError(
|
| 1363 |
+
f"Echec du fallback auto force_with_lease explicite. {diagnostic} | {exc2}"
|
| 1364 |
) from exc2
|
| 1365 |
|
| 1366 |
|
|
|
|
| 1389 |
------
|
| 1390 |
dict
|
| 1391 |
Résumé de synchronisation exploitable par l'appelant.
|
| 1392 |
+
|
| 1393 |
+
Exceptions
|
| 1394 |
+
----------
|
| 1395 |
+
GitHubSyncError
|
| 1396 |
+
En cas d'erreur de configuration, git, API GitHub ou push.
|
| 1397 |
"""
|
| 1398 |
ensure_logger_configured(logging.INFO)
|
| 1399 |
|
|
|
|
| 1442 |
"stdout": "",
|
| 1443 |
"stderr": "",
|
| 1444 |
"mode_used": None,
|
| 1445 |
+
"lease_arg": None,
|
| 1446 |
}
|
| 1447 |
|
| 1448 |
if commit_created or allow_empty_push:
|