diff --git a/bin/cli.ts b/bin/cli.ts index d204be5..80887cb 100644 --- a/bin/cli.ts +++ b/bin/cli.ts @@ -1,10 +1,11 @@ #!/usr/bin/env node import cac from 'cac'; -import { script, Completion } from '../src/index.js'; +import { script } from '../src/t.js'; import tab from '../src/cac.js'; import { setupCompletionForPackageManager } from './completion-handlers'; +import { PackageManagerCompletion } from './package-manager-completion.js'; const packageManagers = ['npm', 'pnpm', 'yarn', 'bun']; const shells = ['zsh', 'bash', 'fish', 'powershell']; @@ -27,8 +28,8 @@ async function main() { const dashIndex = process.argv.indexOf('--'); if (dashIndex !== -1) { - // TOOD: there's no Completion anymore - const completion = new Completion(); + // Use the new PackageManagerCompletion wrapper + const completion = new PackageManagerCompletion(packageManager); setupCompletionForPackageManager(packageManager, completion); const toComplete = process.argv.slice(dashIndex + 1); await completion.parse(toComplete); diff --git a/bin/completion-handlers.ts b/bin/completion-handlers.ts index c272213..3820e0c 100644 --- a/bin/completion-handlers.ts +++ b/bin/completion-handlers.ts @@ -1,11 +1,9 @@ // 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'; - -const noopCompletion = async () => []; +import { PackageManagerCompletion } from './package-manager-completion.js'; export function setupCompletionForPackageManager( packageManager: string, - completion: Completion + completion: PackageManagerCompletion ) { if (packageManager === 'pnpm') { setupPnpmCompletions(completion); @@ -17,54 +15,59 @@ export function setupCompletionForPackageManager( 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); + // Note: Package manager logic is now handled by PackageManagerCompletion wrapper } -export function setupPnpmCompletions(completion: Completion) { - completion.addCommand('add', 'Install a package', [], noopCompletion); - completion.addCommand('remove', 'Remove a package', [], noopCompletion); - completion.addCommand( - 'install', - 'Install all dependencies', - [], - noopCompletion - ); - completion.addCommand('update', 'Update packages', [], noopCompletion); - completion.addCommand('exec', 'Execute a command', [], noopCompletion); - completion.addCommand('run', 'Run a script', [], noopCompletion); - completion.addCommand('publish', 'Publish package', [], noopCompletion); - completion.addCommand('test', 'Run tests', [], noopCompletion); - completion.addCommand('build', 'Build project', [], noopCompletion); +export function setupPnpmCompletions(completion: PackageManagerCompletion) { + completion.command('add', 'Install a package'); + completion.command('remove', 'Remove a package'); + completion.command('install', 'Install dependencies'); + completion.command('update', 'Update dependencies'); + completion.command('run', 'Run a script'); + completion.command('exec', 'Execute a command'); + completion.command('dlx', 'Run a package without installing'); + completion.command('create', 'Create a new project'); + completion.command('init', 'Initialize a new project'); + completion.command('publish', 'Publish the package'); + completion.command('pack', 'Create a tarball'); + completion.command('link', 'Link a package'); + completion.command('unlink', 'Unlink a package'); + completion.command('outdated', 'Check for outdated packages'); + completion.command('audit', 'Run security audit'); + completion.command('list', 'List installed packages'); } -export function setupNpmCompletions(completion: Completion) { - completion.addCommand('install', 'Install a package', [], noopCompletion); - completion.addCommand('uninstall', 'Uninstall a package', [], noopCompletion); - completion.addCommand('run', 'Run a script', [], noopCompletion); - completion.addCommand('test', 'Run tests', [], noopCompletion); - completion.addCommand('publish', 'Publish package', [], noopCompletion); - completion.addCommand('update', 'Update packages', [], noopCompletion); - completion.addCommand('start', 'Start the application', [], noopCompletion); - completion.addCommand('build', 'Build project', [], noopCompletion); +export function setupNpmCompletions(completion: PackageManagerCompletion) { + completion.command('install', 'Install a package'); + completion.command('uninstall', 'Remove a package'); + completion.command('update', 'Update dependencies'); + completion.command('run', 'Run a script'); + completion.command('exec', 'Execute a command'); + completion.command('init', 'Initialize a new project'); + completion.command('publish', 'Publish the package'); + completion.command('pack', 'Create a tarball'); + completion.command('link', 'Link a package'); + completion.command('unlink', 'Unlink a package'); } -export function setupYarnCompletions(completion: Completion) { - completion.addCommand('add', 'Add a package', [], noopCompletion); - completion.addCommand('remove', 'Remove a package', [], noopCompletion); - completion.addCommand('run', 'Run a script', [], noopCompletion); - completion.addCommand('test', 'Run tests', [], noopCompletion); - completion.addCommand('publish', 'Publish package', [], noopCompletion); - completion.addCommand('install', 'Install dependencies', [], noopCompletion); - completion.addCommand('build', 'Build project', [], noopCompletion); +export function setupYarnCompletions(completion: PackageManagerCompletion) { + completion.command('add', 'Install a package'); + completion.command('remove', 'Remove a package'); + completion.command('install', 'Install dependencies'); + completion.command('upgrade', 'Update dependencies'); + completion.command('run', 'Run a script'); + completion.command('exec', 'Execute a command'); + completion.command('create', 'Create a new project'); + completion.command('init', 'Initialize a new project'); } -export function setupBunCompletions(completion: Completion) { - completion.addCommand('add', 'Add a package', [], noopCompletion); - completion.addCommand('remove', 'Remove a package', [], noopCompletion); - completion.addCommand('run', 'Run a script', [], noopCompletion); - completion.addCommand('test', 'Run tests', [], noopCompletion); - completion.addCommand('install', 'Install dependencies', [], noopCompletion); - completion.addCommand('update', 'Update packages', [], noopCompletion); - completion.addCommand('build', 'Build project', [], noopCompletion); +export function setupBunCompletions(completion: PackageManagerCompletion) { + completion.command('add', 'Install a package'); + completion.command('remove', 'Remove a package'); + completion.command('install', 'Install dependencies'); + completion.command('update', 'Update dependencies'); + completion.command('run', 'Run a script'); + completion.command('x', 'Execute a command'); + completion.command('create', 'Create a new project'); + completion.command('init', 'Initialize a new project'); } diff --git a/bin/package-manager-completion.ts b/bin/package-manager-completion.ts new file mode 100644 index 0000000..964d252 --- /dev/null +++ b/bin/package-manager-completion.ts @@ -0,0 +1,115 @@ +import { execSync } from 'child_process'; +import { RootCommand } from '../src/t.js'; + +function debugLog(...args: any[]) { + if (process.env.DEBUG) { + console.error('[DEBUG]', ...args); + } +} + +async function checkCliHasCompletions( + cliName: string, + packageManager: string +): Promise { + 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, + }); + 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 { + 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, + }); + + 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 []; + } +} + +/** + * Package Manager Completion Wrapper + * + * This extends RootCommand and adds package manager-specific logic. + * It acts as a layer on top of the core tab library. + */ +export class PackageManagerCompletion extends RootCommand { + private packageManager: string; + + constructor(packageManager: string) { + super(); + this.packageManager = packageManager; + } + + // Enhanced parse method with package manager logic + async parse(args: string[]) { + // Handle package manager completions first + if (args.length >= 1 && args[0].trim() !== '') { + const potentialCliName = args[0]; + const knownCommands = [...this.commands.keys()]; + + if (!knownCommands.includes(potentialCliName)) { + const hasCompletions = await checkCliHasCompletions( + potentialCliName, + this.packageManager + ); + + if (hasCompletions) { + const cliArgs = args.slice(1); + const suggestions = await getCliCompletions( + potentialCliName, + this.packageManager, + cliArgs + ); + + if (suggestions.length > 0) { + // Print completions directly in the same format as the core library + for (const suggestion of suggestions) { + if (suggestion.startsWith(':')) continue; + + if (suggestion.includes('\t')) { + const [value, description] = suggestion.split('\t'); + console.log(`${value}\t${description}`); + } else { + console.log(suggestion); + } + } + console.log(':4'); // Shell completion directive (NoFileComp) + return; + } + } + } + } + + // Fall back to regular completion logic (shows basic package manager commands) + return super.parse(args); + } +} diff --git a/examples/demo.commander.ts b/examples/demo.commander.ts index db8169a..7582a39 100644 --- a/examples/demo.commander.ts +++ b/examples/demo.commander.ts @@ -61,13 +61,9 @@ const completion = tab(program); // Configure custom completions for (const command of completion.commands.values()) { - if (command.name === 'lint') { - command.handler = () => { - return [ - { value: 'src/**/*.ts', description: 'TypeScript source files' }, - { value: 'tests/**/*.ts', description: 'Test files' }, - ]; - }; + if (command.value === 'lint') { + // Note: Direct handler assignment is not supported in the current API + // Custom completion logic would need to be implemented differently } for (const [option, config] of command.options.entries()) { diff --git a/package.json b/package.json index 16d3296..b7b3b9f 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "@bombsh/tab", "version": "0.0.0", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", + "main": "./dist/t.js", + "types": "./dist/t.d.ts", "type": "module", "bin": { "tab": "./dist/bin/cli.js" @@ -41,9 +41,9 @@ }, "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.js", - "require": "./dist/index.cjs" + "types": "./dist/t.d.ts", + "import": "./dist/t.js", + "require": "./dist/t.cjs" }, "./citty": { "types": "./dist/citty.d.ts", diff --git a/src/bash.ts b/src/bash.ts index 87b9f03..3e3a4f2 100644 --- a/src/bash.ts +++ b/src/bash.ts @@ -1,4 +1,4 @@ -import { ShellCompDirective } from './'; +import { ShellCompDirective } from './t'; export function generate(name: string, exec: string): string { // Replace '-' and ':' with '_' for variable names diff --git a/src/commander.ts b/src/commander.ts index 7a9d842..d3c083a 100644 --- a/src/commander.ts +++ b/src/commander.ts @@ -2,8 +2,8 @@ import * as zsh from './zsh'; import * as bash from './bash'; import * as fish from './fish'; import * as powershell from './powershell'; -import type { Command as CommanderCommand } from 'commander'; -import { Completion } from './'; +import type { Command as CommanderCommand, ParseOptions } from 'commander'; +import t, { RootCommand } from './t'; import { assertDoubleDashes } from './shared'; const execPath = process.execPath; @@ -18,34 +18,20 @@ function quoteIfNeeded(path: string): string { return path.includes(' ') ? `'${path}'` : path; } -export default function tab(instance: CommanderCommand): Completion { - const completion = new Completion(); +export default function tab(instance: CommanderCommand): RootCommand { const programName = instance.name(); // Process the root command - processRootCommand(completion, instance, programName); + processRootCommand(instance, programName); // Process all subcommands - processSubcommands(completion, instance, programName); + processSubcommands(instance, programName); - // Add the complete command + // Add the complete command for normal shell script generation instance .command('complete [shell]') - .allowUnknownOption(true) .description('Generate shell completion scripts') - .action(async (shell, options) => { - // Check if there are arguments after -- - const dashDashIndex = process.argv.indexOf('--'); - let extra: string[] = []; - - if (dashDashIndex !== -1) { - extra = process.argv.slice(dashDashIndex + 1); - // If shell is actually part of the extra args, adjust accordingly - if (shell && extra.length > 0 && shell === '--') { - shell = undefined; - } - } - + .action(async (shell) => { switch (shell) { case 'zsh': { const script = zsh.generate(programName, x); @@ -80,26 +66,46 @@ export default function tab(instance: CommanderCommand): Completion { break; } default: { - assertDoubleDashes(programName); - - // Parse current command context for autocompletion - return completion.parse(extra); + console.error(`Unknown shell: ${shell}`); + console.error('Supported shells: zsh, bash, fish, powershell'); + process.exit(1); } } }); - return completion; + // Override the parse method to handle completion requests before normal parsing + const originalParse = instance.parse.bind(instance); + instance.parse = function (argv?: readonly string[], options?: ParseOptions) { + const args = argv || process.argv; + const completeIndex = args.findIndex((arg) => arg === 'complete'); + const dashDashIndex = args.findIndex((arg) => arg === '--'); + + if ( + completeIndex !== -1 && + dashDashIndex !== -1 && + dashDashIndex > completeIndex + ) { + // This is a completion request, handle it directly + const extra = args.slice(dashDashIndex + 1); + + // Handle the completion directly + assertDoubleDashes(programName); + t.parse(extra); + return instance; + } + + // Normal parsing + return originalParse(argv, options); + }; + + return t; } function processRootCommand( - completion: Completion, command: CommanderCommand, programName: string ): void { - // Add the root command - completion.addCommand('', command.description() || '', [], async () => []); - - // Add root command options + // Add root command options to the root t instance for (const option of command.options) { // Extract short flag from the name if it exists (e.g., "-c, --config" -> "c") const flags = option.flags; @@ -107,19 +113,16 @@ function processRootCommand( const longFlag = flags.match(/--([a-zA-Z0-9-]+)/)?.[1]; if (longFlag) { - completion.addOption( - '', - `--${longFlag}`, - option.description || '', - async () => [], - shortFlag - ); + if (shortFlag) { + t.option(longFlag, option.description || '', shortFlag); + } else { + t.option(longFlag, option.description || ''); + } } } } function processSubcommands( - completion: Completion, rootCommand: CommanderCommand, programName: string ): void { @@ -133,14 +136,8 @@ function processSubcommands( for (const [path, cmd] of commandMap.entries()) { if (path === '') continue; // Skip root command, already processed - // Extract positional arguments from usage - const usage = cmd.usage(); - const args = (usage?.match(/\[.*?\]|<.*?>/g) || []).map((arg) => - arg.startsWith('[') - ); // true if optional (wrapped in []) - - // Add command to completion - completion.addCommand(path, cmd.description() || '', args, async () => []); + // Add command using t.ts API + const command = t.command(path, cmd.description() || ''); // Add command options for (const option of cmd.options) { @@ -150,29 +147,10 @@ function processSubcommands( const longFlag = flags.match(/--([a-zA-Z0-9-]+)/)?.[1]; if (longFlag) { - completion.addOption( - path, - `--${longFlag}`, - option.description || '', - async () => [], - shortFlag - ); - } - } - - // For commands with subcommands, add a special handler - if (cmd.commands.length > 0) { - const subcommandNames = cmd.commands - .filter((subcmd) => subcmd.name() !== 'complete') - .map((subcmd) => ({ - value: subcmd.name(), - description: subcmd.description() || '', - })); - - if (subcommandNames.length > 0) { - const cmdObj = completion.commands.get(path); - if (cmdObj) { - cmdObj.handler = async () => subcommandNames; + if (shortFlag) { + command.option(longFlag, option.description || '', shortFlag); + } else { + command.option(longFlag, option.description || ''); } } } diff --git a/src/fish.ts b/src/fish.ts index 70e1d4f..e510bf0 100644 --- a/src/fish.ts +++ b/src/fish.ts @@ -1,4 +1,4 @@ -import { ShellCompDirective } from './'; +import { ShellCompDirective } from './t'; export function generate(name: string, exec: string): string { // Replace '-' and ':' with '_' for variable names diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index 6bcca5f..0000000 --- a/src/index.ts +++ /dev/null @@ -1,520 +0,0 @@ -import * as zsh from './zsh'; -import * as bash from './bash'; -import * as fish from './fish'; -import * as powershell from './powershell'; -import { execSync } from 'child_process'; -import { Completion as CompletionItem } from './t'; - -const DEBUG = false; - -function debugLog(...args: unknown[]) { - if (DEBUG) { - console.error('[DEBUG]', ...args); - } -} - -async function checkCliHasCompletions( - cliName: string, - packageManager: string -): Promise { - 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, - }); - 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 { - 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, - }); - - 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 []; - } -} - -// ShellCompRequestCmd is the name of the hidden command that is used to request -// completion results from the program. It is used by the shell completion scripts. -export const ShellCompRequestCmd: string = '__complete'; - -// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request -// completion results without their description. It is used by the shell completion scripts. -export const ShellCompNoDescRequestCmd: string = '__completeNoDesc'; - -// ShellCompDirective is a bit map representing the different behaviors the shell -// can be instructed to have once completions have been provided. -export const ShellCompDirective = { - // ShellCompDirectiveError indicates an error occurred and completions should be ignored. - ShellCompDirectiveError: 1 << 0, - - // ShellCompDirectiveNoSpace indicates that the shell should not add a space - // after the completion even if there is a single completion provided. - ShellCompDirectiveNoSpace: 1 << 1, - - // ShellCompDirectiveNoFileComp indicates that the shell should not provide - // file completion even when no completion is provided. - ShellCompDirectiveNoFileComp: 1 << 2, - - // ShellCompDirectiveFilterFileExt indicates that the provided completions - // should be used as file extension filters. - // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename() - // is a shortcut to using this directive explicitly. The BashCompFilenameExt - // annotation can also be used to obtain the same behavior for flags. - ShellCompDirectiveFilterFileExt: 1 << 3, - - // ShellCompDirectiveFilterDirs indicates that only directory names should - // be provided in file completion. To request directory names within another - // directory, the returned completions should specify the directory within - // which to search. The BashCompSubdirsInDir annotation can be used to - // obtain the same behavior but only for flags. - ShellCompDirectiveFilterDirs: 1 << 4, - - // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order - // in which the completions are provided. - ShellCompDirectiveKeepOrder: 1 << 5, - - // =========================================================================== - - // All directives using iota (or equivalent in Go) should be above this one. - // For internal use. - shellCompDirectiveMaxValue: 1 << 6, - - // ShellCompDirectiveDefault indicates to let the shell perform its default - // behavior after completions have been provided. - // This one must be last to avoid messing up the iota count. - ShellCompDirectiveDefault: 0, -}; - -export type Positional = { - required: boolean; - variadic: boolean; - completion: Handler; -}; - -type CompletionResult = { - items: CompletionItem[]; - suppressDefault: boolean; -}; - -export type Handler = ( - previousArgs: string[], - toComplete: string, - endsWithSpace: boolean -) => CompletionItem[] | Promise; - -type Option = { - description: string; - handler: Handler; - alias?: string; -}; - -type Command = { - name: string; - description: string; - args: boolean[]; - handler: Handler; - options: Map; - parent?: Command; -}; - -export class Completion { - commands = new Map(); - completions: CompletionItem[] = []; - directive = ShellCompDirective.ShellCompDirectiveDefault; - result: CompletionResult = { items: [], suppressDefault: false }; - private packageManager: string | null = null; - - setPackageManager(packageManager: string) { - this.packageManager = packageManager; - } - - // vite [...files] - // args: [false, false, true], only the last argument can be variadic - addCommand( - name: string, - description: string, - args: boolean[], - handler: Handler, - parent?: string - ) { - const key = parent ? `${parent} ${name}` : name; - this.commands.set(key, { - name: key, - description, - args, - handler, - options: new Map(), - parent: parent ? this.commands.get(parent) : undefined, - }); - return key; - } - - // --port - addOption( - command: string, - option: string, - description: string, - handler: Handler, - alias?: string - ) { - const cmd = this.commands.get(command); - if (!cmd) { - throw new Error(`Command ${command} not found.`); - } - cmd.options.set(option, { description, handler, alias }); - return option; - } - - // TODO: this should be aware of boolean args and stuff - private stripOptions(args: string[]): string[] { - const parts: string[] = []; - let option = false; - for (const k of args) { - if (k.startsWith('-')) { - option = true; - continue; - } - if (option) { - option = false; - continue; - } - parts.push(k); - } - return parts; - } - - private matchCommand(args: string[]): [Command, string[]] { - args = this.stripOptions(args); - const parts: string[] = []; - let remaining: string[] = []; - // TODO (43081j): we should probably remove this non-null assertion and - // throw if the `''` command doesn't exist - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - let matched: Command = this.commands.get('')!; - for (let i = 0; i < args.length; i++) { - const k = args[i]; - parts.push(k); - const potential = this.commands.get(parts.join(' ')); - - if (potential) { - matched = potential; - } else { - remaining = args.slice(i, args.length); - break; - } - } - return [matched, remaining]; - } - - async parse(args: string[]) { - this.result = { items: [], suppressDefault: false }; - - // TODO: i did not notice this, this should not be handled here at all. package manager completions are something on top of this. just like any other completion system that is going to be built on top of tab. - // Handle package manager completions first - if (this.packageManager && args.length >= 1) { - const potentialCliName = args[0]; - const knownCommands = [...this.commands.keys()]; - - if (!knownCommands.includes(potentialCliName)) { - const hasCompletions = await checkCliHasCompletions( - potentialCliName, - this.packageManager - ); - - if (hasCompletions) { - const cliArgs = args.slice(1); - const suggestions = await getCliCompletions( - potentialCliName, - this.packageManager, - cliArgs - ); - - if (suggestions.length > 0) { - this.result.suppressDefault = true; - - for (const suggestion of suggestions) { - if (suggestion.startsWith(':')) continue; - - if (suggestion.includes('\t')) { - const [value, description] = suggestion.split('\t'); - this.result.items.push({ value, description }); - } else { - this.result.items.push({ value: suggestion }); - } - } - - this.completions = this.result.items; - this.complete(''); - return; - } - } - } - } - - const endsWithSpace = args[args.length - 1] === ''; - - if (endsWithSpace) { - args.pop(); - } - - let toComplete = args[args.length - 1] || ''; - const previousArgs = args.slice(0, -1); - - if (endsWithSpace) { - previousArgs.push(toComplete); - toComplete = ''; - } - - const [matchedCommand] = this.matchCommand(previousArgs); - - const lastPrevArg = previousArgs[previousArgs.length - 1]; - - // 1. Handle flag/option completion - if (this.shouldCompleteFlags(lastPrevArg, toComplete, endsWithSpace)) { - await this.handleFlagCompletion( - matchedCommand, - previousArgs, - toComplete, - endsWithSpace, - lastPrevArg - ); - } else { - // 2. Handle command/subcommand completion - if (this.shouldCompleteCommands(toComplete, endsWithSpace)) { - await this.handleCommandCompletion(previousArgs, toComplete); - } - // 3. Handle positional arguments - if (matchedCommand && matchedCommand.args.length > 0) { - await this.handlePositionalCompletion( - matchedCommand, - previousArgs, - toComplete, - endsWithSpace - ); - } - } - this.complete(toComplete); - } - - private complete(toComplete: string) { - this.directive = ShellCompDirective.ShellCompDirectiveNoFileComp; - - const seen = new Set(); - this.completions - .filter((comp) => { - if (seen.has(comp.value)) return false; - seen.add(comp.value); - return true; - }) - .filter((comp) => comp.value.startsWith(toComplete)) - .forEach((comp) => - console.log(`${comp.value}\t${comp.description ?? ''}`) - ); - console.log(`:${this.directive}`); - } - - private shouldCompleteFlags( - lastPrevArg: string | undefined, - toComplete: string, - endsWithSpace: boolean - ): boolean { - return ( - lastPrevArg?.startsWith('--') || - lastPrevArg?.startsWith('-') || - toComplete.startsWith('--') || - toComplete.startsWith('-') - ); - } - - private shouldCompleteCommands( - toComplete: string, - endsWithSpace: boolean - ): boolean { - return !toComplete.startsWith('-'); - } - - private async handleFlagCompletion( - command: Command, - previousArgs: string[], - toComplete: string, - endsWithSpace: boolean, - lastPrevArg: string | undefined - ) { - // Handle flag value completion - let flagName: string | undefined; - let valueToComplete = toComplete; - - if (toComplete.includes('=')) { - // Handle --flag=value or -f=value case - const parts = toComplete.split('='); - flagName = parts[0]; - valueToComplete = parts[1] || ''; - } else if (lastPrevArg?.startsWith('-')) { - // Handle --flag value or -f value case - flagName = lastPrevArg; - } - - if (flagName) { - // Try to find the option by long name or alias - let option = command.options.get(flagName); - if (!option) { - // If not found by direct match, try to find by alias - for (const [name, opt] of command.options) { - if (opt.alias && `-${opt.alias}` === flagName) { - option = opt; - flagName = name; // Use the long name for completion - break; - } - } - } - - if (option) { - const suggestions = await option.handler( - previousArgs, - valueToComplete, - endsWithSpace - ); - if (toComplete.includes('=')) { - // Reconstruct the full flag=value format - this.completions = suggestions.map((suggestion) => ({ - value: `${flagName}=${suggestion.value}`, - description: suggestion.description, - })); - } else { - this.completions.push(...suggestions); - } - } - return; - } - - // Handle flag name completion - if (toComplete.startsWith('-')) { - const isShortFlag = - toComplete.startsWith('-') && !toComplete.startsWith('--'); - - for (const [name, option] of command.options) { - // For short flags (-), only show aliases - if (isShortFlag) { - if (option.alias && `-${option.alias}`.startsWith(toComplete)) { - this.completions.push({ - value: `-${option.alias}`, - description: option.description, - }); - } - } - // For long flags (--), show the full names - else if (name.startsWith(toComplete)) { - this.completions.push({ - value: name, - description: option.description, - }); - } - } - } - } - - private async handleCommandCompletion( - previousArgs: string[], - toComplete: string - ) { - const commandParts = [...previousArgs].filter(Boolean); - - for (const [k, command] of this.commands) { - if (k === '') continue; - - const parts = k.split(' '); - - let match = true; - let i = 0; - - while (i < commandParts.length) { - if (parts[i] !== commandParts[i]) { - match = false; - break; - } - i++; - } - - if (match && parts[i]?.startsWith(toComplete)) { - this.completions.push({ - value: parts[i], - description: command.description, - }); - } - } - } - - private async handlePositionalCompletion( - command: Command, - previousArgs: string[], - toComplete: string, - endsWithSpace: boolean - ) { - const suggestions = await command.handler( - previousArgs, - toComplete, - endsWithSpace - ); - this.completions.push(...suggestions); - } -} - -export function script( - shell: 'zsh' | 'bash' | 'fish' | 'powershell', - name: string, - x: string -) { - switch (shell) { - case 'zsh': { - const script = zsh.generate(name, x); - console.log(script); - break; - } - case 'bash': { - const script = bash.generate(name, x); - console.log(script); - break; - } - case 'fish': { - const script = fish.generate(name, x); - console.log(script); - break; - } - case 'powershell': { - const script = powershell.generate(name, x); - console.log(script); - break; - } - default: { - throw new Error(`Unsupported shell: ${shell}`); - } - } -} diff --git a/src/powershell.ts b/src/powershell.ts index ffc7f4b..a2337c3 100644 --- a/src/powershell.ts +++ b/src/powershell.ts @@ -1,4 +1,4 @@ -import { ShellCompDirective } from './'; +import { ShellCompDirective } from './t'; // TODO: issue with -- -- completions diff --git a/src/t.ts b/src/t.ts index a38b215..65eda28 100644 --- a/src/t.ts +++ b/src/t.ts @@ -1,5 +1,5 @@ // Shell directive constants -const ShellCompDirective = { +export const ShellCompDirective = { ShellCompDirectiveError: 1 << 0, ShellCompDirectiveNoSpace: 1 << 1, ShellCompDirectiveNoFileComp: 1 << 2, @@ -541,4 +541,9 @@ export class RootCommand extends Command { const t = new RootCommand(); +// TODO: re-check the below +export function script(shell: string, name: string, executable: string) { + t.setup(name, executable, shell); +} + export default t; diff --git a/src/zsh.ts b/src/zsh.ts index 4a70d2d..677e3d3 100644 --- a/src/zsh.ts +++ b/src/zsh.ts @@ -1,4 +1,4 @@ -import { ShellCompDirective } from './'; +import { ShellCompDirective } from './t'; export function generate(name: string, exec: string) { return `#compdef ${name} diff --git a/tests/shell.test.ts b/tests/shell.test.ts index f198e72..b65c4ec 100644 --- a/tests/shell.test.ts +++ b/tests/shell.test.ts @@ -3,7 +3,7 @@ import * as fish from '../src/fish'; import * as bash from '../src/bash'; import * as zsh from '../src/zsh'; import * as powershell from '../src/powershell'; -import { ShellCompDirective } from '../src'; +import { ShellCompDirective } from '../src/t'; describe('shell completion generators', () => { const name = 'testcli'; diff --git a/tsdown.config.ts b/tsdown.config.ts index fb7a5ab..a29c942 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from 'tsdown'; export default defineConfig({ entry: [ - 'src/index.ts', + 'src/t.ts', 'src/citty.ts', 'src/cac.ts', 'src/commander.ts',