Skip to content
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

Add CLI shortcuts #9159

Merged
merged 11 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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/old-cherries-beg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'astro': minor
---

Adds CLI shortcuts for the dev server:

- `r + enter`: restarts the dev server
- `o + enter`: opens the site in your browser
- `q + enter`: quits the dev server
26 changes: 22 additions & 4 deletions packages/astro/src/core/dev/restart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export async function createContainerWithAutomaticRestart({
} else {
// Restart success. Add new watches because this is a new container with a new Vite server
restart.container = result;
addWatches();
setupContainer();
resolveRestart(null);
}
restartComplete = new Promise<Error | null>((resolve) => {
Expand All @@ -153,8 +153,8 @@ export async function createContainerWithAutomaticRestart({
};
}

// Set up watches
function addWatches() {
// Set up watchers, vite restart API, and shortcuts
function setupContainer() {
const watcher = restart.container.viteServer.watcher;
watcher.on('change', handleChangeRestart('Configuration file updated.'));
watcher.on('unlink', handleChangeRestart('Configuration file removed.'));
Expand All @@ -163,7 +163,25 @@ export async function createContainerWithAutomaticRestart({
// Restart the Astro dev server instead of Vite's when the API is called by plugins.
// Ignore the `forceOptimize` parameter for now.
restart.container.viteServer.restart = () => handleServerRestart();

// Set up shortcuts, overriding Vite's default shortcuts so it works for Astro
restart.container.viteServer.bindCLIShortcuts({
customShortcuts: [
{
key: 'r',
description: 'restart the server',
action: () => handleServerRestart(),
},
{
key: 'u',
description: 'show server url',
action() {
// TODO: show the server urls
},
},
],
});
}
addWatches();
setupContainer();
return restart;
}
1 change: 1 addition & 0 deletions packages/astro/src/core/logger/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type LoggerLabel =
| 'middleware'
| 'preferences'
| 'redirects'
| 'shortcut'
// SKIP_FORMAT: A special label that tells the logger not to apply any formatting.
// Useful for messages that are already formatted, like the server start message.
| 'SKIP_FORMAT';
Expand Down
17 changes: 15 additions & 2 deletions packages/astro/src/core/logger/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import stripAnsi from 'strip-ansi';
import type { Logger as ViteLogger, Rollup, LogLevel } from 'vite';
import { isAstroError } from '../errors/errors.js';
import { isLogLevelEnabled, type Logger as AstroLogger } from './core.js';
import { serverShortcuts as formatServerShortcuts } from '../messages.js';

const PKG_PREFIX = fileURLToPath(new URL('../../../', import.meta.url));
const E2E_PREFIX = fileURLToPath(new URL('../../../e2e', import.meta.url));
Expand All @@ -16,6 +17,10 @@ const vitePageReloadMsg = /page reload (.*)( \(.*\))?/;
const viteHmrUpdateMsg = /hmr update (.*)/;
// capture "vite v5.0.0 building SSR bundle for production..." and "vite v5.0.0 building for production..." messages
const viteBuildMsg = /vite.*building.*for production/;
// capture "\n Shortcuts" messages
const viteShortcutTitleMsg = /.*Shortcuts.*/s;
// capture "press * + enter to ..." messages
const viteShortcutHelpMsg = /press\s+(.*\+ enter).*to\s+(.*)$/s;

export function createViteLogger(
astroLogger: AstroLogger,
Expand All @@ -42,10 +47,18 @@ export function createViteLogger(
if (isAstroSrcFile(m[1])) return;
astroLogger.info('watch', m[1]);
}
// Don't log Vite build messages
else if (viteBuildMsg.test(stripped)) {
// Don't log Vite build messages and shortcut titles
else if (viteBuildMsg.test(stripped) || viteShortcutTitleMsg.test(stripped)) {
// noop
}
// Log shortcuts help messages without indent
else if (viteShortcutHelpMsg.test(stripped)) {
// Remove Vite's builtin shortcuts we don't support. We can do this cleaner once
// https://github.com/vitejs/vite/pull/15218 lands
if (stripped.includes('c + enter') || stripped.includes('u + enter')) return;
const [, key, label] = viteShortcutHelpMsg.exec(stripped)! as string[];
astroLogger.info('SKIP_FORMAT', formatServerShortcuts({ key, label }));
}
// Fallback
else {
astroLogger.info('vite', msg);
Expand Down
15 changes: 13 additions & 2 deletions packages/astro/src/core/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,7 @@ export function serverStart({
}

const messages = [
'',
`${bgGreen(bold(` astro `))} ${green(`v${version}`)} ${dim(`ready in`)} ${Math.round(
`${bgGreen(bold(black(` astro `)))} ${green(`v${version}`)} ${dim(`ready in`)} ${Math.round(
startupTime
)} ${dim('ms')}`,
'',
Expand All @@ -95,6 +94,18 @@ export function serverStart({
return messages.filter((msg) => typeof msg === 'string').join('\n');
}

/** Display custom dev server shortcuts */
export function serverShortcuts({
key,
label
}: {
key: string,
label: string,
}): string {
return [dim(' Press'), key, dim('to'), label].join(' ');
}


export function telemetryNotice() {
const headline = blue(`▶ Astro collects anonymous usage data.`);
const why = ' This information helps us improve Astro.';
Expand Down