Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions README.2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
> 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 '@bombsh/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 @bombsh/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.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
[![tweet-1827921103093932490](https://github.com/user-attachments/assets/21521787-7936-44be-8d3c-8214cd2fcee9)](https://x.com/karpathy/status/1827921103093932490)

# 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.
Expand Down
88 changes: 88 additions & 0 deletions bin/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#!/usr/bin/env node

import cac from 'cac';
import { script, Completion } from '../src/index.js';
import tab from '../src/cac.js';

import { setupCompletionForPackageManager } from './completion-handlers';

const packageManagers = ['npm', 'pnpm', 'yarn', 'bun'];
const shells = ['zsh', 'bash', 'fish', 'powershell'];

async function main() {
const cli = cac('tab');

// TODO: aren't these conditions are already handled by cac?
const args = process.argv.slice(2);
if (args.length >= 2 && args[1] === 'complete') {
const packageManager = args[0];

if (!packageManagers.includes(packageManager)) {
console.error(`Error: Unsupported package manager "${packageManager}"`);
console.error(
`Supported package managers: ${packageManagers.join(', ')}`
);
process.exit(1);
}

const dashIndex = process.argv.indexOf('--');
if (dashIndex !== -1) {
// TOOD: there's no Completion anymore
const completion = new Completion();
setupCompletionForPackageManager(packageManager, completion);
const toComplete = process.argv.slice(dashIndex + 1);
await completion.parse(toComplete);
process.exit(0);
} else {
console.error(`Error: Expected '--' followed by command to complete`);
console.error(
`Example: ${packageManager} exec @bombsh/tab ${packageManager} complete -- command-to-complete`
);
process.exit(1);
}
}

cli
.command(
'<packageManager> <shell>',
'Generate shell completion script for a package manager'
)
.action(async (packageManager, shell) => {
if (!packageManagers.includes(packageManager)) {
console.error(`Error: Unsupported package manager "${packageManager}"`);
console.error(
`Supported package managers: ${packageManagers.join(', ')}`
);
process.exit(1);
}

if (!shells.includes(shell)) {
console.error(`Error: Unsupported shell "${shell}"`);
console.error(`Supported shells: ${shells.join(', ')}`);
process.exit(1);
}

generateCompletionScript(packageManager, shell);
});

tab(cli);

cli.parse();
}

// function generateCompletionScript(packageManager: string, shell: string) {
// const name = packageManager;
// const executable = process.env.npm_execpath
// ? `${packageManager} exec @bombsh/tab ${packageManager}`
// : `node ${process.argv[1]} ${packageManager}`;
// script(shell as any, name, executable);
// }

function generateCompletionScript(packageManager: string, shell: string) {
const name = packageManager;
// this always points at the actual file on disk (TESTING)
const executable = `node ${process.argv[1]} ${packageManager}`;
script(shell as any, name, executable);
}

main().catch(console.error);
126 changes: 126 additions & 0 deletions bin/completion-handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// TODO: i do not see any completion functionality in this file. nothing is being provided for the defined commands of these package managers. this is a blocker for release. every each of them should be handled.
import { Completion } from '../src/index.js';
import { execSync } from 'child_process';

const DEBUG = false; // for debugging purposes

function debugLog(...args: any[]) {
if (DEBUG) {
console.error('[DEBUG]', ...args);
}
}

async function checkCliHasCompletions(
cliName: string,
packageManager: string
): Promise<boolean> {
try {
debugLog(`Checking if ${cliName} has completions via ${packageManager}`);
const command = `${packageManager} ${cliName} complete --`;
const result = execSync(command, {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore'],
timeout: 1000, // AMIR: we still havin issues with this, it still hangs if a cli doesn't have completions. longer timeout needed for shell completion system (shell → node → package manager → cli)
});
const hasCompletions = !!result.trim();
debugLog(`${cliName} supports completions: ${hasCompletions}`);
return hasCompletions;
} catch (error) {
debugLog(`Error checking completions for ${cliName}:`, error);
return false;
}
}

async function getCliCompletions(
cliName: string,
packageManager: string,
args: string[]
): Promise<string[]> {
try {
const completeArgs = args.map((arg) =>
arg.includes(' ') ? `"${arg}"` : arg
);
const completeCommand = `${packageManager} ${cliName} complete -- ${completeArgs.join(' ')}`;
debugLog(`Getting completions with command: ${completeCommand}`);

const result = execSync(completeCommand, {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore'],
timeout: 1000, // same: longer timeout needed for shell completion system (shell → node → package manager → cli)
});

const completions = result.trim().split('\n').filter(Boolean);
debugLog(`Got ${completions.length} completions from ${cliName}`);
return completions;
} catch (error) {
debugLog(`Error getting completions from ${cliName}:`, error);
return [];
}
}

export function setupCompletionForPackageManager(
packageManager: string,
completion: Completion
) {
if (packageManager === 'pnpm') {
setupPnpmCompletions(completion);
} else if (packageManager === 'npm') {
setupNpmCompletions(completion);
} else if (packageManager === 'yarn') {
setupYarnCompletions(completion);
} else if (packageManager === 'bun') {
setupBunCompletions(completion);
}

// TODO: the core functionality of tab should have nothing related to package managers. even though completion is not there anymore, but this is something to consider.
completion.setPackageManager(packageManager);
}

export function setupPnpmCompletions(completion: Completion) {
completion.addCommand('add', 'Install a package', [], async () => []);
completion.addCommand('remove', 'Remove a package', [], async () => []);
completion.addCommand(
'install',
'Install all dependencies',
[],
async () => []
);
// TODO: empty functions should be replaced with noop functions rather than creating that many empty functions
completion.addCommand('update', 'Update packages', [], async () => []);
completion.addCommand('exec', 'Execute a command', [], async () => []);
completion.addCommand('run', 'Run a script', [], async () => []);
completion.addCommand('publish', 'Publish package', [], async () => []);
completion.addCommand('test', 'Run tests', [], async () => []);
completion.addCommand('build', 'Build project', [], async () => []);
}

export function setupNpmCompletions(completion: Completion) {
completion.addCommand('install', 'Install a package', [], async () => []);
completion.addCommand('uninstall', 'Uninstall a package', [], async () => []);
completion.addCommand('run', 'Run a script', [], async () => []);
completion.addCommand('test', 'Run tests', [], async () => []);
completion.addCommand('publish', 'Publish package', [], async () => []);
completion.addCommand('update', 'Update packages', [], async () => []);
completion.addCommand('start', 'Start the application', [], async () => []);
completion.addCommand('build', 'Build project', [], async () => []);
}

export function setupYarnCompletions(completion: Completion) {
completion.addCommand('add', 'Add a package', [], async () => []);
completion.addCommand('remove', 'Remove a package', [], async () => []);
completion.addCommand('run', 'Run a script', [], async () => []);
completion.addCommand('test', 'Run tests', [], async () => []);
completion.addCommand('publish', 'Publish package', [], async () => []);
completion.addCommand('install', 'Install dependencies', [], async () => []);
completion.addCommand('build', 'Build project', [], async () => []);
}

export function setupBunCompletions(completion: Completion) {
completion.addCommand('add', 'Add a package', [], async () => []);
completion.addCommand('remove', 'Remove a package', [], async () => []);
completion.addCommand('run', 'Run a script', [], async () => []);
completion.addCommand('test', 'Run tests', [], async () => []);
completion.addCommand('install', 'Install dependencies', [], async () => []);
completion.addCommand('update', 'Update packages', [], async () => []);
completion.addCommand('build', 'Build project', [], async () => []);
}
Loading
Loading