Schniz / cmd-ts

💻 A type-driven command line argument parser
https://cmd-ts.now.sh
MIT License
241 stars 25 forks source link

add parse method to runner #154

Closed ldub closed 2 years ago

ldub commented 2 years ago

Hey @Schniz,

I really like your package. You've created the best argument parser in the typescript world, IMO.

However, sometimes it is necessary to be able to use runtime objects after parsing, which aren't available during command creation.

I've got this lovely command here, but if my client for some third party service gets created at a later point, I can't use the client in the command handler.

import * as cmd from 'cmd-ts';

const someCommand = cmd.command({
  name: 'some-command',
  args: {
    someArg: cmd.positional({ type: cmd.string }),
    someAmount: cmd.option({ type: cmd.number, long: 'amount', short: 'a', defaultValue: () => 1}),
  },
  handler: async ({ someArg, someAmount }) => {
    console.log(`some-command ${someArg} ${someAmount}`);
    // no access to client
  },
});

const client = new ThirdPartyService(apiKey);

In general, it would be extremely useful if it was possible to use your package to handle typesafe command registration and parsing, and retrieve the parse result directly, instead of only being able to pipe it through the handler.

This PR exposes exactly this functionality, via a parse function on the runner. Would you consider merging and supporting this functionality? There is really no alternative for this kind of thing. Using io-ts directly in each project would be a pain and would require recreating a ton of the work you already did.

Another option would be to give the runner the ability to overload the handler when run is called, as opposed to only being able to supply it when the command is created.

changeset-bot[bot] commented 2 years ago

⚠️ No Changeset found

Latest commit: f5ee025340fbe54c48485ed1a73139a771be2983

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

vercel[bot] commented 2 years ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated
cmd-ts ✅ Ready (Inspect) Visit Preview May 17, 2022 at 5:47AM (UTC)
Schniz commented 2 years ago

Hey! Happy that it provides value to you too! 😁 this PR looks great. Do you want to create a changeset so it will be added to the changelog? (I've been toying with changesets for a while and it's amazing 😁 )

Schniz commented 2 years ago

you know what I'm just gonna merge and release and set up changesets in this repo because I'm not sure it is set up correctly yet 😁