Skip to content

prepare the value of an option #535

Closed

Description

@kumar303

Is it possible to prepare the value of an option as part of its configuration? I'd like to do something along these lines:

require('yargs')
  .option('--source-dir', {
    default: process.cwd(),
    prepare: function(sourceDir) {
      return path.resolve(sourceDir);
    },
  })
  .argv;

In other words, I want to always call path.resolve() on the value. I know I could do this myself after accessing argv but it would be easier to keep this logic in the same place as the option definition. Is there a way to do this already?

Activity

  1. bcoe commented on Jul 3, 2016

    @bcoe
    Member

    @kumar303 I think I've heard of this option referred to as coercion by other folks:

    #191

    I like this idea, and would love to add it.

  2. bathos commented on Jul 18, 2016

    @bathos

    Could this be hooked into validation? For example, throwing from your coercer could trigger the typical validation failure handling (or, more robust: cb(err, res) or a promise). Coercing is desirable for keeping the definitions together, but in itself it’s nothing one couldn’t do after the parsing is complete; however, making that coercion hook into yargs’ validation would permit exiting on the first invalid argument, which is something I don’t think is currently possible.

  3. bcoe commented on Aug 14, 2016

    @bcoe
    Member

    @kumar303 @bathos [email protected] has introduced the concept of coercion, which should address this feature request:

    https://github.com/yargs/yargs#coercekey-fn

    Give this a spin:

    npm cache clear; npm i yargs@next

    @bathos if you throw an exception from within the coercion function, it will be handled by yargs' validation logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions