otps
Command line argument parser with format inspired by esbuild
- value:
--format esm
or short -f esm
- flag:
-v
, -vPfz
or -vvv
- key/value:
--format:ts esm
or -f:ts esm
- key:
--external:fs
or short -e:fs
Supports sub-commands, see below.
Getting started
Install otps
using pnpm:
pnpm add otps
Or npm:
npm install --save otps
Let's get started by writing a simple command line application that takes one
parameter named format
(or f
for short).
First, create a app.js
file:
import { parse, Value } from 'otps'
const [params, args] = parse(process.argv.slice(2), {
format: Value(),
f: 'format',
})
Then run the program:
node app.js --format esm index.ts
Or equivalent:
node app.js -f esm index.ts
Sub commands
Let's create a more advanced app that uses a verbose
parameter (with a v
alias) and a sub-commands build
with a level
parameter that takes one of
two values debug
or info
.
Create a subcmdapp.js
file:
import { parse, Flag, OneOf } from 'otps'
const [params, args] = parse(process.argv.slice(2), {
verbose: Flag(),
v: 'verbose',
build: {
level: OneOf('debug', 'info'),
},
})
Then run the program:
node subcmdapp.js -vvv build --level info index.ts
Using cmds
For easier managment of sub-commands, use cmds
:
import { parse, Value, cmds } from 'otps'
const [params, args] = parse(process.argv.slice(2), {
build: {
format: Value(),
production: {
version: Value(),
},
},
})
cmds(params, args)({
build(params, args) {
const format = params.format
cmds(params, args)({
production(params, args) {
const version = params.version
}
})
}
})
Parameters
Parameters are defined using the following syntax: { name: Func }
or with aliases { name: Func, n: 'name' }
. Where Func
is one of:
Value()
:
parse(['--format', 'esm'], { format: Value() })
OneOf(string | regex, ...)
:
parse(['--level', 'dEbUg'], { level: OneOf(/^debug$/i, 'info') })
Flag()
:
parse(['-v'], { v: Flag() })
parse(['-vvv'], { v: Flag() })
parse(['-vP'], { v: Flag(), P: Flag() })
Key()
:
parse(['--external:fs'], { external: Key() })
parse(['--external:fs', '-e:fs'], { external: Key(), e: 'external' })
Key(Value() | OneOf(...))
:
parse(['--define:DEBUG', 'true'], { define: Key(Value()) })
parse(['--define:LEVEL', 'debug'], { define: Key(OneOf('debug', 'info')) })
Maybe(Value() | OneOf(...))
:
parse(['--format'], { format: Maybe(Value()) })
parse(['--format', 'esm'], { format: Maybe(Value()) })
parse(['--level'], { level: Maybe(OneOf('debug', 'info')) })
parse(['--level', 'info'], { level: Maybe(OneOf('debug', 'info')) })
Many(Value() | OneOf(...) | Maybe(...))
:
parse(['--format', 'esm', '--format', 'cjs'], { format: Many(Value()) })
parse(['--format', '--format', 'cjs'], { format: Many(Maybe(OneOf('esm', 'cjs'))) })