From a06da1322bb5853c976c8ef9f818c13afd9d04e7 Mon Sep 17 00:00:00 2001 From: "Michael B. Gale" Date: Tue, 13 Oct 2026 14:48:24 +0100 Subject: [PATCH] Add functions to get the current and dotcom instance --- src/github.test.ts | 44 +++++++++++++++++++++++++++++++++++++++++++- src/github.ts | 16 ++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/github.test.ts b/src/github.test.ts index 8645f493b..79dbb2331 100644 --- a/src/github.test.ts +++ b/src/github.test.ts @@ -1,7 +1,8 @@ import test from "ava"; +import { ActionsEnvVars } from "./environment"; import * as github from "./github"; -import { setupTests } from "./testing-utils"; +import { getTestEnv, setupTests } from "./testing-utils"; setupTests(test); @@ -67,3 +68,44 @@ test("parseGitHubUrl", (t) => { message: '"http:///::::433" is not a valid URL', }); }); + +test("getCurrentInstance throws if required env vars aren't set", (t) => { + t.throws(() => github.getCurrentInstance(getTestEnv())); + t.throws(() => { + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_SERVER_URL]: "https://localhost", + }); + github.getCurrentInstance(env); + }); + t.throws(() => { + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_API_URL]: "https://api.localhost", + }); + github.getCurrentInstance(env); + }); +}); + +test("getCurrentInstance constructs instance from environment", (t) => { + const url = "https://localhost"; + const apiUrl = "https://api.localhost"; + + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_SERVER_URL]: url, + [ActionsEnvVars.GITHUB_API_URL]: apiUrl, + }); + const instance = github.getCurrentInstance(env); + + t.is(instance.url, url); + t.is(instance.apiURL, apiUrl); +}); + +test("getCurrentInstance constructs dotcom instance with dotcom env vars", (t) => { + const env = getTestEnv({ + [ActionsEnvVars.GITHUB_SERVER_URL]: github.GITHUB_DOTCOM_URL, + [ActionsEnvVars.GITHUB_API_URL]: github.GITHUB_DOTCOM_API_URL, + }); + const instance = github.getCurrentInstance(env); + const dotcomInstance = github.getDotcomInstance(); + + t.deepEqual(dotcomInstance, instance); +}); diff --git a/src/github.ts b/src/github.ts index 00d2f3435..8a5a2c389 100644 --- a/src/github.ts +++ b/src/github.ts @@ -60,3 +60,19 @@ export function parseGitHubUrl(inputUrl: string): string { return url.toString(); } + +/** Retrieves a {@link GitHubInstance} describing the instance we are running on. */ +export function getCurrentInstance(env: ReadOnlyEnv): GitHubInstance { + return { + url: env.getRequired(ActionsEnvVars.GITHUB_SERVER_URL), + apiURL: env.getRequired(ActionsEnvVars.GITHUB_API_URL), + }; +} + +/** Retrieves a {@link GitHubInstance} describing the GitHub.com instance. */ +export function getDotcomInstance(): GitHubInstance { + return { + url: GITHUB_DOTCOM_URL, + apiURL: GITHUB_DOTCOM_API_URL, + }; +}