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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions apps/cli/commands/tests/uninstall.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import trash from 'trash';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getCliInstallKind } from 'cli/lib/update-notifier';
import { runCommand } from '../uninstall';

vi.mock( 'trash' );

vi.mock( 'cli/lib/update-notifier', async ( importOriginal ) => ( {
...( await importOriginal< typeof import('cli/lib/update-notifier') >() ),
getCliInstallKind: vi.fn(),
} ) );

vi.mock( 'cli/commands/site/stop', async ( importOriginal ) => ( {
...( await importOriginal< typeof import('../site/stop') >() ),
runCommand: vi.fn().mockResolvedValue( undefined ),
} ) );

describe( 'CLI: studio uninstall', () => {
let root: string;
let installDir: string;
let configDir: string;
const originalExecPath = process.execPath;
const originalPlatform = process.platform;

const setPlatform = ( value: NodeJS.Platform ) =>
Object.defineProperty( process, 'platform', { value, configurable: true } );

beforeEach( () => {
root = fs.mkdtempSync( path.join( os.tmpdir(), 'studio-uninstall-' ) );
installDir = path.join( root, '.studio' );
configDir = path.join( root, 'config' );

fs.mkdirSync( path.join( installDir, 'bin' ), { recursive: true } );
fs.mkdirSync( path.join( installDir, 'cli' ), { recursive: true } );
fs.writeFileSync( path.join( installDir, 'bin', 'node' ), '' );
fs.mkdirSync( configDir, { recursive: true } );
fs.writeFileSync( path.join( configDir, 'cli.json' ), '{}' );

// The launcher runs `<installDir>/bin/node`, so this is how the command
// locates the bundle to remove.
Object.defineProperty( process, 'execPath', {
value: path.join( installDir, 'bin', 'node' ),
configurable: true,
} );
process.env.DEV_CONFIG_DIR = configDir;
// Pin to a POSIX platform so the in-process removal path is exercised
// deterministically (on Windows the runner defers deletion to a helper).
setPlatform( 'linux' );
vi.spyOn( console, 'log' ).mockImplementation( () => undefined );
vi.mocked( getCliInstallKind ).mockReturnValue( 'standalone' );
} );

afterEach( () => {
Object.defineProperty( process, 'execPath', {
value: originalExecPath,
configurable: true,
} );
setPlatform( originalPlatform );
delete process.env.DEV_CONFIG_DIR;
process.exitCode = 0;
fs.rmSync( root, { recursive: true, force: true } );
vi.restoreAllMocks();
} );

it( 'removes the bundle dirs but keeps user config by default', async () => {
await runCommand( false );

expect( fs.existsSync( path.join( installDir, 'bin' ) ) ).toBe( false );
expect( fs.existsSync( path.join( installDir, 'cli' ) ) ).toBe( false );
expect( fs.existsSync( configDir ) ).toBe( true );
} );

it( 'trashes user config when --purge is passed non-interactively', async () => {
Object.defineProperty( process.stdin, 'isTTY', { value: false, configurable: true } );

await runCommand( true );

expect( fs.existsSync( path.join( installDir, 'cli' ) ) ).toBe( false );
expect( trash ).toHaveBeenCalledWith( configDir );
} );

it( 'does nothing destructive for non-standalone installs', async () => {
vi.mocked( getCliInstallKind ).mockReturnValue( 'npm' );

await runCommand( true );

expect( fs.existsSync( path.join( installDir, 'bin' ) ) ).toBe( true );
expect( trash ).not.toHaveBeenCalled();
expect( process.exitCode ).toBe( 1 );
} );
} );
175 changes: 175 additions & 0 deletions apps/cli/commands/uninstall.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { confirm } from '@inquirer/prompts';
import { getConfigDirectory } from '@studio/common/lib/well-known-paths';
import { __, sprintf } from '@wordpress/i18n';
import trash from 'trash';
import { Mode, runCommand as stopSites } from 'cli/commands/site/stop';
import { getCliInstallKind } from 'cli/lib/update-notifier';
import { StudioArgv } from 'cli/types';

// The launcher execs `<installDir>/bin/node`, so the running binary's grandparent
// is the standalone install root (handles a STUDIO_CLI_HOME override too — no need
// to assume ~/.studio).
function getInstallDir(): string {
return path.dirname( path.dirname( process.execPath ) );
}

