0.13.0 ā€¢ Published 10 months ago

cmd-ts v0.13.0

Weekly downloads
460
License
MIT
Repository
-
Last release
10 months ago

cmd-ts

šŸ’» A type-driven command line argument parser, with awesome error reporting šŸ¤¤

Not all command line arguments are strings, but for some reason, our CLI parsers force us to use strings everywhere. šŸ¤” cmd-ts is a fully-fledged command line argument parser, influenced by Rust's clap and structopt:

šŸ¤© Awesome autocomplete, awesome safeness

šŸŽ­ Decode your own custom types from strings with logic and context-aware error handling

šŸŒ² Nested subcommands, composable API

Basic usage

import { command, run, string, number, positional, option } from 'cmd-ts';

const cmd = command({
  name: 'my-command',
  description: 'print something to the screen',
  version: '1.0.0',
  args: {
    number: positional({ type: number, displayName: 'num' }),
    message: option({
      long: 'greeting',
      type: string,
    }),
  },
  handler: (args) => {
    args.message; // string
    args.number; // number
    console.log(args);
  },
});

run(cmd, process.argv.slice(2));

command(arguments)

Creates a CLI command.

Decoding custom types from strings

Not all command line arguments are strings. You sometimes want integers, UUIDs, file paths, directories, globs...

Note: this section describes the ReadStream type, implemented in ./src/example/test-types.ts

Let's say we're about to write a cat clone. We want to accept a file to read into stdout. A simple example would be something like:

// my-app.ts

import { command, run, positional, string } from 'cmd-ts';

const app = command({
  /// name: ...,
  args: {
    file: positional({ type: string, displayName: 'file' }),
  },
  handler: ({ file }) => {
    // read the file to the screen
    fs.createReadStream(file).pipe(stdout);
  },
});

// parse arguments
run(app, process.argv.slice(2));

That works okay. But we can do better. In which ways?

  • Error handling is out of the command line argument parser context, and in userland, making things less consistent and pretty.
  • It shows we lack composability and encapsulation ā€” and we miss a way to distribute shared "command line" behavior.

What if we had a way to get a Stream out of the parser, instead of a plain string? This is where cmd-ts gets its power from, custom type decoding:

// ReadStream.ts

import { Type } from 'cmd-ts';
import fs from 'fs';

// Type<string, Stream> reads as "A type from `string` to `Stream`"
const ReadStream: Type<string, Stream> = {
  async from(str) {
    if (!fs.existsSync(str)) {
      // Here is our error handling!
      throw new Error('File not found');
    }

    return fs.createReadStream(str);
  },
};

Now we can use (and share) this type and always get a Stream, instead of carrying the implementation detail around:

// my-app.ts

import { command, run, positional } from 'cmd-ts';

const app = command({
  // name: ...,
  args: {
    stream: positional({ type: ReadStream, displayName: 'file' }),
  },
  handler: ({ stream }) => stream.pipe(process.stdout),
});

// parse arguments
run(app, process.argv.slice(2));

Encapsulating runtime behaviour and safe type conversions can help us with awesome user experience:

  • We can throw an error when the file is not found
  • We can try to parse the string as a URI and check if the protocol is HTTP, if so - make an HTTP request and return the body stream
  • We can see if the string is -, and when it happens, return process.stdin like many Unix applications

And the best thing about it ā€” everything is encapsulated to an easily tested type definition, which can be easily shared and reused. Take a look at io-ts-types, for instance, which has types like DateFromISOString, NumberFromString and more, which is something we can totally do.

Inspiration

This project was previously called clio-ts, because it was based on io-ts. This is no longer the case, because I want to reduce the dependency count and mental overhead. I might have a function to migrate types between the two.

@infinitebrahmanuniverse/nolb-cmdwechaty@everything-registry/sub-chunk-1343google-photos-migrategloblist-packerfrida-sidecareslint-baselineeslint-overlookimg-catinfluence-asset-export@s21toolkit/cli@s21toolkit/lintgraphql-rss-parserjtz-time-tracker-utilslphistory2k8testk8test-cli-logicminauthpkl-typescriptpatch-semantic-release-npm-for-msrprint-openapiremasteredtablemark-clithe-real-doctestsidecarspa-clienttask-graph-processortask-graph-protocolserve-hpubwechaty-tokenwaka-pmwebdatacommonswechaty-labcdk-git-configcdk-manager@cotar/cli@d-fischer/crowd@antribute/backend-core@api-ts/openapi-generator@basemaps/sprites@bencemanyoki/borm@bencemanyoki/initp@begit/cli@bisonai/orakl-cli@binsee/sidecaramtoolaijinkela-wechaty@crx-tools/create-app@crx-tools/scriptsccna-dl@cogeotiff/cliconvert-sh-theme@solid-cli/core@solid-cli/utils@qlite/cli@stavalfi/ci@strwatcher/suipta@sirhall/shared_worker@replit/river-codegen@sv-oss/changelog-autotagger@sv-oss/find-s3-objects-by-acl@tahini/nc@thomasskk/pg-migrate@thomasgormley/dev-cliyamasbuttercup-to-1password@packtory/cli@ryanke/violet@ryanwolhuter/ui-utils@p-lang/plang@salesway/pgts@pkl-community/pkl-typescript@pp-finder/cli@phryneas/process-profile-sourcemapsd4sdcrowd@gerrit0/broken-link-checker@deptdash/cdk-webapp@eyeseetea/d2-loggerdirectus-ts-schema@ignisda/athalar@era-ci/coredpv-electron-app@flycode-org/tsfind@mat3ra/standata@journeyapps/ts-browser-compat@lunasec/cli@juzi/wechaty@nebrazkp/upa@nirtamir-cli/core@nirtamir-cli/utils@nirtamir2/cli@lo1tuma/parallel-typescript@nk11/ts-json-yaml@msessa/find-s3-objects-by-acl
0.13.0

10 months ago

0.12.1

1 year ago

0.12.0

1 year ago

0.11.0

2 years ago

0.10.2

2 years ago

0.10.1

2 years ago

0.10.0

2 years ago

0.9.0

2 years ago

0.8.0

2 years ago

0.7.0

3 years ago

0.6.9

3 years ago

0.6.8

3 years ago

0.6.7

3 years ago

0.6.6

3 years ago

0.6.5

4 years ago

0.6.4

4 years ago

0.6.3

4 years ago

0.6.2

4 years ago

0.6.1

4 years ago

0.6.0

4 years ago

0.5.0

4 years ago

0.5.1

4 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.3.2

4 years ago

0.3.1

4 years ago

0.3.0

4 years ago

0.3.0-beta-2

4 years ago