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

Use node parseArgs instead of yargs-parser and arg #11645

Merged
merged 10 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions .changeset/fifty-stingrays-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'astro': patch
'@astrojs/db': patch
---

Refactors internally to use `node:util` `parseArgs` instead of `yargs-parser`
7 changes: 7 additions & 0 deletions .changeset/rude-queens-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'create-astro': patch
'@astrojs/upgrade': patch
---

Refactors internally to use `node:util` `parseArgs` instead of `arg`

2 changes: 0 additions & 2 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,6 @@
"vite": "^5.4.0",
"vitefu": "^0.2.5",
"which-pm": "^3.0.0",
"yargs-parser": "^21.1.1",
"zod": "^3.23.8",
"zod-to-json-schema": "^3.23.2"
},
Expand All @@ -206,7 +205,6 @@
"@types/js-yaml": "^4.0.9",
"@types/prompts": "^2.4.9",
"@types/semver": "^7.5.8",
"@types/yargs-parser": "^21.0.3",
"astro-scripts": "workspace:*",
"cheerio": "1.0.0",
"eol": "^0.9.1",
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/performance/content-benchmark.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable no-console */

import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { bold, cyan, dim } from 'kleur/colors';
import yargs from 'yargs-parser';
import { loadFixture } from '../test/test-utils.js';
import { generatePosts } from './scripts/generate-posts.mjs';

Expand Down Expand Up @@ -40,7 +40,7 @@ async function benchmark({ fixtures, templates, numPosts }) {
// Test the build performance for content collections across multiple file types (md, mdx, mdoc)
(async function benchmarkAll() {
try {
const flags = yargs(process.argv.slice(2));
const { values: flags } = parseArgs({ strict: false });
const test = Array.isArray(flags.test)
? flags.test
: typeof flags.test === 'string'
Expand Down
4 changes: 1 addition & 3 deletions packages/astro/performance/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
"author": "",
"license": "ISC",
"devDependencies": {
"@types/yargs-parser": "^21.0.3",
"kleur": "^4.1.5",
"yargs-parser": "^21.1.1"
"kleur": "^4.1.5"
}
}
19 changes: 9 additions & 10 deletions packages/astro/src/cli/add/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import ora from 'ora';
import preferredPM from 'preferred-pm';
import prompts from 'prompts';
import maxSatisfying from 'semver/ranges/max-satisfying.js';
import type yargs from 'yargs-parser';
import {
loadTSConfig,
resolveConfig,
Expand All @@ -29,14 +28,14 @@ import { appendForwardSlash } from '../../core/path.js';
import { apply as applyPolyfill } from '../../core/polyfill.js';
import { ensureProcessNodeEnv, parseNpmName } from '../../core/util.js';
import { eventCliSession, telemetry } from '../../events/index.js';
import { createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js';
import { type Flags, createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js';
import { fetchPackageJson, fetchPackageVersions } from '../install-package.js';
import { generate, parse, t, visit } from './babel.js';
import { ensureImport } from './imports.js';
import { wrapDefaultExport } from './wrapper.js';

interface AddOptions {
flags: yargs.Arguments;
flags: Flags;
}

interface IntegrationInfo {
Expand Down Expand Up @@ -143,7 +142,7 @@ export async function add(names: string[], { flags }: AddOptions) {
}

// Some packages might have a common alias! We normalize those here.
const cwd = flags.root;
const cwd = inlineConfig.root;
const logger = createLoggerFromFlags(flags);
const integrationNames = names.map((name) => (ALIASES.has(name) ? ALIASES.get(name)! : name));
const integrations = await validateIntegrations(integrationNames);
Expand Down Expand Up @@ -249,7 +248,7 @@ export async function add(names: string[], { flags }: AddOptions) {

const rawConfigPath = await resolveConfigPath({
root: rootPath,
configFile: flags.config,
configFile: inlineConfig.configFile,
fs: fsMod,
});
let configURL = rawConfigPath ? pathToFileURL(rawConfigPath) : undefined;
Expand Down Expand Up @@ -580,7 +579,7 @@ async function updateAstroConfig({
}: {
configURL: URL;
ast: t.File;
flags: yargs.Arguments;
flags: Flags;
logger: Logger;
logAdapterInstructions: boolean;
}): Promise<UpdateResult> {
Expand Down Expand Up @@ -717,7 +716,7 @@ async function tryToInstallIntegrations({
}: {
integrations: IntegrationInfo[];
cwd?: string;
flags: yargs.Arguments;
flags: Flags;
logger: Logger;
}): Promise<UpdateResult> {
const installCommand = await getInstallIntegrationsCommand({ integrations, cwd, logger });
Expand Down Expand Up @@ -893,7 +892,7 @@ async function updateTSConfig(
cwd = process.cwd(),
logger: Logger,
integrationsInfo: IntegrationInfo[],
flags: yargs.Arguments,
flags: Flags,
): Promise<UpdateResult> {
const integrations = integrationsInfo.map(
(integration) => integration.id as frameworkWithTSSettings,
Expand Down Expand Up @@ -996,7 +995,7 @@ function parseIntegrationName(spec: string) {
return { scope, name, tag };
}

async function askToContinue({ flags }: { flags: yargs.Arguments }): Promise<boolean> {
async function askToContinue({ flags }: { flags: Flags }): Promise<boolean> {
if (flags.yes || flags.y) return true;

const response = await prompts({
Expand Down Expand Up @@ -1038,7 +1037,7 @@ function getDiffContent(input: string, output: string): string | null {
async function setupIntegrationConfig(opts: {
root: URL;
logger: Logger;
flags: yargs.Arguments;
flags: Flags;
integrationName: string;
possibleConfigFiles: string[];
defaultConfigFile: string;
Expand Down
7 changes: 3 additions & 4 deletions packages/astro/src/cli/build/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import type yargs from 'yargs-parser';
import _build from '../../core/build/index.js';
import { printHelp } from '../../core/messages.js';
import { flagsToAstroInlineConfig } from '../flags.js';
import { type Flags, flagsToAstroInlineConfig } from '../flags.js';

interface BuildOptions {
flags: yargs.Arguments;
flags: Flags;
}

export async function build({ flags }: BuildOptions) {
Expand All @@ -25,5 +24,5 @@ export async function build({ flags }: BuildOptions) {

const inlineConfig = flagsToAstroInlineConfig(flags);

await _build(inlineConfig, { force: flags.force ?? false });
await _build(inlineConfig, { force: !!flags.force });
}
10 changes: 6 additions & 4 deletions packages/astro/src/cli/check/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import path from 'node:path';
import type { Arguments } from 'yargs-parser';
import { ensureProcessNodeEnv } from '../../core/util.js';
import { createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js';
import { type Flags, createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js';
import { getPackage } from '../install-package.js';

export async function check(flags: Arguments) {
export async function check(flags: Flags) {
ensureProcessNodeEnv('production');
const logger = createLoggerFromFlags(flags);
const getPackageOpts = { skipAsk: flags.yes || flags.y, cwd: flags.root };
const getPackageOpts = {
skipAsk: !!flags.yes || !!flags.y,
cwd: typeof flags.root == 'string' ? flags.root : undefined,
};
const checkPackage = await getPackage<typeof import('@astrojs/check')>(
'@astrojs/check',
logger,
Expand Down
25 changes: 19 additions & 6 deletions packages/astro/src/cli/db/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import type { Arguments } from 'yargs-parser';
import type { AstroConfig } from '../../@types/astro.js';
import { resolveConfig } from '../../core/config/config.js';
import { apply as applyPolyfill } from '../../core/polyfill.js';
import { createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js';
import { type Flags, createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js';
import { getPackage } from '../install-package.js';

interface YargsArguments {
_: Array<string | number>;
'--'?: Array<string | number>;
[argName: string]: any;
}

type DBPackage = {
cli: (args: { flags: Arguments; config: AstroConfig }) => unknown;
cli: (args: { flags: YargsArguments; config: AstroConfig }) => unknown;
};

export async function db({ flags }: { flags: Arguments }) {
export async function db({ positionals, flags }: { positionals: string[]; flags: Flags }) {
applyPolyfill();
const logger = createLoggerFromFlags(flags);
const getPackageOpts = { skipAsk: flags.yes || flags.y, cwd: flags.root };
const getPackageOpts = {
skipAsk: !!flags.yes || !!flags.y,
cwd: typeof flags.root == 'string' ? flags.root : undefined,
};
const dbPackage = await getPackage<DBPackage>('@astrojs/db', logger, getPackageOpts, []);

if (!dbPackage) {
Expand All @@ -27,5 +35,10 @@ export async function db({ flags }: { flags: Arguments }) {
const inlineConfig = flagsToAstroInlineConfig(flags);
const { astroConfig } = await resolveConfig(inlineConfig, 'build');

await cli({ flags, config: astroConfig });
const yargsArgs: YargsArguments = {
_: positionals,
...flags,
};

await cli({ flags: yargsArgs, config: astroConfig });
}
5 changes: 2 additions & 3 deletions packages/astro/src/cli/dev/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { cyan } from 'kleur/colors';
import type yargs from 'yargs-parser';
import devServer from '../../core/dev/index.js';
import { printHelp } from '../../core/messages.js';
import { flagsToAstroInlineConfig } from '../flags.js';
import { type Flags, flagsToAstroInlineConfig } from '../flags.js';

interface DevOptions {
flags: yargs.Arguments;
flags: Flags;
}

export async function dev({ flags }: DevOptions) {
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/cli/docs/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type yargs from 'yargs-parser';
import { printHelp } from '../../core/messages.js';
import type { Flags } from '../flags.js';
import { openInBrowser } from './open.js';

interface DocsOptions {
flags: yargs.Arguments;
flags: Flags;
}

export async function docs({ flags }: DocsOptions) {
Expand Down
7 changes: 5 additions & 2 deletions packages/astro/src/cli/flags.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import type { Arguments as Flags } from 'yargs-parser';
import type { parseArgs } from 'node:util';
import type { AstroInlineConfig } from '../@types/astro.js';
import { type LogOptions, Logger } from '../core/logger/core.js';
import { nodeLogDestination } from '../core/logger/node.js';

export type ParsedArgsResult = ReturnType<typeof parseArgs>;
export type Flags = ParsedArgsResult['values'];

export function flagsToAstroInlineConfig(flags: Flags): AstroInlineConfig {
return {
// Inline-only configs
Expand All @@ -16,7 +19,7 @@ export function flagsToAstroInlineConfig(flags: Flags): AstroInlineConfig {
base: typeof flags.base === 'string' ? flags.base : undefined,
outDir: typeof flags.outDir === 'string' ? flags.outDir : undefined,
server: {
port: typeof flags.port === 'number' ? flags.port : undefined,
port: typeof flags.port === 'string' ? Number(flags.port) : undefined,
host:
typeof flags.host === 'string' || typeof flags.host === 'boolean' ? flags.host : undefined,
open:
Expand Down
39 changes: 26 additions & 13 deletions packages/astro/src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { parseArgs } from 'node:util';
/* eslint-disable no-console */
import * as colors from 'kleur/colors';
import yargs from 'yargs-parser';
import { ASTRO_VERSION } from '../core/constants.js';
import type { ParsedArgsResult } from './flags.js';

type CLICommand =
| 'help'
Expand Down Expand Up @@ -65,9 +66,9 @@ function printVersion() {
}

/** Determine which command the user requested */
function resolveCommand(flags: yargs.Arguments): CLICommand {
const cmd = flags._[2] as string;
if (flags.version) return 'version';
function resolveCommand(args: ParsedArgsResult): CLICommand {
const cmd = args.positionals[2] as string;
if (args.values.version) return 'version';

const supportedCommands = new Set([
'add',
Expand Down Expand Up @@ -97,7 +98,9 @@ function resolveCommand(flags: yargs.Arguments): CLICommand {
* NOTE: This function provides no error handling, so be sure
* to present user-friendly error output where the fn is called.
**/
async function runCommand(cmd: string, flags: yargs.Arguments) {
async function runCommand(cmd: string, args: ParsedArgsResult) {
const flags = args.values;

// These commands can run directly without parsing the user config.
switch (cmd) {
case 'help':
Expand All @@ -120,7 +123,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
// Do not track session start, since the user may be trying to enable,
// disable, or modify telemetry settings.
const { update } = await import('./telemetry/index.js');
const subcommand = flags._[3]?.toString();
const subcommand = args.positionals[3];
await update(subcommand, { flags });
return;
}
Expand All @@ -131,7 +134,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
}
case 'preferences': {
const { preferences } = await import('./preferences/index.js');
const [subcommand, key, value] = flags._.slice(3).map((v) => v.toString());
const [subcommand, key, value] = args.positionals.slice(3);
const exitCode = await preferences(subcommand, key, value, { flags });
return process.exit(exitCode);
}
Expand All @@ -151,7 +154,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
switch (cmd) {
case 'add': {
const { add } = await import('./add/index.js');
const packages = flags._.slice(3) as string[];
const packages = args.positionals.slice(3);
await add(packages, { flags });
return;
}
Expand All @@ -161,7 +164,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
case 'link':
case 'init': {
const { db } = await import('./db/index.js');
await db({ flags });
await db({ positionals: args.positionals, flags });
return;
}
case 'dev': {
Expand Down Expand Up @@ -201,11 +204,21 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
}

/** The primary CLI action */
export async function cli(args: string[]) {
const flags = yargs(args, { boolean: ['global'], alias: { g: 'global' } });
const cmd = resolveCommand(flags);
export async function cli(argv: string[]) {
const args = parseArgs({
args: argv,
allowPositionals: true,
strict: false,
options: {
global: { type: 'boolean', short: 'g' },
host: { type: 'string' }, // Can be boolean too, which is covered by `strict: false`
open: { type: 'string' }, // Can be boolean too, which is covered by `strict: false`
// TODO: Add more flags here
},
});
const cmd = resolveCommand(args);
try {
await runCommand(cmd, flags);
await runCommand(cmd, args);
} catch (err) {
const { throwAndExit } = await import('./throw-and-exit.js');
await throwAndExit(cmd, err);
Expand Down
5 changes: 2 additions & 3 deletions packages/astro/src/cli/info/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@ import { arch, platform } from 'node:os';
/* eslint-disable no-console */
import * as colors from 'kleur/colors';
import prompts from 'prompts';
import type yargs from 'yargs-parser';
import type { AstroConfig, AstroUserConfig } from '../../@types/astro.js';
import { resolveConfig } from '../../core/config/index.js';
import { ASTRO_VERSION } from '../../core/constants.js';
import { apply as applyPolyfill } from '../../core/polyfill.js';
import { flagsToAstroInlineConfig } from '../flags.js';
import { type Flags, flagsToAstroInlineConfig } from '../flags.js';

interface InfoOptions {
flags: yargs.Arguments;
flags: Flags;
}

export async function getInfoOutput({
Expand Down
Loading
Loading