|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import os |
| 4 | +import re |
| 5 | +import stat |
| 6 | +import tempfile |
| 7 | +from contextlib import contextmanager |
3 | 8 | from datetime import datetime, timedelta, timezone |
4 | 9 | from pathlib import Path |
| 10 | +from typing import Iterator |
5 | 11 |
|
6 | 12 | from git import Repo |
7 | 13 | from git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError |
|
10 | 16 | from .sync_state import MANIFEST_NAME |
11 | 17 |
|
12 | 18 |
|
| 19 | +def git_pat_env_var_name(task_name: str) -> str: |
| 20 | + normalized = re.sub(r"\W+", "_", task_name.strip()).strip("_") |
| 21 | + return f"{normalized or 'TASK'}_key" |
| 22 | + |
| 23 | + |
13 | 24 | class GitManager: |
14 | 25 | def __init__(self) -> None: |
15 | 26 | self._next_push_at: dict[int, datetime] = {} |
@@ -53,15 +64,64 @@ def maybe_push(self, task: SyncTask) -> bool: |
53 | 64 | next_push = self._next_push_at.get(task_id) |
54 | 65 | if not next_push or datetime.now(timezone.utc) < next_push: |
55 | 66 | return False |
| 67 | + self.push(task) |
| 68 | + self._next_push_at.pop(task_id, None) |
| 69 | + self._last_push_at[task_id] = datetime.now(timezone.utc) |
| 70 | + return True |
| 71 | + |
| 72 | + def push(self, task: SyncTask) -> None: |
56 | 73 | repo = self.ensure_repo(task) |
57 | 74 | try: |
58 | 75 | remote = repo.remote(task.git.remote_name) |
59 | | - remote.push(task.git.branch) |
| 76 | + with self._push_environment(task, repo): |
| 77 | + remote.push(task.git.branch) |
60 | 78 | except (ValueError, GitCommandError): |
61 | 79 | raise |
62 | | - self._next_push_at.pop(task_id, None) |
63 | | - self._last_push_at[task_id] = datetime.now(timezone.utc) |
64 | | - return True |
65 | 80 |
|
66 | 81 | def last_push_at(self, task_id: int) -> datetime | None: |
67 | 82 | return self._last_push_at.get(task_id) |
| 83 | + |
| 84 | + @contextmanager |
| 85 | + def _push_environment(self, task: SyncTask, repo: Repo) -> Iterator[None]: |
| 86 | + token = self._pat_for_task(task) |
| 87 | + if not token: |
| 88 | + yield |
| 89 | + return |
| 90 | + |
| 91 | + askpass_path = self._write_askpass_script(token) |
| 92 | + try: |
| 93 | + with repo.git.custom_environment(GIT_ASKPASS=str(askpass_path), GIT_TERMINAL_PROMPT="0"): |
| 94 | + yield |
| 95 | + finally: |
| 96 | + askpass_path.unlink(missing_ok=True) |
| 97 | + |
| 98 | + def _pat_for_task(self, task: SyncTask) -> str | None: |
| 99 | + for env_var in self._pat_env_var_candidates(task): |
| 100 | + token = os.getenv(env_var) |
| 101 | + if token: |
| 102 | + return token |
| 103 | + return None |
| 104 | + |
| 105 | + def _pat_env_var_candidates(self, task: SyncTask) -> list[str]: |
| 106 | + primary = git_pat_env_var_name(task.name) |
| 107 | + candidates = [primary, primary.upper()] |
| 108 | + raw = f"{task.name}_key" |
| 109 | + if raw not in candidates: |
| 110 | + candidates.append(raw) |
| 111 | + return candidates |
| 112 | + |
| 113 | + def _write_askpass_script(self, token: str) -> Path: |
| 114 | + fd, name = tempfile.mkstemp(prefix="office-docs-git-askpass-", suffix=".sh") |
| 115 | + path = Path(name) |
| 116 | + with os.fdopen(fd, "w", encoding="utf-8") as handle: |
| 117 | + handle.write("#!/bin/sh\n") |
| 118 | + handle.write('case "$1" in\n') |
| 119 | + handle.write(' *Username*) printf "%s\\n" "x-access-token" ;;\n') |
| 120 | + handle.write(f' *) printf "%s\\n" "{self._shell_double_quote(token)}" ;;\n') |
| 121 | + handle.write("esac\n") |
| 122 | + path.chmod(path.stat().st_mode | stat.S_IXUSR) |
| 123 | + return path |
| 124 | + |
| 125 | + @staticmethod |
| 126 | + def _shell_double_quote(value: str) -> str: |
| 127 | + return value.replace("\\", "\\\\").replace('"', '\\"').replace("$", "\\$").replace("`", "\\`") |
0 commit comments