citty icon indicating copy to clipboard operation
citty copied to clipboard

Support argument normalizer/validator

Open peterroe opened this issue 2 years ago • 5 comments

Describe the feature

I am using citty in my project, And I think it's maybe a good idea to support it. 👀

This is my source code:

export default defineCommand({
    meta: {
        name: 'create',
        description: 'Generate new project from template'
    },
    args: {
        projectPath: {
            type: 'string',
            description: 'Project path to create',
            valueHint: "PWD",
            default: process.cwd()
        },
	},
	setup({ args }) {
        args.projectPath = path.resolve(args.projectPath)
    },
	run() {}
}

And support formatter attribute in args definition, then we can do like this:

export default defineCommand({
    meta: {
        name: 'create',
        description: 'Generate new project from template'
    },
    args: {
        projectPath: {
            type: 'string',
            description: 'Project path to create',
            valueHint: "PWD",
            default: process.cwd(),
+			formatter: (inputPath) => path.resolve(inputPath)
        },
	},
-	setup({ args }) {
-        args.projectPath = path.resolve(inputPath)
-    },
	run() {}
}

Additional information

  • [X] Would you be willing to help implement this feature?

peterroe avatar Nov 07 '23 07:11 peterroe

Are you thinking of a validator/normalizer that normalizes value for ctx.args? that's a good idea.

(formatter could also be nice idea btw but i guess for CLI output in usage)

pi0 avatar Nov 07 '23 13:11 pi0

Yes,normalizer is a good idea. But I also think we need validator to validate ctx.args.

In normalizer,ctx.args will be normalized.

In validator, the NodeJs process will be killed if the ctx.args are not as expected

They are different feature.

What's your opinion? :)

peterroe avatar Nov 07 '23 14:11 peterroe

Just ran into this need myself. Seems like a zod-like thing's needed here.

I need to both validate and normalize my-cli --folder=./does-not-exist

  1. Validation to ensure the folder exists (though it's a valid string type)
  2. Normalize the path to process.cwd()

ericclemmons avatar Apr 11 '24 02:04 ericclemmons

For my usecase, I accept a logLevel arg and I'm looking to normalize/transform it to either an enum or a number alongside validation. Would this kind type transformation be a responsibilty of the normalize function or does this qualify another feature request?

Eazash avatar May 08 '24 21:05 Eazash