Skip to content

Commit

Permalink
feat: allow accessing args with camelCase or kebabCase (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
eskydar authored Mar 28, 2023
1 parent 40816ab commit 85ad8c1
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 7 deletions.
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": "pnpm@7.30.5"
"packageManager": "pnpm@7.30.5",
"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

0 comments on commit 85ad8c1

Please sign in to comment.