// Remove the `~/.local/bin/studio` PATH symlink, but only if it still points at
// the bundle we're removing. The shared `export PATH=…/.local/bin` rc line is left
// alone — the desktop app relies on it too.
function removePosixSymlink( installDir: string ): string | null {
const symlink = path.join( os.homedir(), '.local', 'bin', 'studio' );
try {
if ( ! fs.lstatSync( symlink ).isSymbolicLink() ) {
return null;
}
const target = path.resolve( path.dirname( symlink ), fs.readlinkSync( symlink ) );
if ( target !== path.join( installDir, 'bin', 'studio' ) ) {
return null;
}
fs.unlinkSync( symlink );
return symlink;
} catch {
return null;
}
}

// Windows locks bin\node.exe while the CLI runs, so we can't delete our own
// runtime in-process. Hand the destructive work to a detached PowerShell helper
// that waits for this PID to exit, then removes the bundle dirs and strips the
// installer's PATH registry entry (mirroring install.ps1's raw-registry write).
function scheduleWindowsCleanup( installDir: string ): void {
const q = ( p: string ) => p.replace( /'/g, "''" );
const binDir = path.join( installDir, 'bin' );
const script = `
$ErrorActionPreference = 'SilentlyContinue'
while (Get-Process -Id ${
process.pid
} -ErrorAction SilentlyContinue) { Start-Sleep -Milliseconds 200 }
Remove-Item -LiteralPath '${ q( binDir ) }' -Recurse -Force
Remove-Item -LiteralPath '${ q( path.join( installDir, 'cli' ) ) }' -Recurse -Force
Remove-Item -LiteralPath '${ q( installDir ) }' -Force
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
if ($key) {
$raw = [string]$key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
$parts = $raw -split ';' | Where-Object { $_ -ne '' -and $_ -ne '${ q( binDir ) }' }
[Environment]::SetEnvironmentVariable('PATH', ($parts -join ';'), 'User')
$key.Close()
}
`;
spawn(
'powershell.exe',
[ '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script ],
{ detached: true, stdio: 'ignore', windowsHide: true }
).unref();
}

export async function runCommand( purge: boolean ): Promise< void > {
const installKind = getCliInstallKind();

if ( installKind === 'npm' ) {
console.log(
__( 'This Studio CLI was installed via npm. Remove it with: npm rm -g wp-studio' )
);
process.exitCode = 1;
return;
}
if ( installKind !== 'standalone' ) {
console.log(
__(
'This Studio CLI is bundled with the Studio desktop app. Uninstall the app to remove it.'
)
);
process.exitCode = 1;
return;
}
Comment thread
bcotrim marked this conversation as resolved.

const installDir = getInstallDir();

// Stop running sites + the daemon first so nothing holds open handles on the
// runtime we're about to delete (mandatory on Windows; tidy on POSIX).
try {
await stopSites( Mode.STOP_ALL_SITES, undefined );
} catch {
// Best-effort — a broken/already-stopped install shouldn't block uninstall.
}

const configDir = getConfigDirectory();
let removeConfig = purge;
if ( purge && process.stdin.isTTY ) {
removeConfig = await confirm( {
message: sprintf(
/* translators: %s is the config directory path */
__( 'Delete your Studio config in %s?' ),
configDir
),
default: false,
} );
}

const removed: string[] = [];

if ( process.platform === 'win32' ) {
// PATH entry + runtime dirs are removed by the detached helper after exit.
scheduleWindowsCleanup( installDir );
removed.push( path.join( installDir, 'bin' ), path.join( installDir, 'cli' ) );
} else {
for ( const dir of [ path.join( installDir, 'bin' ), path.join( installDir, 'cli' ) ] ) {
fs.rmSync( dir, { recursive: true, force: true } );
removed.push( dir );
}
const symlink = removePosixSymlink( installDir );
if ( symlink ) {
removed.push( symlink );
}
}

if ( removeConfig ) {
// Trash rather than hard-delete — the user's sites/config are recoverable if they
// change their mind.
await trash( configDir );
removed.push( configDir );
}
Comment on lines +130 to +135

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's trash it instead.


console.log( __( 'Studio CLI uninstalled. Removed:' ) );
for ( const item of removed ) {
console.log( ` ${ item }` );
}
if ( ! removeConfig ) {
console.log(
sprintf(
/* translators: %s is the config directory path */
__( '\nYour Studio config and sites are still in %s.' ),
configDir
)
);
}
Comment thread
bcotrim marked this conversation as resolved.
if ( process.platform === 'win32' ) {
console.log( __( '\nThe runtime and PATH entry are removed once this process exits.' ) );
} else {
console.log(
__( '\nThe ".local/bin" PATH line in your shell profile was left for the desktop app.' )
);
}
}

export const registerCommand = ( yargs: StudioArgv ) => {
return yargs.command( {
command: 'uninstall',
describe: __( 'Uninstall the standalone Studio CLI' ),
builder: ( yargs ) => {
return yargs.option( 'purge', {
type: 'boolean',
alias: 'all',
describe: __( 'Also delete your Studio config (~/.studio)' ),
default: false,
} );
},
handler: async ( argv ) => {
await runCommand( Boolean( argv.purge ) );
},
} );
};
3 changes: 3 additions & 0 deletions apps/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { registerCommand as registerSiteListCommand } from 'cli/commands/site/li
import { registerCommand as registerSiteStartCommand } from 'cli/commands/site/start';
import { registerCommand as registerSiteStatusCommand } from 'cli/commands/site/status';
import { registerCommand as registerSiteStopCommand } from 'cli/commands/site/stop';
import { registerCommand as registerUninstallCommand } from 'cli/commands/uninstall';
import {
bumpAggregatedUniqueStat,
bumpStat,
Expand Down Expand Up @@ -215,6 +216,8 @@ async function main() {
registerImportCommand( studioArgv );
registerExportCommand( studioArgv );

registerUninstallCommand( studioArgv );

studioArgv.command( 'preview', __( 'Manage preview sites' ), async ( previewYargs ) => {
const [
{ registerCommand: registerPreviewCreateCommand },
Expand Down
36 changes: 36 additions & 0 deletions apps/cli/lib/tests/update-notifier.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-control-regex */
import { type MockInstance, vi } from 'vitest';
import { readCliConfig } from 'cli/lib/cli-config/core';
import {
formatUpdateBanner,
setupUpdateNotifier,
Expand Down Expand Up @@ -214,5 +215,40 @@ describe( 'setupUpdateNotifier', () => {
await expect( setupUpdateNotifier( '1.0.0', 'standalone' ) ).resolves.toBeUndefined();
expect( stderrWriteSpy ).not.toHaveBeenCalled();
} );

it( 'refetches instead of trusting a fresh cache from a different channel', async () => {
// Nightly cache left in the shared ~/.studio by a prior install; the running CLI is
// production. The stale 1.12.0-dev131 must not be offered — we refetch (server: 204).
vi.mocked( readCliConfig ).mockResolvedValueOnce( {
standaloneUpdateCheck: { lastChecked: Date.now(), latestVersion: '1.12.0-dev131' },
} as never );
const fetchMock = vi.fn().mockResolvedValue( {
ok: true,
status: 204,
json: async () => ( {} ),
} );
vi.stubGlobal( 'fetch', fetchMock );

await setupUpdateNotifier( '1.11.0', 'standalone' );

expect( fetchMock ).toHaveBeenCalled();
expect( stderrWriteSpy ).not.toHaveBeenCalled();
} );

it( 'trusts a fresh same-channel cache without re-fetching', async () => {
vi.mocked( readCliConfig ).mockResolvedValueOnce( {
standaloneUpdateCheck: { lastChecked: Date.now(), latestVersion: '1.13.0' },
} as never );
const fetchMock = vi.fn();
vi.stubGlobal( 'fetch', fetchMock );

await setupUpdateNotifier( '1.11.0', 'standalone' );

expect( fetchMock ).not.toHaveBeenCalled();
const output = stripAnsi(
stderrWriteSpy.mock.calls.map( ( call ) => String( call[ 0 ] ) ).join( '' )
);
expect( output ).toContain( '1.13.0' );
} );
} );
} );
8 changes: 7 additions & 1 deletion apps/cli/lib/update-notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,13 @@ async function notifyStandalone( currentVersion: string ): Promise< void > {

let latestVersion: string | null = null;

if ( cached && now - cached.lastChecked < UPDATE_CHECK_INTERVAL_MS ) {
// ~/.studio is shared across installs, so a cache left by a different channel (e.g. a
// prior nightly) must not be trusted for this one — refetch on a channel mismatch.
if (
cached &&
now - cached.lastChecked < UPDATE_CHECK_INTERVAL_MS &&
channelForVersion( cached.latestVersion ) === channelForVersion( currentVersion )
) {
latestVersion = cached.latestVersion;
} else {
const result = await fetchStandaloneUpdate( currentVersion );
Expand Down