Skip to content

feat: allow accessing args with camelCase or kebabCase #17

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 11 commits into from
Mar 28, 2023
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,8 @@
"unbuild": "^1.1.2",
"vitest": "^0.29.7"
},
"packageManager": "[email protected]"
"packageManager": "[email protected]",
"dependencies": {
"scule": "^1.0.0"
}
}
2 changes: 1 addition & 1 deletion playground/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default defineCommand({
description: "disable hot module replacement",
default: true,
},
dir: {
workDir: {
type: "string",
description: "working directory",
required: true,
Expand Down
5 changes: 4 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 11 additions & 4 deletions src/args.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { kebabCase, camelCase } from "scule";
import { parseRawArgs } from "./_parser";
import type { Arg, ArgsDef, ParsedArgs } from "./types";
import { CLIError, toArray } from "./_utils";
Expand Down Expand Up @@ -28,25 +29,31 @@ export function parseArgs(rawArgs: string[], argsDef: ArgsDef): ParsedArgs {
const parsed = parseRawArgs(rawArgs, parseOptions);
const [, ...positionalArguments] = parsed._;

const parsedArgsProxy = new Proxy(parsed, {
get(target: ParsedArgs, prop: string) {
return target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];
},
});

for (const [, arg] of args.entries()) {
if (arg.type === "positional") {
const nextPositionalArgument = positionalArguments.shift();
if (nextPositionalArgument !== undefined) {
parsed[arg.name] = nextPositionalArgument;
parsedArgsProxy[arg.name] = nextPositionalArgument;
} else if (arg.default !== undefined) {
parsed[arg.name] = arg.default;
parsedArgsProxy[arg.name] = arg.default;
} else {
throw new CLIError(
`Missing required positional argument: ${arg.name.toUpperCase()}`,
"EARG"
);
}
} else if (arg.required && parsed[arg.name] === undefined) {
} else if (arg.required && parsedArgsProxy[arg.name] === undefined) {
throw new CLIError(`Missing required argument: --${arg.name}`, "EARG");
}
}

return parsed;
return parsedArgsProxy;
}

export function resolveArgs(argsDef: ArgsDef): Arg[] {
Expand Down