Search code examples
typescriptyargs

How to distinguish empty command case and default command in yargs?


I want to write a little CLI tool using yargs and typescript.

The first goal is to run the program(I will call it something in this question) when the empty command and --input is given.(e.g. something --input="../hello.there"). I used the default route to handle this.

The second is to ignore or show help on every command except help. However, I used default router '*' so it capture every command that is not defined. Is there any good way to compare undefined routes and ''?

This is the code of my program.

import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import { getPath } from './parser';
import { ArgumentsCamelCase } from 'yargs';

yargs(process.argv)
  .command({
    command: '*',
    describe: "Parse a file's contents",
    builder: function (yargs) {
      return yargs.option('i', {
        alias: 'input',
        describe: 'the URL to make an HTTP request to',
        type: 'string',
      });
    },
    handler() {
      console.log('hi');
    },
  })
  .help()
  .parse();

Solution

  • I found the method. The basic idea is if there is a command, then process.argv[2] does not start with --. By checking this condition in the handler function, we can know that this is a valid empty command or an invalid command.

    const cmd = yargs(process.argv)
      .version('0.1.0')
      .help()
      .command({
        command: '*',
        describe: "Parse a file's contents",
        builder: function (yargs) {
          return yargs.option('input', {
            alias: 'i',
            describe: 'the URL to make an HTTP request to',
            type: 'string',
          });
        },
        handler: (argv) => {
          if (process.argv[2].slice(0, 2) == '--' && argv.input) {
            const sourcePath = getPath(argv.input);
            console.log(sourcePath);
          } else {
            cmd.showHelp();
          }
        },
      })
      .showHelpOnFail(true);
    
    cmd.parse();