Questions about -v variable=value & parsing .arguments() #318
-
Hi! I have some questions:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @cascading-jox, sry for late reply, i somehow missed this discussion. 1.)
There are different ways to achieve your goal: await new Command()
.option(
"-v, --variable <variable-name>",
"pass variable(s) to script",
{
value: (val) => {
const [key, ...parts] = val.split("=");
const value = parts.join("=");
if (!value) {
throw new ValidationError(`missing value for variable: ${val}`);
}
return { [key]: value };
},
},
)
.action(({ variable }) => console.log("variable:", variable))
.parse(Deno.args); In combination with the list type:await new Command()
.option(
"-v, --variable <variable-name:string[]>",
"pass variable(s) to script",
{
value: (values, prev: Record<string, string> = {}) => {
for (const val of values) {
const [key, ...parts] = val.split("=");
const value = parts.join("=");
if (!value) {
throw new ValidationError(`missing value for variable: ${val}`);
}
prev[key] = value;
}
return prev;
},
},
)
.action(({ variable }) => console.log("variable:", variable))
.parse(Deno.args); In combination with the collect option:await new Command()
.option(
"-v, --variable <variable-name>",
"pass variable(s) to script",
{
collect: true,
value: (val, prev: Record<string, string> = {}) => {
const [key, ...parts] = val.split("=");
const value = parts.join("=");
if (!value) {
throw new ValidationError(`missing value for variable: ${val}`);
}
return { ...prev, [key]: value };
},
},
)
.action(({ variable }) => console.log("variable:", variable))
.parse(Deno.args); await new Command()
.type("variable", ({ label, name, type, value }) => {
const [key, ...parts] = value.split("=");
const val = parts.join("=");
if (!val) {
throw new ValidationError(
`${label} "${name}" must be of type "${type}", but got "${value}". Expacted value: <variable>=<value>`,
);
}
return { [key]: val };
})
.option(
"-v, --variable <variable-name:variable>",
"pass variable(s) to script",
)
.action(({ variable }) => console.log("variable:", variable))
.parse(Deno.args); A custom type can be also combined with the 2.)
Arguments supports also build-in and custom types: I planned to also add a 3.)
Types can be defined after the argument name separated by colon: There are a few build-in types and you can also define your custom types. new Command()
.option("-f, --foo <name>", "Description...", ({value}) => {
// validate value...
return value;
}) or: new Command()
.option("-f, --foo <name>", "Description...", {
value: ({value}) => {
// validate value...
return value;
}
}) |
Beta Was this translation helpful? Give feedback.
Hi @cascading-jox,
sry for late reply, i somehow missed this discussion.
1.)
There are different ways to achieve your goal:
Value handler
…