-
Notifications
You must be signed in to change notification settings - Fork 86
Add update notifier to CLI #3096
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
7 commits
Select commit
Hold shift + click to select a range
79fa700
Add update notifier to CLI
youknowriad 13beb40
Address PR review feedback for update notifier
youknowriad bd59655
Store update check cache in cli.json instead of separate file
youknowriad f9d9e48
Await update notifier and show banner on first run
youknowriad 44614db
Fix lint error: await async setupUpdateNotifier in test
youknowriad fa295fd
Guard against negative rightPad in update banner
youknowriad 0eebd17
Disable update notifier for bundled CLI
youknowriad 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
Some comments aren't visible on the classic Files Changed page.
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| /* eslint-disable no-control-regex */ | ||
| import { type MockInstance, vi } from 'vitest'; | ||
| import { formatUpdateBanner, setupUpdateNotifier } from 'cli/lib/update-notifier'; | ||
|
|
||
| describe( 'formatUpdateBanner', () => { | ||
| it( 'should include version numbers', () => { | ||
| const banner = formatUpdateBanner( '1.7.8', '1.8.0' ); | ||
| const plain = banner.replace( /\u001B\[[0-9;]*m/g, '' ); | ||
| expect( plain ).toContain( '1.7.8' ); | ||
| expect( plain ).toContain( '1.8.0' ); | ||
| } ); | ||
|
|
||
| it( 'should include the changelog URL', () => { | ||
| const banner = formatUpdateBanner( '1.7.8', '1.8.0' ); | ||
| const plain = banner.replace( /\u001B\[[0-9;]*m/g, '' ); | ||
| expect( plain ).toContain( | ||
| 'https://developer.wordpress.com/docs/developer-tools/studio/changelog/' | ||
| ); | ||
| } ); | ||
|
|
||
| it( 'should include the npm update command', () => { | ||
| const banner = formatUpdateBanner( '1.7.8', '1.8.0' ); | ||
| const plain = banner.replace( /\u001B\[[0-9;]*m/g, '' ); | ||
| expect( plain ).toContain( 'npm update -g wp-studio' ); | ||
| } ); | ||
|
|
||
| it( 'should be wrapped in a box', () => { | ||
| const banner = formatUpdateBanner( '1.0.0', '2.0.0' ); | ||
| const plain = banner.replace( /\u001B\[[0-9;]*m/g, '' ); | ||
| expect( plain ).toContain( '╭' ); | ||
| expect( plain ).toContain( '╰' ); | ||
| expect( plain ).toContain( '│' ); | ||
| } ); | ||
| } ); | ||
|
|
||
| describe( 'setupUpdateNotifier', () => { | ||
| const originalSend = process.send; | ||
| let stderrWriteSpy: MockInstance; | ||
|
|
||
| beforeEach( () => { | ||
| stderrWriteSpy = vi.spyOn( process.stderr, 'write' ).mockImplementation( () => true ); | ||
| } ); | ||
|
|
||
| afterEach( () => { | ||
| process.send = originalSend; | ||
| stderrWriteSpy.mockRestore(); | ||
| } ); | ||
|
|
||
| it( 'should not show banner when in IPC mode', async () => { | ||
| process.send = vi.fn(); | ||
| await setupUpdateNotifier( '1.0.0' ); | ||
| expect( stderrWriteSpy ).not.toHaveBeenCalled(); | ||
| } ); | ||
| } ); |
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,147 @@ | ||
| import fs from 'fs'; | ||
| import { getCliConfigPath } from '@studio/common/lib/well-known-paths'; | ||
| import { __, sprintf } from '@wordpress/i18n'; | ||
| import chalk from 'chalk'; | ||
| import semver from 'semver'; | ||
| import { z } from 'zod'; | ||
| import { updateCheckSchema, updateCliConfigWithPartial } from 'cli/lib/cli-config/core'; | ||
|
|
||
| const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours | ||
| const FETCH_TIMEOUT_MS = 3000; | ||
| const NPM_REGISTRY_URL = 'https://registry.npmjs.org/wp-studio/latest'; | ||
| const CHANGELOG_URL = 'https://developer.wordpress.com/docs/developer-tools/studio/changelog/'; | ||
|
|
||
| type UpdateCheck = z.infer< typeof updateCheckSchema >; | ||
|
|
||
| const npmRegistryResponseSchema = z.object( { | ||
| version: z.string(), | ||
| } ); | ||
|
|
||
| /** | ||
| * Reads the updateCheck field from cli.json synchronously. | ||
| * Uses a direct fs.readFileSync + zod parse to avoid the async readCliConfig path, | ||
| * so the banner can be printed before any command output. | ||
| */ | ||
| function readUpdateCheck(): UpdateCheck | null { | ||
| try { | ||
| const content = fs.readFileSync( getCliConfigPath(), 'utf8' ); | ||
| const data = JSON.parse( content ); | ||
| return updateCheckSchema.parse( data?.updateCheck ); | ||
| } catch { | ||
| // File doesn't exist, field missing, or invalid | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| async function fetchLatestVersion(): Promise< string | null > { | ||
| try { | ||
| const controller = new AbortController(); | ||
| const timeout = setTimeout( () => controller.abort(), FETCH_TIMEOUT_MS ); | ||
|
|
||
| const response = await fetch( NPM_REGISTRY_URL, { | ||
| signal: controller.signal, | ||
| headers: { Accept: 'application/json' }, | ||
| } ); | ||
| clearTimeout( timeout ); | ||
|
|
||
| if ( ! response.ok ) { | ||
| return null; | ||
| } | ||
|
|
||
| const data = npmRegistryResponseSchema.parse( await response.json() ); | ||
| return data.version; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| function hasJsonFlag(): boolean { | ||
| return process.argv.includes( '--json' ); | ||
| } | ||
|
|
||
| /** | ||
| * Checks for available updates and displays a banner at the top of output. | ||
| * | ||
| * Reads the updateCheck field from cli.json synchronously so the banner prints | ||
| * immediately, before any command output. If the cache is stale or missing, | ||
| * fetches the latest version from the npm registry and saves it to cli.json. | ||
| * | ||
| * The banner is suppressed in IPC mode or when --json flag is used. | ||
| */ | ||
| export async function setupUpdateNotifier( currentVersion: string ): Promise< void > { | ||
| if ( ! __IS_PACKAGED_FOR_NPM__ || Boolean( process.send ) || hasJsonFlag() ) { | ||
| return; | ||
| } | ||
|
|
||
| const updateCheck = readUpdateCheck(); | ||
| const now = Date.now(); | ||
|
|
||
| // Fetch and cache if stale or missing (up to FETCH_TIMEOUT_MS) | ||
| if ( ! updateCheck || now - updateCheck.lastChecked >= UPDATE_CHECK_INTERVAL_MS ) { | ||
| const version = await fetchLatestVersion(); | ||
| if ( version ) { | ||
| try { | ||
| await updateCliConfigWithPartial( { | ||
| updateCheck: { lastChecked: now, latestVersion: version }, | ||
| } ); | ||
| } catch { | ||
| // Non-critical, ignore write failures | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Read again in case we just updated the cache on the first run | ||
| const latestCheck = readUpdateCheck(); | ||
|
|
||
| if ( | ||
| latestCheck && | ||
| semver.valid( latestCheck.latestVersion ) && | ||
| semver.valid( currentVersion ) && | ||
| semver.gt( latestCheck.latestVersion, currentVersion ) | ||
| ) { | ||
| process.stderr.write( formatUpdateBanner( currentVersion, latestCheck.latestVersion ) ); | ||
| } | ||
| } | ||
|
|
||
| export function formatUpdateBanner( currentVersion: string, latestVersion: string ): string { | ||
| const updateLine = sprintf( | ||
| /* translators: 1: current version, 2: latest version */ | ||
| __( 'Update available: %1$s → %2$s' ), | ||
| chalk.dim( currentVersion ), | ||
| chalk.green( latestVersion ) | ||
| ); | ||
|
|
||
| const commandLine = sprintf( | ||
| /* translators: %s is the npm command to run */ | ||
| __( 'Run %s to update' ), | ||
| chalk.cyan( 'npm update -g wp-studio' ) | ||
| ); | ||
|
|
||
| const changelogLine = sprintf( | ||
| /* translators: %s is the changelog URL */ | ||
| __( 'Changelog: %s' ), | ||
| chalk.cyan( CHANGELOG_URL ) | ||
| ); | ||
|
|
||
| const lines = [ '', updateLine, commandLine, '', changelogLine, '' ]; | ||
|
|
||
| // Calculate box width based on longest line (strip ANSI for measurement) | ||
| // eslint-disable-next-line no-control-regex | ||
| const ansiPattern = new RegExp( '\u001B\\[[0-9;]*m', 'g' ); | ||
| const stripAnsi = ( str: string ) => str.replace( ansiPattern, '' ); | ||
| const maxLen = Math.max( ...lines.map( ( l ) => stripAnsi( l ).length ) ); | ||
| const padding = 2; | ||
| const innerWidth = maxLen + padding * 2; | ||
|
|
||
| const top = chalk.yellow( `╭${ '─'.repeat( innerWidth ) }╮` ); | ||
| const bottom = chalk.yellow( `╰${ '─'.repeat( innerWidth ) }╯` ); | ||
| const side = chalk.yellow( '│' ); | ||
|
|
||
| const paddedLines = lines.map( ( line ) => { | ||
| const visibleLen = stripAnsi( line ).length; | ||
| const rightPad = Math.max( 0, innerWidth - padding - visibleLen ); | ||
| return `${ side }${ ' '.repeat( padding ) }${ line }${ ' '.repeat( rightPad ) }${ side }`; | ||
| } ); | ||
|
|
||
| return [ '', top, ...paddedLines, bottom, '' ].join( '\n' ); | ||
| } | ||
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
Oops, something went wrong.
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.