Skip to content
This repository has been archived by the owner on Aug 22, 2023. It is now read-only.

Support forwarding arguments #74

Open
AuHau opened this issue Mar 27, 2020 · 1 comment
Open

Support forwarding arguments #74

AuHau opened this issue Mar 27, 2020 · 1 comment

Comments

@AuHau
Copy link

AuHau commented Mar 27, 2020

When -- is present the rest is taken as arguments. I believe it should be possible to specify the behavior where these "rest" arguments should be distinguishable from other args in order to have "forwarding behavior".

For example cli --parameter 1 --bool arg1 arg2 -- --parameter 2 arg3 arg4 should distinguish arg1 and arg2 from --parameter 2 arg3 arg4.

@ozum
Copy link

ozum commented Jun 14, 2020

Related to this, please support extraArgs and extraFlags properties, which returns all values not defined in static flags and static args. So I can forward extra arguments to other cli tools.

For example:

class SomeCommand extends Command {
  static strict = false;
  static flags = {
    force: flags.boolean({ char: "f" }),
  };
}

$ my-cli somecommand -f --clearCache --dir src

const { flags, extraFlags } = this.parse(SomeCommand);
// flags --> { force: true }
// extraFlags --> { "--clearCache": undefined, "--dir": "src" }

A Simple Implementation

Below is a simple implementation with limitations if anyone interested.

  • Only supports flags. (Args are not supported)
  • Multiple flags are not supported. (Throws if a flag found is multiple.)
class SomeCommand extends Command {
  static strict = false;
  static flags = {
    force: flags.boolean({ char: "f" }),
    dir: flags.string({ char: "d" }),
  };

  protected get extraFlags(): string[] {
    const constructor = this.constructor as any;
    const flagDefinitions = constructor.flags;
    const { flags }: { flags: string[] } = this.parse(constructor);
    const argv = process.argv.slice(3);
    Object.entries(flags).forEach(([flag, value]) => {
      const flagIndex = argv.findIndex((argvalue) => argvalue === `--${flag}` || argvalue === `-${flagDefinitions[flag].char}`);

      if (flagIndex > -1) {
        if (flagDefinitions[flag].multiple) throw new Error("Multiple falgs are not supported.");
        const numberOfItemsToRemove = argv[flagIndex + 1] === value ? 2 : 1;
        argv.splice(flagIndex, numberOfItemsToRemove);
      }
    });

    return argv;
  }
}

// `my-cli somecommand -a 1 -f --dir src -b 2 -c`
// this.extraFlags ---> ["-a", "1", "-b", "2", "-c"]

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants