telme/lib/utils/index.ts

139 lines
No EOL
3.4 KiB
TypeScript

import InvalidArgumentsError from "../errors/invalid_arguments.error";
const CLI_OPTIONS = {
versionFlags: ['--version', '-v'],
helpFlags: ['--help', '-h'],
initFlags: ['--init', '-i'],
profileFlags: ['--profile', '-p'],
messageFlags: ['--message', '-m'],
};
export class ArgParser {
static CLI_OPTIONS = CLI_OPTIONS;
static parse(testArgs: string[] = null): IRunOptions {
let cliArgs = testArgs ? testArgs.slice(2) : process.argv.slice(2);
let tokens = tokenize(cliArgs);
if (tokens.version) {
return {
mode: ERunMode.VERSION
}
} else if (tokens.help) {
return {
mode: ERunMode.HELP
}
} else if (tokens.init) {
return {
mode: ERunMode.INIT,
mode_data: {
profileName: tokens.profile
}
}
} else if (tokens.simpleMessage) {
return {
mode: ERunMode.SIMPLE_MESSAGE,
mode_data: {
profileName: tokens.profile,
message: tokens.simpleMessage
}
}
} else {
// Task
return {
mode: ERunMode.TASK_MESSAGE,
mode_data: {
profileName: tokens.profile,
command: tokens.task.cmd,
args: tokens.task.args || []
}
}
}
}
}
function tokenize(args: string[]) {
let cliArgs = args;
if (!cliArgs.length) throw new InvalidArgumentsError('Missing a command to run');
const tokens: ITokenizeArgs = { init: false, help: false, version: false };
// ['node', 'execCommand', ...];
let mode: ERunMode = ERunMode.TASK_MESSAGE;
while (cliArgs.length > 0) {
let tokenCursor = 1;
const token = cliArgs[0];
if (CLI_OPTIONS.versionFlags.indexOf(token) >= 0) {
tokens.version = true;
return tokens;
} else if (CLI_OPTIONS.helpFlags.indexOf(token) >= 0) {
tokens.help = true;
return tokens;
} else if (CLI_OPTIONS.initFlags.indexOf(token) >= 0) {
tokens.init = true;
} else if (CLI_OPTIONS.profileFlags.indexOf(token) >= 0) {
if (!cliArgs[1]) {
throw new InvalidArgumentsError('Must provide a profile name');
}
tokens.profile = cliArgs[1];
tokenCursor = 2;
} else if (CLI_OPTIONS.messageFlags.indexOf(token) >= 0) {
if (!cliArgs[1]) {
throw new InvalidArgumentsError('Must provide a message to send');
}
tokens.simpleMessage = cliArgs[1];
tokenCursor = 2
} else {
// Task
if (!cliArgs[0]) {
throw new InvalidArgumentsError('Missing a command to run');
}
tokens.task = {
cmd: cliArgs[0],
args: cliArgs.slice(1)
};
cliArgs = [];
}
if (cliArgs.length) cliArgs = cliArgs.slice(tokenCursor);
}
return tokens;
}
interface ITokenizeArgs {
version: boolean;
help: boolean;
profile?: string;
init: boolean;
simpleMessage?: string;
task?: {
cmd: string;
args?: string[]
}
}
export interface IRunOptions {
mode: ERunMode;
mode_data?: IInitProfileOptions | ISimpleMessageOptions | ITaskOptions;
}
export interface IBasicOptions {
profileName?: string;
}
export interface IInitProfileOptions extends IBasicOptions { }
export interface ISimpleMessageOptions extends IBasicOptions {
message: string;
}
export interface ITaskOptions extends IBasicOptions {
command: string;
args: string[];
}
export enum ERunMode {
VERSION,
HELP,
INIT,
SIMPLE_MESSAGE,
TASK_MESSAGE
}