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
9 changes: 9 additions & 0 deletions .changeset/improve-update-status.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"clerk": patch
---

Fix `clerk update` printing a new spinner line on every frame in terminals wider than 80 columns, and tidy its output.
The spinner now wraps at the real terminal width instead of a fixed 80 columns, and its message no longer includes the install path.
`clerk update` now shows the install path as it appears on `PATH` (for example `/opt/homebrew/bin/clerk`) instead of the version-specific Homebrew Cellar folder that the upgrade removes.
It no longer prints the `hash -r` hint, since every installer it drives upgrades in place behind the same path.
The duplicate "Checking for updates" line and extra blank line before the confirm prompt are gone.
1 change: 0 additions & 1 deletion packages/cli-core/src/commands/update/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ clerk update [options]
5. Runs the installer's global install command (e.g. `npm install -g clerk@<version>`, `bun add -g clerk@<version>`)
6. If any updated target was inside an asdf-managed tool, runs `asdf reshim <plugin>` so the shim picks up the new binary (safety net; modern asdf-nodejs auto-reshims)
7. With `--all`, updates every on-PATH `clerk` install whose owner the CLI can drive. If the primary itself is blocked (e.g. Homebrew on `canary`, or `null` owner), the primary is skipped with a warning and the remaining installs still run; the run only refuses when every target is blocked. Failures on individual installs are recorded in the summary but don't short-circuit the rest.
8. After a successful install, prints a shell-specific `hash -r` / `rehash` hint when applicable

## Primary target selection

Expand Down
67 changes: 24 additions & 43 deletions packages/cli-core/src/commands/update/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export type UpdateOptions = {
type Target = {
/** Path as it appears on PATH (shown to the user). */
displayPath: string;
/** Underlying binary after asdf-shim resolution; equal to displayPath for non-shim targets. */
/** Underlying binary after symlink and asdf-shim resolution. */
resolvedPath: string;
owner: Installer | null;
};
Expand All @@ -52,11 +52,12 @@ async function resolveTargets(
safeRealpath(runningPath),
]);

const resolved = await Promise.all(onPath.map(async (p) => resolveAsdfShim(p)));
const candidates = onPath.map((displayPath, i) => ({
displayPath,
resolvedPath: resolved[i]!,
}));
const candidates = await Promise.all(
onPath.map(async ({ path, real }) => ({
displayPath: path,
resolvedPath: await resolveAsdfShim(real),
})),
);

// Dedupe by resolvedPath: a shim and its resolved target shouldn't both appear.
const seen = new Set<string>();
Expand Down Expand Up @@ -208,23 +209,6 @@ function reportOtherInstalls(others: Target[], channel: string): void {
log.info(`Run ${cyan("clerk update --all")} to update them too.`);
}

/** Hint for invalidating the current shell's command-hash cache after update. */
function hashHint(): string | null {
// Windows native shells (cmd.exe, PowerShell) don't cache command paths.
// On Windows, $SHELL is typically unset, so nothing below would match anyway —
// but return early to be explicit.
if (process.platform === "win32") return null;
const shell = (process.env.SHELL ?? "").toLowerCase();
if (shell.endsWith("/fish") || process.env.FISH_VERSION) return null; // auto-rehashes
// pwsh can run on Linux/macOS via $SHELL=/usr/bin/pwsh; no command-hash cache.
if (shell.endsWith("/pwsh")) return null;
if (shell.endsWith("/tcsh") || shell.endsWith("/csh")) {
return "If `clerk` still points to the old binary, run `rehash` or open a new shell.";
}
// bash, zsh, sh, dash, ksh all support `hash -r`.
return "If `clerk` still points to the old binary, run `hash -r` or open a new shell.";
}

/**
* Detect invocation via a package runner (npx/bunx). The binary lives in a
* runner cache (e.g. `~/.npm/_npx/<hash>/...`) not on PATH, so `ownerOfBinary`
Expand Down Expand Up @@ -270,18 +254,20 @@ export async function update(options: UpdateOptions): Promise<void> {
if (isHuman()) intro("Checking for updates");

const [latest, installDirs] = await Promise.all([
withSpinner("Checking for updates...", async () => fetchLatestVersion(channel)).catch(
(error: unknown) => {
// A registry that answered — badly, or without the requested channel —
// already carries its own code, and a Ctrl-C is the user's decision,
// not the network's. Only transport and timeout failures are genuinely
// "unreachable", and retrying is only right for those.
if (error instanceof CliError || isCancelled(error)) throw error;
throw new CliError("Could not reach npm registry. Check your network connection.", {
code: ERROR_CODE.REGISTRY_UNREACHABLE,
});
},
),
withSpinner(
"Fetching latest version...",
async () => fetchLatestVersion(channel),
"Fetched latest version",
).catch((error: unknown) => {
// A registry that answered — badly, or without the requested channel —
// already carries its own code, and a Ctrl-C is the user's decision,
// not the network's. Only transport and timeout failures are genuinely
// "unreachable", and retrying is only right for those.
if (error instanceof CliError || isCancelled(error)) throw error;
throw new CliError("Could not reach npm registry. Check your network connection.", {
code: ERROR_CODE.REGISTRY_UNREACHABLE,
});
}),
getInstallerPackageDirs(),
]);

Expand All @@ -297,7 +283,6 @@ export async function update(options: UpdateOptions): Promise<void> {
log.info(` Current: ${CURRENT_VERSION}`);
log.info(` Latest: ${cyan(latest)}${formatChannelLabel(channel)}`);
log.info(` Target: ${formatTarget(primary)}`);
log.blank();

// Build the ordered updatable list. Without --all, only the primary counts;
// with --all, include every on-PATH install whose owner we can update.
Expand Down Expand Up @@ -376,7 +361,9 @@ export async function update(options: UpdateOptions): Promise<void> {
const owner = t.owner as Installer;
try {
await withSpinner(
`Installing ${packageSpec} via ${owner} (${t.displayPath})...`,
// Path stays out of the spinner: it's on the Target line already, and
// a long frame that wraps garbles clack's redraw in narrow terminals.
`Installing ${packageSpec} via ${owner}...`,
async () => runGlobalInstall(owner, packageSpec, latest),
`Updated ${owner}: ${t.displayPath}`,
);
Expand Down Expand Up @@ -434,12 +421,6 @@ export async function update(options: UpdateOptions): Promise<void> {
reportOtherInstalls(others, channel);
}

const hint = hashHint();
if (hint) {
log.blank();
log.info(hint);
}

if (isHuman()) {
await outro(anyFailed ? "Update completed with errors" : `Successfully updated to ${latest}`);
}
Expand Down
25 changes: 19 additions & 6 deletions packages/cli-core/src/lib/installer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ describe("findClerkOnPath", () => {
await chmod(bin, 0o755);
process.env.PATH = sandbox;
const found = await findClerkOnPath();
expect(found).toEqual([bin]);
expect(found).toEqual([{ path: bin, real: bin }]);
});

test("skips non-executable files on POSIX", async () => {
Expand Down Expand Up @@ -326,10 +326,10 @@ describe("findClerkOnPath", () => {
await chmod(aBin, 0o755);
await chmod(bBin, 0o755);
process.env.PATH = [dirA, dirB].join(delimiter);
expect(await findClerkOnPath()).toEqual([aBin, bBin]);
expect((await findClerkOnPath()).map((f) => f.path)).toEqual([aBin, bBin]);
// Reversed PATH should reverse the order too.
process.env.PATH = [dirB, dirA].join(delimiter);
expect(await findClerkOnPath()).toEqual([bBin, aBin]);
expect((await findClerkOnPath()).map((f) => f.path)).toEqual([bBin, aBin]);
});

test("dedupes by realpath when two PATH entries resolve to the same file", async () => {
Expand All @@ -343,16 +343,29 @@ describe("findClerkOnPath", () => {
await chmod(bin, 0o755);
process.env.PATH = [real, link].join(delimiter);
const found = await findClerkOnPath();
expect(found.length).toBe(1);
expect(found[0]).toBe(bin);
expect(found).toEqual([{ path: bin, real: bin }]);
});

test("keeps the PATH entry for display while resolving symlinks (Homebrew layout)", async () => {
if (process.platform === "win32") return; // skip symlink test on win32
const cellarBin = join(sandbox, "Cellar", "clerk", "3.4.0", "bin");
const binDir = join(sandbox, "bin");
await mkdir(cellarBin, { recursive: true });
await mkdir(binDir);
const real = join(cellarBin, "clerk");
await writeFile(real, "#!/bin/sh\necho fake");
await chmod(real, 0o755);
await symlink(real, join(binDir, "clerk"));
process.env.PATH = binDir;
expect(await findClerkOnPath()).toEqual([{ path: join(binDir, "clerk"), real }]);
});

test("ignores empty PATH entries (:: as CWD)", async () => {
const bin = join(sandbox, "clerk");
await writeFile(bin, "#!/bin/sh\necho fake");
await chmod(bin, 0o755);
process.env.PATH = `${sandbox}${delimiter}${delimiter}`;
expect(await findClerkOnPath()).toEqual([bin]);
expect(await findClerkOnPath()).toEqual([{ path: bin, real: bin }]);
});
});

Expand Down
18 changes: 10 additions & 8 deletions packages/cli-core/src/lib/installer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,28 +37,30 @@ export function isHomebrewPath(execPath: string): boolean {
// install that owns `process.execPath` rather than the first PATH hit.

/**
* Returns symlink-resolved absolute paths to every `clerk` binary on PATH, in
* PATH order. Duplicates (same realpath reached via two PATH entries) are
* collapsed; first occurrence wins so PATH order is preserved.
* Returns every `clerk` binary on PATH, in PATH order: `path` is the entry as
* the shell sees it (e.g. `/opt/homebrew/bin/clerk`), `real` its
* symlink-resolved target. Duplicates (same realpath reached via two PATH
* entries) are collapsed; first occurrence wins so PATH order is preserved.
*
* Shell-agnostic: reads `process.env.PATH` directly, no `which`/`where`
* subshell. Post-update command-hash invalidation (`hash -r`, `rehash`) is
* the caller's responsibility.
* subshell.
*
* Platform handling:
* POSIX: iterates PATH as-is; filters to regular files with the X bit set.
* Empty PATH entries (`::`) are ignored rather than treated as CWD.
* Windows: iterates PATHEXT in declared order; accepts any regular file
* since NTFS has no X bit.
*/
export async function findClerkOnPath(binaryName = UPDATE_PACKAGE_NAME): Promise<string[]> {
export async function findClerkOnPath(
binaryName = UPDATE_PACKAGE_NAME,
): Promise<Array<{ path: string; real: string }>> {
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
const exts =
process.platform === "win32"
? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean)
: [""];

const resolved: string[] = [];
const resolved: Array<{ path: string; real: string }> = [];
const seen = new Set<string>();
for (const dir of dirs) {
for (const ext of exts) {
Expand All @@ -72,7 +74,7 @@ export async function findClerkOnPath(binaryName = UPDATE_PACKAGE_NAME): Promise
}
if (seen.has(real)) continue;
seen.add(real);
resolved.push(real);
resolved.push({ path: candidate, real });
break; // first matching extension in this dir wins (Windows resolution order)
}
}
Expand Down
50 changes: 33 additions & 17 deletions packages/cli-core/src/lib/spinner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ interface SpinnerCall {
message?: string;
}
let spinnerCalls: SpinnerCall[] = [];
let lastSpinnerOutput: { columns?: number } | undefined;

mock.module("@clack/prompts", () => ({
intro: (title?: string) => {
Expand All @@ -23,23 +24,26 @@ mock.module("@clack/prompts", () => ({
outroCalls++;
lastOutroLabel = label;
},
spinner: () => ({
start: (message: string) => {
spinnerCalls.push({ type: "start", message });
},
stop: (message?: string) => {
spinnerCalls.push({ type: "stop", message });
},
message: (message?: string) => {
spinnerCalls.push({ type: "message", message });
},
clear: () => {
spinnerCalls.push({ type: "clear" });
},
error: (message?: string) => {
spinnerCalls.push({ type: "error", message });
},
}),
spinner: (opts?: { output?: { columns?: number } }) => {
lastSpinnerOutput = opts?.output;
return {
start: (message: string) => {
spinnerCalls.push({ type: "start", message });
},
stop: (message?: string) => {
spinnerCalls.push({ type: "stop", message });
},
message: (message?: string) => {
spinnerCalls.push({ type: "message", message });
},
clear: () => {
spinnerCalls.push({ type: "clear" });
},
error: (message?: string) => {
spinnerCalls.push({ type: "error", message });
},
};
},
// Stubs for sibling test-process exports
cancel: () => {},
log: { info: () => {}, warn: () => {}, error: () => {}, success: () => {} },
Expand Down Expand Up @@ -235,6 +239,18 @@ test("withSpinner starts, runs fn, and stops with success message", async () =>
expect(spinnerCalls[1]?.message).toBe("Loading");
});

test("spinner output reports the real stderr width so clack wraps frames correctly", async () => {
const saved = Object.getOwnPropertyDescriptor(process.stderr, "columns");
Object.defineProperty(process.stderr, "columns", { value: 173, configurable: true });
try {
await captureStderrAsync(() => withSpinner("Loading...", async () => undefined));
expect(lastSpinnerOutput?.columns).toBe(173);
} finally {
if (saved) Object.defineProperty(process.stderr, "columns", saved);
else delete (process.stderr as { columns?: number }).columns;
}
});

test("withSpinner uses an explicit doneMessage when provided", async () => {
await captureStderrAsync(() => withSpinner("Fetching...", async () => undefined, "Fetched"));

Expand Down
6 changes: 6 additions & 0 deletions packages/cli-core/src/lib/spinner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ const logUiOutput = new Writable({
callback();
},
});
// Clack wraps spinner frames at `output.columns`, defaulting to 80 when it's
// missing. Wrapping at 80 in a wider terminal breaks its redraw: it sizes the
// erase from the bare message but draws "◒ " + message + up to 3 dots, so a
// message within 6 columns of the width wraps and frames leave their first
// line behind.
Object.defineProperty(logUiOutput, "columns", { get: () => process.stderr.columns });

function getOutput() {
return getUiOutput() ?? logUiOutput;
Expand Down
Loading