feat(cli): add help flags to various commands (#6394)

Co-authored-by: Happydev <81974850+MoustaphaDev@users.noreply.github.com>
This commit is contained in:
Emanuele Stoppa 2023-03-06 16:58:56 +00:00 committed by GitHub
parent b087b83fe2
commit a4a74ab70c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 128 additions and 19 deletions

View file

@ -0,0 +1,5 @@
---
'astro': minor
---
Add `--help` to various commands: `check`, `sync`, `dev`, `preview`, and `build`

View file

@ -2,7 +2,6 @@
import { AstroCheck, DiagnosticSeverity } from '@astrojs/language-server'; import { AstroCheck, DiagnosticSeverity } from '@astrojs/language-server';
import type { AstroSettings } from '../../@types/astro'; import type { AstroSettings } from '../../@types/astro';
import type { LogOptions } from '../../core/logger/core.js'; import type { LogOptions } from '../../core/logger/core.js';
import glob from 'fast-glob'; import glob from 'fast-glob';
import * as fs from 'fs'; import * as fs from 'fs';
import { bold, dim, red, yellow } from 'kleur/colors'; import { bold, dim, red, yellow } from 'kleur/colors';
@ -10,6 +9,8 @@ import { createRequire } from 'module';
import ora from 'ora'; import ora from 'ora';
import { fileURLToPath, pathToFileURL } from 'url'; import { fileURLToPath, pathToFileURL } from 'url';
import { printDiagnostic } from './print.js'; import { printDiagnostic } from './print.js';
import { Arguments } from 'yargs-parser';
import { printHelp } from '../../core/messages.js';
interface Result { interface Result {
errors: number; errors: number;
@ -18,11 +19,25 @@ interface Result {
hints: number; hints: number;
} }
export async function check(settings: AstroSettings, { logging }: { logging: LogOptions }) { export async function check(
settings: AstroSettings,
{ logging, flags }: { logging: LogOptions; flags: Arguments }
) {
if (flags.help || flags.h) {
printHelp({
commandName: 'astro check',
usage: '[...flags]',
tables: {
Flags: [['--help (-h)', 'See all available flags.']],
},
description: `Runs diagnostics against your project and reports errors to the console.`,
});
return;
}
console.log(bold('astro check')); console.log(bold('astro check'));
const { syncCli } = await import('../../core/sync/index.js'); const { syncCli } = await import('../../core/sync/index.js');
const syncRet = await syncCli(settings, { logging, fs }); const syncRet = await syncCli(settings, { logging, fs, flags });
// early exit on sync failure // early exit on sync failure
if (syncRet === 1) return syncRet; if (syncRet === 1) return syncRet;

View file

@ -75,13 +75,18 @@ async function printVersion() {
/** Determine which command the user requested */ /** Determine which command the user requested */
function resolveCommand(flags: Arguments): CLICommand { function resolveCommand(flags: Arguments): CLICommand {
const cmd = flags._[2] as string; const cmd = flags._[2] as string;
if (cmd === 'add') return 'add';
if (cmd === 'sync') return 'sync';
if (cmd === 'telemetry') return 'telemetry';
if (flags.version) return 'version'; if (flags.version) return 'version';
else if (flags.help) return 'help';
const supportedCommands = new Set(['dev', 'build', 'preview', 'check', 'docs']); const supportedCommands = new Set([
'add',
'sync',
'telemetry',
'dev',
'build',
'preview',
'check',
'docs',
]);
if (supportedCommands.has(cmd)) { if (supportedCommands.has(cmd)) {
return cmd as CLICommand; return cmd as CLICommand;
} }
@ -144,6 +149,16 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
} }
case 'docs': { case 'docs': {
telemetry.record(event.eventCliSession(cmd)); telemetry.record(event.eventCliSession(cmd));
if (flags.help || flags.h) {
printHelp({
commandName: 'astro docs',
tables: {
Flags: [['--help (-h)', 'See all available flags.']],
},
description: `Launches the Astro Docs website directly from the terminal.`,
});
return;
}
return await openInBrowser('https://docs.astro.build/'); return await openInBrowser('https://docs.astro.build/');
} }
case 'telemetry': { case 'telemetry': {
@ -203,26 +218,29 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
case 'build': { case 'build': {
const { default: build } = await import('../core/build/index.js'); const { default: build } = await import('../core/build/index.js');
return await build(settings, { ...flags, logging, telemetry, teardownCompiler: true }); return await build(settings, { flags, logging, telemetry, teardownCompiler: true });
} }
case 'check': { case 'check': {
const ret = await check(settings, { logging }); const ret = await check(settings, { logging, flags });
return process.exit(ret); return process.exit(ret);
} }
case 'sync': { case 'sync': {
const { syncCli } = await import('../core/sync/index.js'); const { syncCli } = await import('../core/sync/index.js');
const ret = await syncCli(settings, { logging, fs }); const ret = await syncCli(settings, { logging, fs, flags });
return process.exit(ret); return process.exit(ret);
} }
case 'preview': { case 'preview': {
const { default: preview } = await import('../core/preview/index.js'); const { default: preview } = await import('../core/preview/index.js');
const server = await preview(settings, { logging, telemetry }); const server = await preview(settings, { logging, telemetry, flags });
return await server.closed(); // keep alive until the server is closed if (server) {
return await server.closed(); // keep alive until the server is closed
}
return;
} }
} }

View file

@ -10,7 +10,7 @@ export interface TelemetryOptions {
export async function update(subcommand: string, { flags, telemetry }: TelemetryOptions) { export async function update(subcommand: string, { flags, telemetry }: TelemetryOptions) {
const isValid = ['enable', 'disable', 'reset'].includes(subcommand); const isValid = ['enable', 'disable', 'reset'].includes(subcommand);
if (flags.help || !isValid) { if (flags.help || flags.h || !isValid) {
msg.printHelp({ msg.printHelp({
commandName: 'astro telemetry', commandName: 'astro telemetry',
usage: '[command]', usage: '[command]',

View file

@ -21,6 +21,8 @@ import { collectPagesData } from './page-data.js';
import { staticBuild, viteBuild } from './static-build.js'; import { staticBuild, viteBuild } from './static-build.js';
import { StaticBuildOptions } from './types.js'; import { StaticBuildOptions } from './types.js';
import { getTimeStat } from './util.js'; import { getTimeStat } from './util.js';
import { printHelp } from '../messages.js';
import yargs from 'yargs-parser';
export interface BuildOptions { export interface BuildOptions {
mode?: RuntimeMode; mode?: RuntimeMode;
@ -31,11 +33,27 @@ export interface BuildOptions {
* building once, but may cause a performance hit if building multiple times in a row. * building once, but may cause a performance hit if building multiple times in a row.
*/ */
teardownCompiler?: boolean; teardownCompiler?: boolean;
flags?: yargs.Arguments;
} }
/** `astro build` */ /** `astro build` */
export default async function build(settings: AstroSettings, options: BuildOptions): Promise<void> { export default async function build(settings: AstroSettings, options: BuildOptions): Promise<void> {
applyPolyfill(); applyPolyfill();
if (options.flags?.help || options.flags?.h) {
printHelp({
commandName: 'astro build',
usage: '[...flags]',
tables: {
Flags: [
['--drafts', `Include Markdown draft pages in the build.`],
['--help (-h)', 'See all available flags.'],
],
},
description: `Builds your site for deployment.`,
});
return;
}
const builder = new AstroBuilder(settings, options); const builder = new AstroBuilder(settings, options);
await builder.run(); await builder.run();
} }

View file

@ -10,11 +10,13 @@ import { info, LogOptions, warn } from '../logger/core.js';
import * as msg from '../messages.js'; import * as msg from '../messages.js';
import { startContainer } from './container.js'; import { startContainer } from './container.js';
import { createContainerWithAutomaticRestart } from './restart.js'; import { createContainerWithAutomaticRestart } from './restart.js';
import { printHelp } from '../messages.js';
import { cyan } from 'kleur/colors';
export interface DevOptions { export interface DevOptions {
configFlag: string | undefined; configFlag: string | undefined;
configFlagPath: string | undefined; configFlagPath: string | undefined;
flags: yargs.Arguments | undefined; flags?: yargs.Arguments;
logging: LogOptions; logging: LogOptions;
telemetry: AstroTelemetry; telemetry: AstroTelemetry;
handleConfigError: (error: Error) => void; handleConfigError: (error: Error) => void;
@ -32,7 +34,26 @@ export interface DevServer {
export default async function dev( export default async function dev(
settings: AstroSettings, settings: AstroSettings,
options: DevOptions options: DevOptions
): Promise<DevServer> { ): Promise<DevServer | undefined> {
if (options.flags?.help || options.flags?.h) {
printHelp({
commandName: 'astro dev',
usage: '[...flags]',
tables: {
Flags: [
['--port', `Specify which port to run on. Defaults to 3000.`],
['--host', `Listen on all addresses, including LAN and public addresses.`],
['--host <custom-address>', `Expose on a network IP address at <custom-address>`],
['--help (-h)', 'See all available flags.'],
],
},
description: `Check ${cyan(
'https://docs.astro.build/en/reference/cli-reference/#astro-dev'
)} for more information.`,
});
return;
}
const devStart = performance.now(); const devStart = performance.now();
await options.telemetry.record([]); await options.telemetry.record([]);

View file

@ -6,17 +6,35 @@ import { runHookConfigDone, runHookConfigSetup } from '../../integrations/index.
import type { LogOptions } from '../logger/core'; import type { LogOptions } from '../logger/core';
import createStaticPreviewServer from './static-preview-server.js'; import createStaticPreviewServer from './static-preview-server.js';
import { getResolvedHostForHttpServer } from './util.js'; import { getResolvedHostForHttpServer } from './util.js';
import type { Arguments } from 'yargs-parser';
import { printHelp } from '../messages.js';
import { cyan } from 'kleur/colors';
interface PreviewOptions { interface PreviewOptions {
logging: LogOptions; logging: LogOptions;
telemetry: AstroTelemetry; telemetry: AstroTelemetry;
flags?: Arguments;
} }
/** The primary dev action */ /** The primary dev action */
export default async function preview( export default async function preview(
_settings: AstroSettings, _settings: AstroSettings,
{ logging }: PreviewOptions { logging, flags }: PreviewOptions
): Promise<PreviewServer> { ): Promise<PreviewServer | undefined> {
if (flags?.help || flags?.h) {
printHelp({
commandName: 'astro preview',
usage: '[...flags]',
tables: {
Flags: [['--help (-h)', 'See all available flags.']],
},
description: `Starts a local server to serve your static dist/ directory. Check ${cyan(
'https://docs.astro.build/en/reference/cli-reference/#astro-preview'
)} for more information.`,
});
return;
}
const settings = await runHookConfigSetup({ const settings = await runHookConfigSetup({
settings: _settings, settings: _settings,
command: 'preview', command: 'preview',

View file

@ -11,13 +11,27 @@ import { getTimeStat } from '../build/util.js';
import { createVite } from '../create-vite.js'; import { createVite } from '../create-vite.js';
import { AstroError, AstroErrorData } from '../errors/index.js'; import { AstroError, AstroErrorData } from '../errors/index.js';
import { info, LogOptions } from '../logger/core.js'; import { info, LogOptions } from '../logger/core.js';
import { printHelp } from '../messages.js';
import { Arguments } from 'yargs-parser';
type ProcessExit = 0 | 1; type ProcessExit = 0 | 1;
export async function syncCli( export async function syncCli(
settings: AstroSettings, settings: AstroSettings,
{ logging, fs }: { logging: LogOptions; fs: typeof fsMod } { logging, fs, flags }: { logging: LogOptions; fs: typeof fsMod; flags?: Arguments }
): Promise<ProcessExit> { ): Promise<ProcessExit> {
if (flags?.help || flags?.h) {
printHelp({
commandName: 'astro sync',
usage: '[...flags]',
tables: {
Flags: [['--help (-h)', 'See all available flags.']],
},
description: `Generates TypeScript types for all Astro modules.`,
});
return 0;
}
const resolvedSettings = await runHookConfigSetup({ const resolvedSettings = await runHookConfigSetup({
settings, settings,
logging, logging,