-
Notifications
You must be signed in to change notification settings - Fork 86
Add studio uninstall command for the standalone CLI #3974
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 ); | ||
| } ); | ||
| } ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
|
|
||
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
| ) | ||
| ); | ||
| } | ||
|
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 ) ); | ||
| }, | ||
| } ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.