93 lines
2.3 KiB
TypeScript
93 lines
2.3 KiB
TypeScript
import { InboundMessage, ParsedCommand } from './types';
|
|
|
|
export class CommandError extends Error {}
|
|
|
|
/**
|
|
* 命令解析器,移植自 Rust 版 command_parser:
|
|
* - 支持单/双引号、双引号内反斜杠转义
|
|
* - --key=value / --key value / --flag(无值则为 "true")
|
|
* 第一个 token 为命令名,其余为位置参数。
|
|
*/
|
|
export function tokenize(input: string): string[] {
|
|
const tokens: string[] = [];
|
|
let buf = '';
|
|
let inSingle = false;
|
|
let inDouble = false;
|
|
|
|
for (let i = 0; i < input.length; i++) {
|
|
const ch = input[i];
|
|
if (ch === "'" && !inDouble) {
|
|
inSingle = !inSingle;
|
|
} else if (ch === '"' && !inSingle) {
|
|
inDouble = !inDouble;
|
|
} else if (ch === '\\' && inDouble) {
|
|
const next = input[i + 1];
|
|
if (next === undefined) {
|
|
throw new CommandError('dangling escape');
|
|
}
|
|
buf += next;
|
|
i++;
|
|
} else if (/\s/.test(ch) && !inSingle && !inDouble) {
|
|
if (buf.length > 0) {
|
|
tokens.push(buf);
|
|
buf = '';
|
|
}
|
|
} else {
|
|
buf += ch;
|
|
}
|
|
}
|
|
|
|
if (inSingle || inDouble) {
|
|
throw new CommandError('unterminated quote');
|
|
}
|
|
if (buf.length > 0) {
|
|
tokens.push(buf);
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
export function parseCommand(raw: InboundMessage, text: string): ParsedCommand {
|
|
const tokens = tokenize(text);
|
|
if (tokens.length === 0) {
|
|
throw new CommandError('empty command');
|
|
}
|
|
|
|
const command = tokens[0];
|
|
const args: string[] = [];
|
|
const options: Record<string, string> = {};
|
|
|
|
let i = 1;
|
|
while (i < tokens.length) {
|
|
const token = tokens[i];
|
|
if (token.startsWith('--')) {
|
|
const body = token.slice(2);
|
|
if (body.length === 0) {
|
|
throw new CommandError('invalid option: --');
|
|
}
|
|
const eq = body.indexOf('=');
|
|
if (eq >= 0) {
|
|
const key = body.slice(0, eq);
|
|
if (key.length === 0) {
|
|
throw new CommandError(`invalid option key in '--${body}'`);
|
|
}
|
|
options[key] = body.slice(eq + 1);
|
|
i++;
|
|
continue;
|
|
}
|
|
const next = tokens[i + 1];
|
|
if (next !== undefined && !next.startsWith('-')) {
|
|
options[body] = next;
|
|
i += 2;
|
|
} else {
|
|
options[body] = 'true';
|
|
i++;
|
|
}
|
|
continue;
|
|
}
|
|
args.push(token);
|
|
i++;
|
|
}
|
|
|
|
return { raw, command, args, options };
|
|
}
|