diff --git a/repo-stats/README.adoc b/repo-stats/README.adoc index 0a00116..59203ca 100644 --- a/repo-stats/README.adoc +++ b/repo-stats/README.adoc @@ -98,6 +98,8 @@ Both options are optional, and you can use either one alone. repo-stats never reads, stores or sends a token. `gh` and `glab` find their own login, in this order: an environment variable (`GH_TOKEN`, `GITLAB_TOKEN`), then the login saved by `gh auth login` or `glab auth login` (in the OS keychain where there is one). +NOTE: `gh` reads `GH_TOKEN` only for github.com and `*.ghe.com`. For GitHub Enterprise Server, name the variable `GH_ENTERPRISE_TOKEN` instead. + === On your machine Use the login you already have, or run `gh auth login` / `glab auth login` once. Nothing else is needed. @@ -132,6 +134,7 @@ jobs: - uses: actions/checkout@v4 with: repository: husam-e/scripts + ref: # pin a commit you have reviewed: it runs next to the token path: tools - run: python3 tools/repo-stats/repo_stats.py . -o repo-stats.html env: @@ -143,6 +146,7 @@ jobs: ---- Set `GH_TOKEN` on this step only, so other steps never see it. +On GitHub Enterprise Server, set `GH_ENTERPRISE_TOKEN: ${{ github.token }}` instead; `gh` ignores `GH_TOKEN` there. To analyse another private repository, use a GitHub App installation token (for example from `actions/create-github-app-token`), not a personal token. === GitLab CI @@ -154,9 +158,12 @@ repo-stats: variables: GIT_DEPTH: 0 # full history GLAB_ENABLE_CI_AUTOLOGIN: "true" # glab signs in with the job's CI_JOB_TOKEN + REPO_STATS_SHA: "" # pin a commit you have reviewed: it runs next to the token script: - apk add --no-cache python3 - - git clone --depth 1 https://github.com/husam-e/scripts.git /tmp/tools + - git init -q /tmp/tools + - git -C /tmp/tools fetch -q --depth 1 https://github.com/husam-e/scripts.git "$REPO_STATS_SHA" + - git -C /tmp/tools checkout -q FETCH_HEAD - python3 /tmp/tools/repo-stats/repo_stats.py . -o repo-stats.html artifacts: paths: [repo-stats.html] @@ -197,7 +204,7 @@ repo-stats never handles a credential: * It never reads a token variable. `gh` and `glab` read their own. * The API host is `github.com` or `gitlab.com` from the remote, or the `--hostname` you pass. It is never taken from any other remote, because `gh` and `glab` send environment tokens to whatever host they are given. A lookalike remote such as `github.evil.example` starts no CLI at all. -* The CLI always gets `--hostname` and runs from the system temp directory, never the analysed repository, so `glab` cannot pick up a host from the repository's remote. glab telemetry (which sends its own request with the credential) and the CLIs' request-logging debug switches are turned off for these calls. +* The CLI always gets `--hostname` and runs from a new, empty, private temporary directory (mode 0700), never the analysed repository or the shared temp directory, so `glab` cannot pick up a host or config from a repository's `.git`. glab telemetry (which sends its own request with the credential) and the CLIs' request-logging debug switches are turned off for these calls. * git runs without the credential variables (`GH_TOKEN`, `GITLAB_TOKEN`, `CI_JOB_TOKEN` and the like), so hooks or filters in the analysed repository cannot read them. * No token is written to any output. diff --git a/repo-stats/repo_stats.py b/repo-stats/repo_stats.py index f412517..8a7d23a 100644 --- a/repo-stats/repo_stats.py +++ b/repo-stats/repo_stats.py @@ -720,7 +720,8 @@ def infer_prs_from_git(first_parent: List[Commit], graph: Graph, default_branch: # GitLab CI job token. Two CLI behaviours shape this code: both send an environment token to whatever # --hostname they are given, and glab without --hostname follows the remote of the git repository in its # working directory. So the host always comes from the allowlist or an explicit flag, it is always passed -# as --hostname, and the CLI runs from the system temp directory, not the analysed repository. +# as --hostname, and the CLI runs from a new private temp directory, not the analysed repository (or the +# shared system temp directory, where another local user could plant a .git). class ApiError(ToolError): """A failed or unexpected GitHub/GitLab API call. `status` is the HTTP status, when there was one.""" @@ -736,10 +737,19 @@ class CliUnavailable(ApiError): CLI_FOR = {"github": "gh", "gitlab": "glab"} -CLI_HELP = { # tool -> (install page, what to set in CI) - "gh": ("https://cli.github.com", "GH_TOKEN"), - "glab": ("https://gitlab.com/gitlab-org/cli", "GLAB_ENABLE_CI_AUTOLOGIN=true or GITLAB_TOKEN"), -} +CLI_INSTALL = {"gh": "https://cli.github.com", "glab": "https://gitlab.com/gitlab-org/cli"} + + +def ci_login_hint(tool: str, host: str) -> str: + """Return what to set in CI so `tool` finds a login for `host`. + + gh reads GH_TOKEN only for github.com and *.ghe.com; GitHub Enterprise Server needs GH_ENTERPRISE_TOKEN. + """ + if tool == "glab": + return "GLAB_ENABLE_CI_AUTOLOGIN=true or GITLAB_TOKEN" + return "GH_TOKEN" if host == "github.com" or host.endswith(".ghe.com") else "GH_ENTERPRISE_TOKEN" + + # Debug switches that make the CLIs dump requests to stderr, which repo-stats may quote in an error. CLI_DEBUG_VARS = ("GH_DEBUG", "DEBUG", "GLAB_DEBUG", "GLAB_DEBUG_HTTP") CLI_TIMEOUT = 120 @@ -752,6 +762,11 @@ class CliUnavailable(ApiError): GITLAB_READ_ENDPOINT = re.compile(r"^projects/[^/?#\s]+/merge_requests(?:/\d+/(?:commits|notes))?$") +def _backoff(seconds: float) -> None: + """Wait between API retries. Tests replace this, not time.sleep, which subprocess also uses.""" + time.sleep(seconds) + + def _retry_after(value: Optional[str], default: int) -> int: """Seconds to wait from a Retry-After header (integer seconds or an HTTP date), capped at 60.""" if not value: @@ -792,9 +807,9 @@ def parse_cli_response(out: bytes) -> Tuple[Optional[int], Dict[str, str], bytes class Cli: """Read-only access to one GitHub or GitLab host through `gh api` or `glab api`. - Every request passes the read-only allowlist, gets an explicit --hostname, runs from the system temp - directory, and runs without debug switches and (for glab) without telemetry, which would send its own - request with the credential. + Every request passes the read-only allowlist, gets an explicit --hostname, runs from a private temp + directory (removed by close() or at the end of a `with` block), and runs without debug switches and + (for glab) without telemetry, which would send its own request with the credential. """ def __init__(self, tool: str, host: str, environ: Optional[Mapping[str, str]] = None) -> None: @@ -803,9 +818,23 @@ def __init__(self, tool: str, host: str, environ: Optional[Mapping[str, str]] = env["GLAB_SEND_TELEMETRY"] = "false" exe = shutil.which(tool, path=env.get("PATH", os.defpath)) if not exe: - raise CliUnavailable(f"{tool} is not installed. Install it from {CLI_HELP[tool][0]} for exact PR data.") + raise CliUnavailable(f"{tool} is not installed. Install it from {CLI_INSTALL[tool]} for exact PR data.") self.tool, self.host, self.exe, self.env = tool, host, exe, env - self.hint = f"Run `{tool} auth login --hostname {host}`, or in CI set {CLI_HELP[tool][1]}." + self.hint = f"Run `{tool} auth login --hostname {host}`, or in CI set {ci_login_hint(tool, host)}." + # Mode 0700 and empty: no .git or CLI config of the analysed repository or of another local user. + self._cwd = tempfile.TemporaryDirectory(prefix="repo-stats-cli-") + + def close(self) -> None: + """Remove the private working directory.""" + self._cwd.cleanup() + + def __enter__(self) -> "Cli": + """Return self; the working directory is removed on exit.""" + return self + + def __exit__(self, *exc: object) -> None: + """Remove the private working directory.""" + self.close() def graphql(self, query: str, variables: Mapping[str, Optional[str]]) -> Any: """Send a read-only GraphQL query with string variables (None values are left out); return the JSON.""" @@ -831,11 +860,11 @@ def _run(self, args: List[str]) -> Tuple[Any, Dict[str, str]]: delay = 2 for attempt in range(CLI_RETRIES + 1): try: - p = subprocess.run([self.exe, *args], cwd=tempfile.gettempdir(), env=self.env, stdin=subprocess.DEVNULL, + p = subprocess.run([self.exe, *args], cwd=self._cwd.name, env=self.env, stdin=subprocess.DEVNULL, capture_output=True, timeout=CLI_TIMEOUT) except subprocess.TimeoutExpired: if attempt < CLI_RETRIES: - time.sleep(delay) + _backoff(delay) delay *= 2 continue raise ApiError(f"{self.tool} api timed out after {CLI_TIMEOUT}s") @@ -849,7 +878,7 @@ def _run(self, args: List[str]) -> Tuple[Any, Dict[str, str]]: # No HTTP response at all (DNS, refused connection, TLS): retrying will not fix it. raise ApiError(f"Could not reach the API through {self.tool}: {err or f'exit status {p.returncode}'}") if status in (429, 500, 502, 503, 504) and attempt < CLI_RETRIES: - time.sleep(_retry_after(headers.get("retry-after"), delay)) + _backoff(_retry_after(headers.get("retry-after"), delay)) delay *= 2 continue if status == 401: @@ -1046,8 +1075,8 @@ def fetch_gitlab(cli: Cli, project_path: str, since: Optional[int], base_branch: """Fetch merge requests from the GitLab REST API through `glab api`, with per-MR commit and review times. REST, not GraphQL, because a GitLab CI job token cannot call GraphQL. A job token can list MRs and - their notes but not their commits; when the commits endpoint is refused, commit lookups stop and the - PRs are marked "commits_refused" so build_records can use local merge commits instead. + their notes but not their commits; when the commits endpoint is refused (401 or 403), commit lookups + stop and the PRs are marked "commits_refused" so build_records can use local merge commits instead. `info`, if given, receives "seen" (MRs fetched), "detail_errors" and "commits_refused" (0 or 1). """ @@ -1101,7 +1130,7 @@ def mr_commits(iid: Any) -> List[Dict[str, Any]]: try: probe = mr_commits(mrs[0]["iid"]) except ApiError as e: - commits_refused = e.status in (401, 403, 404) + commits_refused = e.status in (401, 403) # a 404 is about that one MR, not the login except (ValueError, KeyError, TypeError, AttributeError): pass @@ -1555,17 +1584,17 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non tool = CLI_FOR[provider] path = parsed[1] try: - cli = Cli(tool, api_host, env) - log(f"Fetching pull requests from {api_host} with `{tool} api` ...") - if provider == "github": - if "/" not in path: - raise ApiError(f"Cannot read owner/name from the remote path '{path}'") - owner, name = path.split("/", 1) - api_prs = fetch_github(cli, owner, name, since, short_branch, args.all_bases, args.max_prs, - info=info) - else: - api_prs = fetch_gitlab(cli, path, since, short_branch, args.all_bases, args.max_prs, - not args.no_reviews, info=info) + with Cli(tool, api_host, env) as cli: + log(f"Fetching pull requests from {api_host} with `{tool} api` ...") + if provider == "github": + if "/" not in path: + raise ApiError(f"Cannot read owner/name from the remote path '{path}'") + owner, name = path.split("/", 1) + api_prs = fetch_github(cli, owner, name, since, short_branch, args.all_bases, args.max_prs, + info=info) + else: + api_prs = fetch_gitlab(cli, path, since, short_branch, args.all_bases, args.max_prs, + not args.no_reviews, info=info) except CliUnavailable as e: if source == "api": raise diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 40d35ed..e55a18d 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -1248,7 +1248,7 @@ def h(req: ms.Request) -> ms.Response: return 500, {}, {"message": "boom"} return ms.gitlab_handler(self.mrs, self.commits, self.notes, page_size=50)(req) - with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(h) as srv: + with mock.patch.object(rs, "_backoff", lambda s: None), ms.MockServer(h) as srv: d, _ = collect(self.r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "api") @@ -1347,6 +1347,34 @@ def test_source_api_not_logged_in_is_error(self) -> None: self.assertIn("gh auth login --hostname github.com", p.stderr) self.assertNotIn("Traceback", p.stderr) + def test_login_hint_names_the_variable_gh_reads_for_the_host(self) -> None: + """github.com needs GH_TOKEN; GitHub Enterprise Server needs GH_ENTERPRISE_TOKEN, and GH_TOKEN is not enough.""" + self.assertEqual(rs.ci_login_hint("gh", "github.com"), "GH_TOKEN") + self.assertEqual(rs.ci_login_hint("gh", "acme.ghe.com"), "GH_TOKEN") + self.assertEqual(rs.ci_login_hint("gh", "ghe.corp.example"), "GH_ENTERPRISE_TOKEN") + self.assertIn("GITLAB_TOKEN", rs.ci_login_hint("glab", "gitlab.com")) + r = api_repo("https://ghe.corp.example/acme/widgets.git") + d, _ = collect(r, "--provider", "github", "--hostname", "ghe.corp.example", env={"GH_TOKEN": FAKE}) + self.assertEqual(d["meta"]["mode"], "git") + self.assertTrue(any("not logged in to ghe.corp.example" in w and "set GH_ENTERPRISE_TOKEN" in w + for w in d["meta"]["warnings"]), d["meta"]["warnings"]) + + def test_glab_without_login_falls_back_with_the_login_command(self) -> None: + """glab with no login sends an anonymous request; the 401 falls back to git and names `glab auth login`.""" + r = api_repo("git@gitlab.com:grp/proj.git") + mrs, commits, notes = gitlab_fixture(r) + with ms.MockServer(ms.gitlab_handler(mrs, commits, notes, page_size=50)) as srv: + d, _ = collect(r, "--fake-api", srv.url) + self.assertTrue(srv.requests) + self.assertTrue(all("private-token" not in q["headers"] for q in srv.requests)) + self.assertEqual(d["meta"]["mode"], "git") + self.assertTrue(any("401" in w and "glab auth login --hostname gitlab.com" in w for w in d["meta"]["warnings"]), + d["meta"]["warnings"]) + with ms.MockServer(ms.gitlab_handler(mrs, commits, notes, page_size=50)) as srv: + with self.assertRaises(rs.ApiError) as cm: + collect(r, "--fake-api", srv.url, "--source", "api") + self.assertIn("glab auth login", str(cm.exception)) + def test_missing_cli_falls_back_or_errors(self) -> None: """Without gh installed, auto mode uses git and says where to get it; --source api is an error.""" r = api_repo() @@ -1361,8 +1389,10 @@ def test_missing_cli_warns_on_the_command_line(self) -> None: """Without gh on PATH, the run prints a warning, uses local git history and says so.""" r = api_repo() empty = tmpdir() - git_dir = Path(subprocess.run(["sh", "-c", "command -v git"], capture_output=True, text=True).stdout.strip()).parent - p = run_cli([r.path, "-o", tmpdir() / "o.html"], env={"PATH": os.pathsep.join([str(empty), str(git_dir)])}) + # Only git on PATH: the directory git lives in may also hold a real gh, which must never run here. + git = subprocess.run(["sh", "-c", "command -v git"], capture_output=True, text=True).stdout.strip() + os.symlink(git, empty / "git") + p = run_cli([r.path, "-o", tmpdir() / "o.html"], env={"PATH": str(empty)}) self.assertEqual(p.returncode, 0, p.stderr) self.assertIn("warning: gh is not installed", p.stderr) self.assertIn("PRs are inferred from git history", p.stderr) @@ -1426,7 +1456,7 @@ def test_api_source_errors_for_4xx_cli(self) -> None: def test_500_retries_then_falls_back(self) -> None: """Server errors are retried with exponential back-off, then fall back.""" sleeps = [] - with mock.patch.object(rs.time, "sleep", sleeps.append), self._srv(500) as srv: + with mock.patch.object(rs, "_backoff", sleeps.append), self._srv(500) as srv: d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(len(srv.requests), 5) self.assertEqual(sleeps, [2, 4, 8, 16]) @@ -1434,7 +1464,7 @@ def test_500_retries_then_falls_back(self) -> None: def test_500_with_source_api_raises(self) -> None: """--source api raises ToolError after repeated 500s.""" - with mock.patch.object(rs.time, "sleep", lambda s: None), self._srv(500) as srv: + with mock.patch.object(rs, "_backoff", lambda s: None), self._srv(500) as srv: with self.assertRaises(rs.ToolError) as cm: collect(self.r, "--fake-api", srv.url, "--source", "api", env={"GITHUB_TOKEN": FAKE}) self.assertIn("500", str(cm.exception)) @@ -1446,7 +1476,7 @@ def test_connection_refused(self) -> None: port = s.getsockname()[1] s.close() sleeps = [] - with mock.patch.object(rs.time, "sleep", sleeps.append): + with mock.patch.object(rs, "_backoff", sleeps.append): d, _ = collect(self.r, "--fake-api", f"http://127.0.0.1:{port}", env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git") self.assertTrue(any("Could not reach" in w for w in d["meta"]["warnings"])) @@ -1469,7 +1499,7 @@ def h(req: ms.Request) -> ms.Response: return inner(req) sleeps = [] - with mock.patch.object(rs.time, "sleep", sleeps.append), ms.MockServer(h) as srv: + with mock.patch.object(rs, "_backoff", sleeps.append), ms.MockServer(h) as srv: d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(sleeps, [3]) self.assertEqual(d["meta"]["mode"], "api") @@ -1487,7 +1517,7 @@ def h(req: ms.Request) -> ms.Response: return 429, {"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, {"message": "slow down"} return inner(req) - with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(h) as srv: + with mock.patch.object(rs, "_backoff", lambda s: None), ms.MockServer(h) as srv: d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "api") @@ -2277,9 +2307,9 @@ def _fetch(self, handler: ms.Handler) -> tuple[list[dict[str, Any]], dict[str, i """Run fetch_gitlab against `handler` and return (raw PRs, info).""" info: dict[str, int] = {} env = helpers.clean_env({"GITLAB_TOKEN": FAKE}) - with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(handler) as srv: - cli = rs.Cli("glab", "gitlab.com", {**env, "REPO_STATS_FAKE_URL": srv.url}) - prs = rs.fetch_gitlab(cli, "g/p", None, "main", False, None, True, progress=lambda m: None, info=info) + with mock.patch.object(rs, "_backoff", lambda s: None), ms.MockServer(handler) as srv: + with rs.Cli("glab", "gitlab.com", {**env, "REPO_STATS_FAKE_URL": srv.url}) as cli: + prs = rs.fetch_gitlab(cli, "g/p", None, "main", False, None, True, progress=lambda m: None, info=info) return prs, info def test_notes_failure_is_not_unreviewed(self) -> None: @@ -2310,7 +2340,7 @@ def h(req: ms.Request) -> ms.Response: """Fail every notes request with 500.""" return (500, {}, {"message": "boom"}) if req["path"].endswith("/notes") else base(req) - with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(h) as srv: + with mock.patch.object(rs, "_backoff", lambda s: None), ms.MockServer(h) as srv: d, _ = collect(r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE}) self.assertTrue(any("lookups fail" in w for w in d["meta"]["warnings"])) self.assertTrue(all(p["reviewed"] is None for p in d["prs"])) @@ -2437,9 +2467,11 @@ class G1_ReadOnlyCli(unittest.TestCase): """Every API request is a read-only gh/glab call to an explicit host, from outside the repository.""" def _cli(self, tool: str, url: str = "http://127.0.0.1:1", **extra: str) -> rs.Cli: - """A Cli for `tool` that uses the fake CLIs and the mock server at `url`.""" - return rs.Cli(tool, "github.com" if tool == "gh" else "gitlab.com", - helpers.clean_env({"REPO_STATS_FAKE_URL": url, **extra})) + """A Cli for `tool` that uses the fake CLIs and the mock server at `url`; closed after the test.""" + cli = rs.Cli(tool, "github.com" if tool == "gh" else "gitlab.com", + helpers.clean_env({"REPO_STATS_FAKE_URL": url, **extra})) + self.addCleanup(cli.close) + return cli def test_graphql_refuses_mutations(self) -> None: """Mutations, subscriptions and anything that is not a query are refused before gh runs.""" @@ -2491,7 +2523,7 @@ def test_hostname_needs_provider_for_unknown_hosts(self) -> None: self.assertTrue(any("needs --provider" in w for w in d["meta"]["warnings"])) def test_every_call_is_read_only_explicit_host_and_outside_the_repo(self) -> None: - """Each gh/glab call has --hostname and --include, no write flags, and runs from the system temp dir.""" + """Each gh/glab call has --hostname and --include, no write flags, and runs from a private temp dir.""" for remote, provider_env, handler_for in ( ("https://github.com/acme/widgets.git", "GITHUB_TOKEN", lambda r: ms.github_handler(desc_nodes(github_nodes(r)), page_size=3)), @@ -2515,7 +2547,20 @@ def test_every_call_is_read_only_explicit_host_and_outside_the_repo(self) -> Non self.assertEqual(argv[1], "graphql") query = next(a for a in argv if a.startswith("query="))[len("query="):] self.assertTrue(rs.READ_ONLY_GRAPHQL.match(query)) - self.assertEqual(Path(c["cwd"]).resolve(), Path(tempfile.gettempdir()).resolve()) + self.assertEqual(Path(c["cwd"]).resolve().parent, Path(tempfile.gettempdir()).resolve()) + self.assertTrue(Path(c["cwd"]).name.startswith("repo-stats-cli-"), c["cwd"]) + # One private directory per run, and it is gone afterwards. + self.assertEqual(len({c["cwd"] for c in calls}), 1) + self.assertFalse(Path(calls[0]["cwd"]).exists()) + + def test_cli_working_directory_is_private_and_empty(self) -> None: + """The CLI's working directory is new, empty and mode 0700, so nobody can plant a .git in it.""" + with rs.Cli("gh", "github.com", helpers.clean_env()) as cli: + cwd = Path(cli._cwd.name) + self.assertEqual(list(cwd.iterdir()), []) + if os.name == "posix": + self.assertEqual(cwd.stat().st_mode & 0o777, 0o700) + self.assertFalse(cwd.exists()) def test_cli_environment_has_no_telemetry_or_debug_switches(self) -> None: """glab runs with telemetry off, and neither CLI gets request-dumping debug flags.""" @@ -2612,6 +2657,31 @@ def h(req: ms.Request) -> ms.Response: self.assertTrue(p1["reviewed"]) # notes still work with a job token self.assertIsNone(by_number(d)[4]["first_commit"]) # open, no local commit: stays unknown + def test_404_on_the_probed_mr_does_not_stop_other_lookups(self) -> None: + """A 404 on one MR's commits is about that MR, not the login: the other MRs still get commit data.""" + r = api_repo("git@gitlab.com:grp/sub/proj.git") + mrs, commits, notes = gitlab_fixture(r) + inner = ms.gitlab_handler(mrs, commits, notes, page_size=50) + first: list[str] = [] + + def h(req: ms.Request) -> ms.Response: + """Answer 404 for the commits of the first MR asked about; serve everything else.""" + if req["path"].endswith("/commits"): + if not first: + first.append(req["path"]) + if req["path"] == first[0]: + return 404, {}, {"message": "404 Not Found"} + return inner(req) + + with ms.MockServer(h) as srv: + d, _ = collect(r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE}) + commit_paths = {q["path"] for q in srv.requests if q["path"].endswith("/commits")} + self.assertEqual(d["meta"]["mode"], "api") + self.assertGreater(len(commit_paths), 1, "lookups continue after a 404") + self.assertFalse(any("cannot read merge request commits" in w for w in d["meta"]["warnings"])) + self.assertTrue(any("1 merge request(s) had commit or review lookups fail" in w for w in d["meta"]["warnings"]), + d["meta"]["warnings"]) + def test_job_token_autologin_reaches_the_api(self) -> None: """With GLAB_ENABLE_CI_AUTOLOGIN in GitLab CI, glab authenticates with CI_JOB_TOKEN by itself.""" r = api_repo("git@gitlab.com:grp/sub/proj.git") @@ -2648,8 +2718,8 @@ def _gl(self, notes: Sequence[dict[str, Any]], merged: int | None = BASE + 20 * mr = ms.gl_mr(1, "feat: x", BASE, merged=merged) env = helpers.clean_env({"GITLAB_TOKEN": FAKE}) with ms.MockServer(ms.gitlab_handler([mr], {1: [ms.gl_commit(BASE)]}, {1: list(notes)})) as srv: - cli = rs.Cli("glab", "gitlab.com", {**env, "REPO_STATS_FAKE_URL": srv.url}) - return rs.fetch_gitlab(cli, "g/p", None, "main", False, None, want_reviews, progress=lambda m: None)[0] + with rs.Cli("glab", "gitlab.com", {**env, "REPO_STATS_FAKE_URL": srv.url}) as cli: + return rs.fetch_gitlab(cli, "g/p", None, "main", False, None, want_reviews, progress=lambda m: None)[0] # -- the counting rule