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

Revert parseArgs change #11733

Merged
merged 2 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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/famous-dolls-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'create-astro': patch
'@astrojs/db': patch
---

Reverts back to `arg` package for CLI argument parsing
6 changes: 6 additions & 0 deletions .changeset/wild-trainers-matter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'astro': patch
'@astrojs/db': patch
---

Reverts back to `yargs-parser` package for CLI argument parsing
2 changes: 1 addition & 1 deletion packages/astro/src/cli/check/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export async function check(flags: Flags) {
const logger = createLoggerFromFlags(flags);
const getPackageOpts = {
skipAsk: !!flags.yes || !!flags.y,
cwd: typeof flags.root == 'string' ? flags.root : undefined,
cwd: flags.root,
};
const checkPackage = await getPackage<typeof import('@astrojs/check')>(
'@astrojs/check',
Expand Down
22 changes: 6 additions & 16 deletions packages/astro/src/cli/db/index.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
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 { type Flags, createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js';
import { 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: YargsArguments; config: AstroConfig }) => unknown;
cli: (args: { flags: Arguments; config: AstroConfig }) => unknown;
};

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

Expand All @@ -35,10 +30,5 @@ export async function db({ positionals, flags }: { positionals: string[]; flags:
const inlineConfig = flagsToAstroInlineConfig(flags);
const { astroConfig } = await resolveConfig(inlineConfig, 'build');

const yargsArgs: YargsArguments = {
_: positionals,
...flags,
};

await cli({ flags: yargsArgs, config: astroConfig });
await cli({ flags, config: astroConfig });
}
8 changes: 4 additions & 4 deletions packages/astro/src/cli/flags.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { parseArgs } from 'node:util';
import type { Arguments } from 'yargs-parser';
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'];
// Alias for now, but allows easier migration to node's `parseArgs` in the future.
export type Flags = Arguments;

export function flagsToAstroInlineConfig(flags: Flags): AstroInlineConfig {
return {
Expand All @@ -20,7 +20,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 === 'string' ? Number(flags.port) : undefined,
port: typeof flags.port === 'number' ? flags.port : undefined,
host:
typeof flags.host === 'string' || typeof flags.host === 'boolean' ? flags.host : undefined,
open:
Expand Down
37 changes: 12 additions & 25 deletions packages/astro/src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
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 @@ -66,9 +65,9 @@ function printVersion() {
}

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

const supportedCommands = new Set([
'add',
Expand Down Expand Up @@ -98,9 +97,7 @@ function resolveCommand(args: ParsedArgsResult): 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, args: ParsedArgsResult) {
const flags = args.values;

async function runCommand(cmd: string, flags: yargs.Arguments) {
// These commands can run directly without parsing the user config.
switch (cmd) {
case 'help':
Expand All @@ -123,7 +120,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) {
// 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 = args.positionals[3];
const subcommand = flags._[3]?.toString();
await update(subcommand, { flags });
return;
}
Expand All @@ -134,7 +131,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) {
}
case 'preferences': {
const { preferences } = await import('./preferences/index.js');
const [subcommand, key, value] = args.positionals.slice(3);
const [subcommand, key, value] = flags._.slice(3).map((v) => v.toString());
const exitCode = await preferences(subcommand, key, value, { flags });
return process.exit(exitCode);
}
Expand All @@ -154,7 +151,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) {
switch (cmd) {
case 'add': {
const { add } = await import('./add/index.js');
const packages = args.positionals.slice(3);
const packages = flags._.slice(3) as string[];
await add(packages, { flags });
return;
}
Expand All @@ -164,7 +161,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) {
case 'link':
case 'init': {
const { db } = await import('./db/index.js');
await db({ positionals: args.positionals, flags });
await db({ flags });
return;
}
case 'dev': {
Expand Down Expand Up @@ -205,20 +202,10 @@ async function runCommand(cmd: string, args: ParsedArgsResult) {

/** The primary CLI action */
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);
const flags = yargs(argv, { boolean: ['global'], alias: { g: 'global' } });
const cmd = resolveCommand(flags);
try {
await runCommand(cmd, args);
await runCommand(cmd, flags);
} catch (err) {
const { throwAndExit } = await import('./throw-and-exit.js');
await throwAndExit(cmd, err);
Expand Down
91 changes: 39 additions & 52 deletions packages/create-astro/src/actions/context.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os from 'node:os';
import { parseArgs } from 'node:util';
import { type Task, prompt } from '@astrojs/cli-kit';
import { random } from '@astrojs/cli-kit/utils';
import arg from 'arg';

import getSeasonalData from '../data/seasonal.js';
import { getName, getVersion } from '../messages.js';
Expand Down Expand Up @@ -33,44 +33,47 @@ export interface Context {
}

export async function getContext(argv: string[]): Promise<Context> {
const args = parseArgs({
args: argv,
allowPositionals: true,
strict: false,
options: {
template: { type: 'string' },
ref: { type: 'string' },
yes: { type: 'boolean', short: 'y' },
no: { type: 'boolean', short: 'n' },
install: { type: 'boolean' },
'no-install': { type: 'boolean' },
git: { type: 'boolean' },
'no-git': { type: 'boolean' },
typescript: { type: 'string' },
'skip-houston': { type: 'boolean' },
'dry-run': { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
fancy: { type: 'boolean' },
const flags = arg(
{
'--template': String,
'--ref': String,
'--yes': Boolean,
'--no': Boolean,
'--install': Boolean,
'--no-install': Boolean,
'--git': Boolean,
'--no-git': Boolean,
'--typescript': String,
'--skip-houston': Boolean,
'--dry-run': Boolean,
'--help': Boolean,
'--fancy': Boolean,

'-y': '--yes',
'-n': '--no',
'-h': '--help',
},
});
{ argv, permissive: true },
);

const packageManager = detectPackageManager() ?? 'npm';
const projectName = args.positionals[0];
let cwd = flags['_'][0];
let {
help,
template,
no,
yes,
install,
'no-install': noInstall,
git,
'no-git': noGit,
typescript,
fancy,
'skip-houston': skipHouston,
'dry-run': dryRun,
ref,
} = args.values;
'--help': help = false,
'--template': template,
'--no': no,
'--yes': yes,
'--install': install,
'--no-install': noInstall,
'--git': git,
'--no-git': noGit,
'--typescript': typescript,
'--fancy': fancy,
'--skip-houston': skipHouston,
'--dry-run': dryRun,
'--ref': ref,
} = flags;
let projectName = cwd;

if (no) {
yes = false;
Expand All @@ -79,26 +82,10 @@ export async function getContext(argv: string[]): Promise<Context> {
if (typescript == undefined) typescript = 'strict';
}

skipHouston = typeof skipHouston == 'boolean' ? skipHouston : undefined;
skipHouston =
((os.platform() === 'win32' && !fancy) || skipHouston) ??
[yes, no, install, git, typescript].some((v) => v !== undefined);

// We use `strict: false` in `parseArgs` to allow unknown options, but Node also
// simply doesn't guarantee the types anymore, so we need to validate ourselves :(
help = !!help;
template = typeof template == 'string' ? template : undefined;
no = !!no;
yes = !!yes;
install = !!install;
noInstall = !!noInstall;
git = !!git;
noGit = !!noGit;
typescript = typeof typescript == 'string' ? typescript : undefined;
fancy = !!fancy;
dryRun = !!dryRun;
ref = typeof ref == 'string' ? ref : undefined;

const { messages, hats, ties } = getSeasonalData({ fancy });

const context: Context = {
Expand All @@ -120,7 +107,7 @@ export async function getContext(argv: string[]): Promise<Context> {
install: install ?? (noInstall ? false : undefined),
git: git ?? (noGit ? false : undefined),
typescript,
cwd: projectName,
cwd,
exit(code) {
process.exit(code);
},
Expand Down
2 changes: 2 additions & 0 deletions packages/db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,13 @@
"ora": "^8.0.1",
"prompts": "^2.4.2",
"strip-ansi": "^7.1.0",
"yargs-parser": "^21.1.1",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/deep-diff": "^1.0.5",
"@types/prompts": "^2.4.9",
"@types/yargs-parser": "^21.0.3",
"astro": "workspace:*",
"astro-scripts": "workspace:*",
"cheerio": "1.0.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/db/src/core/cli/commands/execute/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getManagedAppTokenOrExit } from '@astrojs/studio';
import { LibsqlError } from '@libsql/client';
import type { AstroConfig } from 'astro';
import { green } from 'kleur/colors';
import type { Arguments } from 'yargs-parser';
import {
EXEC_DEFAULT_EXPORT_ERROR,
EXEC_ERROR,
Expand All @@ -15,7 +16,6 @@ import {
} from '../../../integration/vite-plugin-db.js';
import { bundleFile, importBundledFile } from '../../../load-file.js';
import type { DBConfig } from '../../../types.js';
import type { YargsArguments } from '../../types.js';

export async function cmd({
astroConfig,
Expand All @@ -24,7 +24,7 @@ export async function cmd({
}: {
astroConfig: AstroConfig;
dbConfig: DBConfig;
flags: YargsArguments;
flags: Arguments;
}) {
const filePath = flags._[4];
if (typeof filePath !== 'string') {
Expand Down
4 changes: 2 additions & 2 deletions packages/db/src/core/cli/commands/login/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { cyan } from 'kleur/colors';
import open from 'open';
import ora from 'ora';
import prompt from 'prompts';
import type { Arguments } from 'yargs-parser';
import type { DBConfig } from '../../../types.js';
import type { YargsArguments } from '../../types.js';

const isWebContainer =
// Stackblitz heuristic
Expand All @@ -21,7 +21,7 @@ export async function cmd({
}: {
astroConfig: AstroConfig;
dbConfig: DBConfig;
flags: YargsArguments;
flags: Arguments;
}) {
let session = flags.session;

Expand Down
4 changes: 2 additions & 2 deletions packages/db/src/core/cli/commands/push/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getManagedAppTokenOrExit } from '@astrojs/studio';
import type { AstroConfig } from 'astro';
import prompts from 'prompts';
import type { Arguments } from 'yargs-parser';
import { safeFetch } from '../../../../runtime/utils.js';
import { MIGRATION_VERSION } from '../../../consts.js';
import { type DBConfig, type DBSnapshot } from '../../../types.js';
Expand All @@ -12,15 +13,14 @@ import {
getMigrationQueries,
getProductionCurrentSnapshot,
} from '../../migration-queries.js';
import type { YargsArguments } from '../../types.js';

export async function cmd({
dbConfig,
flags,
}: {
astroConfig: AstroConfig;
dbConfig: DBConfig;
flags: YargsArguments;
flags: Arguments;
}) {
const isDryRun = flags.dryRun;
const isForceReset = flags.forceReset;
Expand Down
Loading
Loading