What is cmd-ts?
cmd-ts is a TypeScript library for building command-line applications. It provides a simple and type-safe way to define commands, arguments, and options, making it easier to create robust CLI tools.
What are cmd-ts's main functionalities?
Defining a Command
This feature allows you to define a command with arguments. In this example, a 'hello' command is created that takes a 'name' argument and prints a greeting message.
const { command, run, string } = require('cmd-ts');
const hello = command({
name: 'hello',
args: {
name: string({
description: 'Name to greet'
})
},
handler: ({ name }) => {
console.log(`Hello, ${name}!`);
}
});
run(hello, process.argv.slice(2));
Handling Options
This feature allows you to handle options in your command. In this example, an 'excited' option is added to the 'greet' command, which appends an exclamation mark to the greeting if specified.
const { command, run, string, option } = require('cmd-ts');
const greet = command({
name: 'greet',
args: {
name: string({
description: 'Name to greet'
}),
excited: option({
type: Boolean,
long: 'excited',
description: 'Add an exclamation mark'
})
},
handler: ({ name, excited }) => {
const greeting = `Hello, ${name}${excited ? '!' : ''}`;
console.log(greeting);
}
});
run(greet, process.argv.slice(2));
Subcommands
This feature allows you to define subcommands within a main command. In this example, 'hello' and 'goodbye' are subcommands of the 'app' command.
const { command, run, subcommands, string } = require('cmd-ts');
const hello = command({
name: 'hello',
args: {
name: string({
description: 'Name to greet'
})
},
handler: ({ name }) => {
console.log(`Hello, ${name}!`);
}
});
const goodbye = command({
name: 'goodbye',
args: {
name: string({
description: 'Name to bid farewell'
})
},
handler: ({ name }) => {
console.log(`Goodbye, ${name}!`);
}
});
const app = subcommands({
name: 'app',
cmds: { hello, goodbye }
});
run(app, process.argv.slice(2));
Other packages similar to cmd-ts
commander
Commander is a popular library for building command-line interfaces in Node.js. It provides a flexible and easy-to-use API for defining commands, arguments, and options. Compared to cmd-ts, Commander is more widely used and has a larger community, but it is not type-safe out of the box.
yargs
Yargs is another widely-used library for building CLI applications. It offers a rich set of features for parsing arguments and options, and it supports command chaining and middleware. Yargs is more feature-rich than cmd-ts but does not provide the same level of type safety.
oclif
Oclif is a framework for building command-line tools, developed by Heroku. It provides a robust structure for creating complex CLI applications with plugins and generators. Oclif is more suited for large-scale CLI applications compared to cmd-ts, which is simpler and more lightweight.
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;
args.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:
import { command, run, positional, string } from 'cmd-ts';
const app = command({
args: {
file: positional({ type: string, displayName: 'file' }),
},
handler: ({ file }) => {
fs.createReadStream(file).pipe(stdout);
},
});
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:
import { Type } from 'cmd-ts';
import fs from 'fs';
const ReadStream: Type<string, Stream> = {
async from(str) {
if (!fs.existsSync(str)) {
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:
import { command, run, positional } from 'cmd-ts';
const app = command({
args: {
stream: positional({ type: ReadStream, displayName: 'file' }),
},
handler: ({ stream }) => stream.pipe(process.stdout),
});
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.