All Projects → Schniz → cmd-ts

Schniz / cmd-ts

Licence: MIT License
💻 A type-driven command line argument parser

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to cmd-ts

Flags
⛳ Simple, extensible, header-only C++17 argument parser released into the public domain.
Stars: ✭ 187 (+103.26%)
Mutual labels:  parse, argument-parser
go-getoptions
Fully featured Go (golang) command line option parser with built-in auto-completion support.
Stars: ✭ 41 (-55.43%)
Mutual labels:  argument-parser
pyhaproxy
Python library to parse haproxy configurations
Stars: ✭ 50 (-45.65%)
Mutual labels:  parse
args-parser
args-parser is a small C++ header-only library for parsing command line arguments.
Stars: ✭ 53 (-42.39%)
Mutual labels:  argument-parser
CROHME extractor
CROHME dataset extractor for OFFLINE-text-recognition task.
Stars: ✭ 77 (-16.3%)
Mutual labels:  parse
Console CommandLine
Full featured command line options and arguments parser.
Stars: ✭ 19 (-79.35%)
Mutual labels:  argument-parser
libdvbtee
dvbtee: a digital television streamer / parser / service information aggregator supporting various interfaces including telnet CLI & http control
Stars: ✭ 65 (-29.35%)
Mutual labels:  parse
carsBase
База автомобилей с марками и моделями JSON, CSV, XLSX и MySQL
Stars: ✭ 49 (-46.74%)
Mutual labels:  parse
eval-estree-expression
Safely evaluate JavaScript (estree) expressions, sync and async.
Stars: ✭ 22 (-76.09%)
Mutual labels:  parse
vgprompter
C# library to parse a subset of Ren'Py script syntax
Stars: ✭ 17 (-81.52%)
Mutual labels:  parse
Android-Shortify
An Android library used for making an Android application more faster with less amount of code. Shortify for Android provides basic functionalities of view and resource binding, view customization, JSON parsing, AJAX, various readymade dialogs and much more.
Stars: ✭ 21 (-77.17%)
Mutual labels:  parse
der-parser
BER/DER parser written in pure Rust. Fast, zero-copy, safe.
Stars: ✭ 73 (-20.65%)
Mutual labels:  parse
easy-json-parse
Parse your json safely and easily.
Stars: ✭ 33 (-64.13%)
Mutual labels:  parse
astutils
Bare essentials for building abstract syntax trees, and skeleton classes for PLY lexers and parsers.
Stars: ✭ 13 (-85.87%)
Mutual labels:  parse
parse-cloud-class
Extendable way to set up Parse Cloud classes behaviour
Stars: ✭ 40 (-56.52%)
Mutual labels:  parse
option-parser
A Lightweight, header-only CLI option parser for C++
Stars: ✭ 16 (-82.61%)
Mutual labels:  argument-parser
parse it
A python library for parsing multiple types of config files, envvars & command line arguments that takes the headache out of setting app configurations.
Stars: ✭ 86 (-6.52%)
Mutual labels:  argument-parser
Splain
small parser to create more interesting language/sentences
Stars: ✭ 15 (-83.7%)
Mutual labels:  parse
expresol
Library for executing customizable script-languages in python
Stars: ✭ 11 (-88.04%)
Mutual labels:  parse
warframe-worldstate-parser
📗 An Open parser for Warframe's Worldstate in Javascript
Stars: ✭ 50 (-45.65%)
Mutual labels:  parse

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].