Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 5 additions & 11 deletions apps/cli/src/commands/update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ describe("update command", () => {
let errorSpy: ReturnType<typeof vi.spyOn>;

beforeEach(() => {
vi.clearAllMocks();
program = new Command();
program.exitOverride(); // throw instead of process.exit
registerUpdateCommand(program);
Expand Down Expand Up @@ -115,19 +116,12 @@ describe("update command", () => {
);
});

it("proceeds with update when version check fails", async () => {
it("does not bypass release selection when no stable version is found", async () => {
mockedFetchLatestVersion.mockResolvedValue(undefined);

await program.parseAsync(["node", "scope", "update"]);

expect(mockedExecSync).toHaveBeenCalledWith(
expect.stringContaining("gh release list --repo microsoft/scope"),
expect.anything(),
);
expect(mockedExecSync).toHaveBeenCalledWith(
expect.stringContaining('gh release download "cli/v0.3.0" --repo microsoft/scope'),
expect.anything(),
);
await expect(program.parseAsync(["node", "scope", "update"])).rejects.toThrow("process.exit");
expect(mockedExecSync).not.toHaveBeenCalled();
expect(errorSpy).toHaveBeenCalledWith("Could not determine the latest CLI release tag.");
});

it("rejects update in dev mode", async () => {
Expand Down
10 changes: 0 additions & 10 deletions apps/cli/src/commands/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,6 @@ export function registerUpdateCommand(program: Command): void {
}
targetTag = latest ? `cli/v${latest}` : undefined;

if (!targetTag) {
// Resolve tag via gh release list
try {
targetTag = execSync(
`gh release list --repo ${RELEASES_REPO} --json tagName -q '[.[].tagName | select(startswith("cli/v"))][0]'`,
{ encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] },
).trim();
} catch { /* ignore */ }
}

if (!targetTag) {
console.error("Could not determine the latest CLI release tag.");
process.exit(1);
Expand Down
24 changes: 20 additions & 4 deletions apps/cli/src/utils/update-check.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,15 +175,31 @@ describe("update-check (via bundle)", () => {
}
});

it("handles pre-release versions correctly", async () => {
it("does not offer a prerelease as a stable update", async () => {
releaseResponse = { status: 200, body: [{ tag_name: "cli/v2.0.0-beta.1" }] };
await startServers();
const tempDir = mkdtempSync(join(tmpdir(), "scope-uc-"));
try {
const { stderr } = await runBundle(["run", "list"], tempDir);
// 2.0.0-beta.1 > 0.0.0-dev in semver
expect(stderr).toContain("2.0.0-beta.1");
expect(stderr).toContain("scope update");
expect(stderr).not.toContain("newer version");
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});

it("offers the stable release after newer draft and prerelease entries", async () => {
releaseResponse = { status: 200, body: [
{ tag_name: "cli/v100.0.0", draft: true },
{ tag_name: "cli/v99.0.0", prerelease: true },
{ tag_name: "cli/v98.0.0" },
] };
await startServers();
const tempDir = mkdtempSync(join(tmpdir(), "scope-uc-"));
try {
const { stderr } = await runBundle(["run", "list"], tempDir);
expect(stderr).toContain("newer version of scope is available: 98.0.0");
expect(stderr).not.toContain("99.0.0");
expect(stderr).not.toContain("100.0.0");
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
Expand Down
41 changes: 39 additions & 2 deletions apps/cli/src/utils/update-check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe("public CLI release lookup", () => {
});

it("targets the same public repository through gh when available", async () => {
vi.mocked(execSync).mockReturnValue("cli/v2.0.0\n");
vi.mocked(execSync).mockReturnValue(JSON.stringify([{ tagName: "cli/v2.0.0", isDraft: false, isPrerelease: false }]));
const fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal("fetch", fetchMock);
const { fetchLatestVersion } = await import("./update-check.js");
Expand All @@ -56,10 +56,47 @@ describe("public CLI release lookup", () => {
});

it("returns no version when no CLI release has been published", async () => {
vi.mocked(execSync).mockReturnValue("");
vi.mocked(execSync).mockReturnValue("[]");
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json([{ tag_name: "other/v9.0.0" }]));
vi.stubGlobal("fetch", fetchMock);
const { fetchLatestVersion } = await import("./update-check.js");
expect(await fetchLatestVersion()).toBeUndefined();
});

it("skips drafts, prereleases and invalid tags when choosing a stable release", async () => {
vi.stubEnv("SCOPE_RELEASES_URL", "http://localhost:9999/releases");
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockResolvedValue(Response.json([
{ tag_name: "cli/v9.0.0", draft: true },
{ tag_name: "cli/v8.0.0", prerelease: true },
{ tag_name: "cli/v7.0.0-rc.1" },
{ tag_name: "cli/vinvalid" },
{ tag_name: "cli/v2.0.0", draft: false, prerelease: false },
])));
const { fetchLatestVersion } = await import("./update-check.js");

expect(await fetchLatestVersion()).toBe("2.0.0");
});

it("applies the same stable-release filter to gh results", async () => {
vi.mocked(execSync).mockReturnValue(JSON.stringify([
{ tagName: "cli/v9.0.0", isDraft: true },
{ tagName: "cli/v8.0.0", isPrerelease: true },
{ tagName: "cli/v7.0.0-beta.1" },
{ tagName: "cli/v2.0.0" },
]));
const { fetchLatestVersion } = await import("./update-check.js");

expect(await fetchLatestVersion()).toBe("2.0.0");
});

it("returns no version when only preview releases are available", async () => {
vi.stubEnv("SCOPE_RELEASES_URL", "http://localhost:9999/releases");
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockResolvedValue(Response.json([
{ tag_name: "cli/v2.0.0", prerelease: true },
{ tag_name: "cli/v3.0.0-rc.1" },
])));
const { fetchLatestVersion } = await import("./update-check.js");

expect(await fetchLatestVersion()).toBeUndefined();
});
});
44 changes: 29 additions & 15 deletions apps/cli/src/utils/update-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,30 @@ export const RELEASES_URL =
process.env.SCOPE_RELEASES_URL ||
`https://api.github.com/repos/${RELEASES_REPO}/releases`;

/** Select a published stable CLI version from a GitHub release record. */
function stableReleaseVersion(release: unknown): string | undefined {
if (!release || typeof release !== "object") return undefined;
const record = release as Record<string, unknown>;
if (record.draft || record.prerelease || record.isDraft || record.isPrerelease) return undefined;
const tag = record.tag_name ?? record.tagName;
if (typeof tag !== "string" || !tag.startsWith("cli/v")) return undefined;
const version = tag.slice("cli/v".length);
return semver.valid(version) && !semver.prerelease(version) ? version : undefined;
}

/** Keep GitHub's release ordering, skipping records that are not stable CLI releases. */
function selectStableVersion(data: unknown): string | undefined {
const releases: unknown[] = Array.isArray(data) ? data : [data];
for (const release of releases) {
const version = stableReleaseVersion(release);
if (version) return version;
}
return undefined;
}

/**
* Fetch the latest released CLI version.
* Only considers releases with a `cli/v*` tag prefix.
* Only considers published, stable releases with a valid `cli/v*` tag.
* Uses `gh release list`, falling back to the public REST API.
* Returns the version string (without prefix) or undefined on failure.
* Timeout defaults to 5000ms but can be overridden (background check uses 2000ms).
Expand All @@ -88,13 +109,12 @@ export async function fetchLatestVersion(timeoutMs = 5000): Promise<string | und
if (!process.env.SCOPE_RELEASES_URL) {
// Prefer gh CLI when available; its configured token also avoids anonymous rate limits.
try {
const tag = execSync(
`gh release list --repo ${RELEASES_REPO} --json tagName -q '[.[].tagName | select(startswith("cli/v"))][0]'`,
const output = execSync(
`gh release list --repo ${RELEASES_REPO} --json tagName,isDraft,isPrerelease`,
{ encoding: "utf-8", timeout: timeoutMs, stdio: ["pipe", "pipe", "pipe"] },
).trim();
if (!tag.startsWith("cli/v")) return undefined;
const version = tag.slice("cli/v".length);
if (semver.valid(version)) return version;
);
const releases: unknown = JSON.parse(output);
return selectStableVersion(releases);
} catch {
// gh not available or failed — fall through to REST API
}
Expand Down Expand Up @@ -123,14 +143,8 @@ export async function fetchLatestVersion(timeoutMs = 5000): Promise<string | und

if (!res.ok) return undefined;

const data = (await res.json()) as Array<{ tag_name?: string }> | { tag_name?: string };
// Handle both array (releases list) and single object (test mock compatibility)
const releases = Array.isArray(data) ? data : [data];
const match = releases.find((r) => r.tag_name?.startsWith("cli/v"));
if (!match?.tag_name) return undefined;

const latest = match.tag_name.slice("cli/v".length);
return semver.valid(latest) ? latest : undefined;
const data: unknown = await res.json();
return selectStableVersion(data);
} catch {
return undefined;
} finally {
Expand Down
4 changes: 4 additions & 0 deletions docs/architecture/cli-distribution.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ rerun the public installer without `gh`.
After each command, the CLI performs a non-blocking check for newer versions:

- Checks `cli/v*` releases in `microsoft/scope` (2s per background lookup attempt)
- Both GitHub CLI and REST lookups skip draft, prerelease, and invalid-version
releases, including prerelease versions whose GitHub flag is unset. The
updater uses the same selection and fails without replacing the CLI when no
stable release is available.
- Compares the current embedded version against the latest release tag
- If newer, prints a one-line notice with the upgrade command
- Suppressed by `SCOPE_NO_UPDATE_CHECK=1`
Expand Down
Loading