Skip to content

How best to get raw args? #2424

@mmkal

Description

@mmkal

Hi - I have a use case where I'd like to get the exact raw arguments passed to the command - what's the best way to do that? I notice some inconsistencies in all of the ways that I'm aware of. Example:

import {Argument, Command, Option, program} from 'commander'

program
  .name('myprogram')
  .addOption(new Option('--foo'))
  .addArgument(new Argument('abc'))
  .action(async function (...args) {
    console.log(this.name(), args.slice(0, -2), this.args, this.processedArgs, this.rawArgs)
  })

// `node myprogram.js abc --foo` outputs:
// myprogram ["abc"] ["abc"] ["abc"] ["/usr/local/bin/node", "/path/to/myprogram.js", "abc", "--foo"]

const sub = new Command('subcommand')
sub
  .addOption(new Option('--foo'))
  .addArgument(new Argument('abc'))
  .action(async function (...args) {
    console.log(this.name(), args.slice(0, -2), this.args, this.processedArgs, this.rawArgs)
  })
program.addCommand(sub)

// `node myprogram.js subcommand abc --foo` outputs:
// subcommand [ 'abc' ] [ 'abc' ] [ 'abc' ] []

program.parse()

Note the comments showing the differences in the outputs. The root program exposes everything in rawArgs, which is roughly what I want (ideally I'd like the rawProcessedArgs which would be ["abc", "--foo"] but I can handle getting rid of the node and program path)

But for the subcommand, none of the available ways of getting args, includes the --foo option that I passed. And for some reason rawArgs doesn't even include the abc argument.

Also rawArgs is not part of the typescript interface, so maybe I'm not supposed to be using it?

Is there a better way to get ["abc", "--foo"] in both cases?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions