diff --git a/README.2.md b/README.2.md deleted file mode 100644 index 6415ad2..0000000 --- a/README.2.md +++ /dev/null @@ -1,108 +0,0 @@ -> A video showcasing how pnpm autocompletions work on a test CLI command like `my-cli` - -# tab - -> Instant feedback for your CLI tool when hitting [TAB] in your terminal - -As CLI tooling authors, if we can spare our users a second or two by not checking the documentation or writing the `-h` option, we're doing them a huge favor. The unconscious loves hitting the [TAB] key. It always expects feedback. So it feels disappointing when hitting that key in the terminal but then nothing happens. That frustration is apparent across the whole JavaScript CLI tooling ecosystem. - -Autocompletions are the solution to not break the user's flow. The issue is they're not simple to add. `zsh` expects them in one way, and `bash` in another way. Then where do we provide them so the shell environment parses them? Too many headaches to ease the user's experience. Whether it's worth it or not is out of the question. Because tab is the solution to this complexity. - -`my-cli.ts`: - -```typescript -import t from '@bomb.sh/tab'; - -t.name('my-cli'); - -t.command('start', 'start the development server'); - -if (process.argv[2] === 'complete') { - const [shell, ...args] = process.argv.slice(3); - if (shell === '--') { - t.parse(args); - } else { - t.setup(shell, x); - } -} -``` - -This `my-cli.ts` would be equipped with all the tools required to provide autocompletions. - -```bash -node my-cli.ts complete -- "st" -``` - -``` -start start the development server -:0 -``` - -This output was generated by the `t.parse` method to autocomplete "st" to "start". - -Obviously, the user won't be running that command directly in their terminal. They'd be running something like this. - -```bash -source <(node my-cli.ts complete zsh) -``` - -Now whenever the shell sees `my-cli`, it would bring the autocompletions we wrote for this CLI tool. The `node my-cli.ts complete zsh` part would output the zsh script that loads the autocompletions provided by `t.parse` which then would be executed using `source`. - -The autocompletions only live through the current shell session. To set them up across all terminal sessions, the autocompletion script should be injected in the `.zshrc` file. - -```bash -my-cli complete zsh > ~/completion-for-my-cli.zsh && echo 'source ~/completion-for-my-cli.zsh' >> ~/.zshrc -``` - -Or - -```bash -echo 'source <(npx --offline my-cli complete zsh)' >> ~/.zshrc -``` - -This is an example of autocompletions on a global CLI command that is usually installed using the `-g` flag (e.g. `npm add -g my-cli`) which is available across the computer. - ---- - -While working on tab, we came to the realization that most JavaScript CLIs are not global CLI commands but rather, per-project dependencies. - -For instance, Vite won't be installed globally and instead it'd be always installed on a project. Here's an example usage: - -```bash -pnpm vite dev -``` - -Rather than installing it globally. This example is pretty rare: - -```bash -vite dev -``` - -So in this case, a computer might have hundreds of Vite instances each installed separately and potentially from different versions on different projects. - -We were looking for a fluid strategy that would be able to load the autocompletions from each of these dependencies on a per-project basis. - -And that made us develop our own autocompletion abstraction over npm, pnpm and yarn. This would help tab identify which binaries are available in a project and which of these binaries provide autocompletions. So the user would not have to `source` anything or inject any script in their `.zshrc`. - -They'd only have to run this command once and inject it in their shell config. - -```bash -npx @bomb.sh/tab pnpm zsh -``` - -These autocompletions on top of the normal autocompletions that these package managers provide are going to be way more powerful. - -These new autocompletions on top of package managers would help us with autocompletions on commands like `pnpm vite` and other global or per-project binaries. The only requirement would be that the npm binary itself would be a tab-compatible binary. - -What is a tab-compatible binary? It's a tool that provides the `complete` subcommand that was showcased above. Basically any CLI tool that uses tab for its autocompletions is a tab-compatible binary. - -```bash -pnpm my-cli complete -- -``` - -``` -start start the development server -:0 -``` - -We are planning to maintain these package manager autocompletions on our own and turn them into full-fledged autocompletions that touch on every part of our package managers. diff --git a/README.md b/README.md index f4686cc..3c2710e 100644 --- a/README.md +++ b/README.md @@ -1,169 +1,167 @@ +> A video showcasing how pnpm autocompletions work on a test CLI command +> like `my-cli` + # tab -Shell autocompletions are largely missing in the javascript cli ecosystem. This tool is an attempt to make autocompletions come out of the box for any cli tool. +Shell autocompletions are largely missing in the JavaScript CLI ecosystem. Tab provides a simple API for adding autocompletions to any JavaScript CLI tool. -Tools like git and their autocompletion experience inspired us to build this tool and make the same ability available for any javascript cli project. Developers love hitting the tab key, hence why they prefer tabs over spaces. +Additionally, tab supports autocompletions for `pnpm`, `npm`, `yarn`, and `bun`. -## Examples +As CLI tooling authors, if we can spare our users a second or two by not checking documentation or writing the `-h` flag, we're doing them a huge favor. The unconscious mind loves hitting the [TAB] key and always expects feedback. When nothing happens, it breaks the user's flow - a frustration apparent across the whole JavaScript CLI tooling ecosystem. -Check out the [examples directory](./examples) for complete examples of using Tab with different command-line frameworks: +Tab solves this complexity by providing autocompletions that work consistently across `zsh`, `bash`, `fish`, and `powershell`. -- [CAC](./examples/demo.cac.ts) -- [Citty](./examples/demo.citty.ts) -- [Commander.js](./examples/demo.commander.ts) +## Installation -## Usage +```bash +npm install @bomb.sh/tab +# or +pnpm add @bomb.sh/tab +# or +yarn add @bomb.sh/tab +# or +bun add @bomb.sh/tab +``` -```ts -import { Completion, script } from '@bomb.sh/tab'; +## Quick Start -const name = 'my-cli'; -const completion = new Completion(); +Add autocompletions to your CLI tool: -completion.addCommand( - 'start', - 'Start the application', - async (previousArgs, toComplete, endsWithSpace) => { - // suggestions - return [ - { value: 'dev', description: 'Start in development mode' }, - { value: 'prod', description: 'Start in production mode' }, - ]; - } -); - -completion.addOption( - 'start', - '--port', - 'Specify the port number', - async (previousArgs, toComplete, endsWithSpace) => { - return [ - { value: '3000', description: 'Development port' }, - { value: '8080', description: 'Production port' }, - ]; - } -); +```typescript +import t from '@bomb.sh/tab'; -// a way of getting the executable path to pass to the shell autocompletion script -function quoteIfNeeded(path: string) { - return path.includes(' ') ? `'${path}'` : path; -} -const execPath = process.execPath; -const processArgs = process.argv.slice(1); -const quotedExecPath = quoteIfNeeded(execPath); -const quotedProcessArgs = processArgs.map(quoteIfNeeded); -const quotedProcessExecArgs = process.execArgv.map(quoteIfNeeded); -const x = `${quotedExecPath} ${quotedProcessExecArgs.join(' ')} ${quotedProcessArgs[0]}`; - -if (process.argv[2] === '--') { - // autocompletion logic - await completion.parse(process.argv.slice(2), 'start'); // TODO: remove "start" -} else { - // process.argv[2] can be "zsh", "bash", "fish", "powershell" - script(process.argv[2], name, x); +// Define your CLI structure +const devCmd = t.command('dev', 'Start development server'); +devCmd.option('port', 'Specify port', (complete) => { + complete('3000', 'Development port'); + complete('8080', 'Production port'); +}); + +// Handle completion requests +if (process.argv[2] === 'complete') { + const shell = process.argv[3]; + if (shell === '--') { + const args = process.argv.slice(4); + t.parse(args); + } else { + t.setup('my-cli', 'node my-cli.js', shell); + } } ``` -Now your user can run `source <(my-cli complete zsh)` and they will get completions for the `my-cli` command using the [autocompletion server](#autocompletion-server). +Test your completions: + +```bash +node my-cli.js complete -- dev --port= +# Output: --port=3000 Development port +# --port=8080 Production port +``` + +Install for users: + +```bash +# One-time setup +source <(my-cli complete zsh) + +# Permanent setup +my-cli complete zsh > ~/.my-cli-completion.zsh +echo 'source ~/.my-cli-completion.zsh' >> ~/.zshrc +``` + +## Package Manager Completions + +As mentioned earlier, tab provides completions for package managers as well: + +```bash +# Generate and install completion scripts +npx @bomb.sh/tab pnpm zsh > ~/.pnpm-completion.zsh && echo 'source ~/.pnpm-completion.zsh' >> ~/.zshrc +npx @bomb.sh/tab npm bash > ~/.npm-completion.bash && echo 'source ~/.npm-completion.bash' >> ~/.bashrc +npx @bomb.sh/tab yarn fish > ~/.config/fish/completions/yarn.fish +npx @bomb.sh/tab bun powershell > ~/.bun-completion.ps1 && echo '. ~/.bun-completion.ps1' >> $PROFILE +``` + +Example in action: + +```bash +pnpm install --reporter= +# Shows: append-only, default, ndjson, silent (with descriptions) + +yarn add --emoji= +# Shows: true, false +``` -## Adapters +## Framework Adapters -Since we are heavy users of tools like `cac` and `citty`, we have created adapters for both of them. Ideally, tab would be integrated internally into these tools, but for now, this is a good compromise. +Tab provides adapters for popular JavaScript CLI frameworks. -### `@bomb.sh/tab/cac` +### CAC Integration -```ts +```typescript import cac from 'cac'; import tab from '@bomb.sh/tab/cac'; const cli = cac('my-cli'); -cli.command('dev', 'Start dev server').option('--port ', 'Specify port'); +// Define your CLI +cli + .command('dev', 'Start dev server') + .option('--port ', 'Specify port') + .option('--host ', 'Specify host'); +// Initialize tab completions const completion = tab(cli); -// Get the dev command completion handler -const devCommandCompletion = completion.commands.get('dev'); - -// Get and configure the port option completion handler -const portOptionCompletion = devCommandCompletion.options.get('--port'); -portOptionCompletion.handler = async ( - previousArgs, - toComplete, - endsWithSpace -) => { - return [ - { value: '3000', description: 'Development port' }, - { value: '8080', description: 'Production port' }, - ]; -}; +// Add custom completions for option values +completion.commands.get('dev')?.options.get('--port')!.handler = async () => [ + { value: '3000', description: 'Development port' }, + { value: '8080', description: 'Production port' }, +]; cli.parse(); ``` -Now autocompletion will be available for any specified command and option in your cac instance. If your user writes `my-cli dev --po`, they will get suggestions for the `--port` option. Or if they write `my-cli d` they will get suggestions for the `dev` command. - -Suggestions are missing in the adapters since yet cac or citty do not have a way to provide suggestions (tab just came out!), we'd have to provide them manually. Mutations do not hurt in this situation. - -### `@bomb.sh/tab/citty` +### Citty Integration -```ts -import citty, { defineCommand, createMain } from 'citty'; +```typescript +import { defineCommand, createMain } from 'citty'; import tab from '@bomb.sh/tab/citty'; const main = defineCommand({ - meta: { - name: 'my-cli', - description: 'My CLI tool', + meta: { name: 'my-cli', description: 'My CLI tool' }, + subCommands: { + dev: defineCommand({ + meta: { name: 'dev', description: 'Start dev server' }, + args: { + port: { type: 'string', description: 'Specify port' }, + host: { type: 'string', description: 'Specify host' }, + }, + }), }, }); -const devCommand = defineCommand({ - meta: { - name: 'dev', - description: 'Start dev server', - }, - args: { - port: { type: 'string', description: 'Specify port' }, - }, -}); - -main.subCommands = { - dev: devCommand, -}; - +// Initialize tab completions const completion = await tab(main); -// TODO: addHandler function to export -const devCommandCompletion = completion.commands.get('dev'); - -const portOptionCompletion = devCommandCompletion.options.get('--port'); - -portOptionCompletion.handler = async ( - previousArgs, - toComplete, - endsWithSpace -) => { - return [ - { value: '3000', description: 'Development port' }, - { value: '8080', description: 'Production port' }, - ]; -}; +// Add custom completions +completion.commands.get('dev')?.options.get('--port')!.handler = async () => [ + { value: '3000', description: 'Development port' }, + { value: '8080', description: 'Production port' }, +]; const cli = createMain(main); cli(); ``` -### `@bomb.sh/tab/commander` +### Commander.js Integration -```ts +```typescript import { Command } from 'commander'; import tab from '@bomb.sh/tab/commander'; const program = new Command('my-cli'); program.version('1.0.0'); -// Add commands +// Define commands program .command('serve') .description('Start the server') @@ -173,74 +171,40 @@ program console.log('Starting server...'); }); -// Initialize tab completion +// Initialize tab completions const completion = tab(program); -// Configure custom completions -for (const command of completion.commands.values()) { - if (command.name === 'serve') { - for (const [option, config] of command.options.entries()) { - if (option === '--port') { - config.handler = () => { - return [ - { value: '3000', description: 'Default port' }, - { value: '8080', description: 'Alternative port' }, - ]; - }; - } - } - } -} +// Add custom completions +completion.commands.get('serve')?.options.get('--port')!.handler = async () => [ + { value: '3000', description: 'Default port' }, + { value: '8080', description: 'Alternative port' }, +]; program.parse(); ``` -## Recipe - -`source <(my-cli complete zsh)` won't be enough since the user would have to run this command each time they spin up a new shell instance. - -We suggest this approach for the end user that you as a maintainer might want to push. - -``` -my-cli completion zsh > ~/completion-for-my-cli.zsh -echo 'source ~/completion-for-my-cli.zsh' >> ~/.zshrc -``` - -For other shells: +Tab uses a standardized completion protocol that any CLI can implement: ```bash -# Bash -my-cli complete bash > ~/.bash_completion.d/my-cli -echo 'source ~/.bash_completion.d/my-cli' >> ~/.bashrc +# Generate shell completion script +my-cli complete zsh -# Fish -my-cli complete fish > ~/.config/fish/completions/my-cli.fish - -# PowerShell -my-cli complete powershell > $PROFILE.CurrentUserAllHosts +# Parse completion request (called by shell) +my-cli complete -- install --port="" ``` -## Autocompletion Server - -By integrating tab into your cli, your cli would have a new command called `complete`. This is where all the magic happens. And the shell would contact this command to get completions. That's why we call it the autocompletion server. +**Output Format:** -```zsh -my-cli complete -- --po ---port Specify the port number -:0 +``` +--port=3000 Development port +--port=8080 Production port +:4 ``` -The autocompletion server can be a standard to identify whether a package provides autocompletions. Whether running `tool complete --` would result in an output that ends with `:{Number}` (matching the pattern `/:\d+$/`). - -In situations like `my-cli dev --po` you'd have autocompletions! But in the case of `pnpm my-cli dev --po` which is what most of us use, tab does not inject autocompletions for a tool like pnpm. - -Since pnpm already has its own autocompletion [script](https://pnpm.io/completion), this provides the opportunity to check whether a package provides autocompletions and use those autocompletions if available. - -This would also have users avoid injecting autocompletions in their shell config for any tool that provides its own autocompletion script, since pnpm would already support proxying the autocompletions out of the box. +## Documentation -Other package managers like `npm` and `yarn` can decide whether to support this or not too for more universal support. +See [bombshell docs](https://bomb.sh/docs/tab/). -## Inspiration +## Contributing -- git -- [cobra](https://github.com/spf13/cobra/blob/main/shell_completions.go), without cobra, tab would have took 10x longer to build +We welcome contributions! Tab's architecture makes it easy to add support for new package managers or CLI frameworks.