All files / sportident-testbench-shell/src Shell.ts

59.3% Statements 51/86
47.82% Branches 11/23
69.23% Functions 18/26
58.82% Lines 50/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207                                                                                            2x         6x 6x     6x         6x       6x 11x 11x   6x 5x     5x 5x 5x 5x 5x 4x   4x     1x           1x   6x       10x           11x               11x   28x 5x 5x   23x     23x     23x       23x 23x 23x   11x                                                                                           11x 11x 28x 28x 28x 5x   23x   11x       34x 34x 321x 321x 28x   293x     34x         22x 608x        
import {ISiDevice, ISiDeviceDriverData} from 'sportident/lib/SiDevice/ISiDevice';
import {ISiExternalApplication} from './ISiExternalApplication';
 
export interface ShellUserInterface {
    getChar: () => number|undefined;
    putChar: (char: number) => void;
}
 
export interface ShellCommand {
    autocomplete: (args: string[]) => string[];
    validateArgs: (context: ShellCommandContext) => boolean;
    run: (context: ShellCommandContext) => Promise<void>;
    printUsage: (context: ShellCommandContext) => void;
}
 
export interface ShellCommandContext {
    args: string[];
    getChar: () => number|undefined;
    waitChar: () => Promise<number>;
    putChar: (char: number) => void;
    getLine: () => Promise<string>;
    putString: (line: string) => void;
    env: ShellEnv;
}
 
export interface AllShellOptions {
    prompt: string;
    initialEnv: ShellEnv;
}
 
export interface ShellOptions {
    prompt?: string;
    initialEnv?: ShellEnv;
}
 
type ShellEnv = {[varName: string]: unknown}&{
    externalApplication?: {new(url: string): ISiExternalApplication},
    device?: ISiDevice<ISiDeviceDriverData<unknown>>,
};
 
type ShellInputParser<T> = (
    contentSoFar: T,
    newChar: number,
    ui: ShellUserInterface,
) => [boolean, T];
 
export class Shell {
    private env: ShellEnv;
    private options: AllShellOptions;
 
    constructor(
                public ui: ShellUserInterface,
                private commands: {[commandName: string]: ShellCommand},
                options: ShellOptions = {},
    ) {
        this.options = {
            initialEnv: {},
            prompt: '$ ',
            ...options,
        };
        this.env = {...options.initialEnv};
    }
 
    run(): Promise<unknown> {
        const promptForNewCommand = () => {
            this.putString(this.options.prompt);
            return this.getLine(this.autocompleteCommand.bind(this));
        };
        const loop = (commandStr: string): Promise<string> => {
            Iif (commandStr === 'exit') {
                return Promise.resolve('');
            }
            const args = commandStr.split(/\s+/);
            const command = this.commands[args[0]];
            if (command) {
                const isValid = command.validateArgs(this.getCommandContext(args));
                if (isValid) {
                    return command.run(this.getCommandContext(args))
                        .catch(() => undefined)
                        .then(() => promptForNewCommand())
                        .then(loop);
                }
                command.printUsage(this.getCommandContext(args));
            } else E{
                this.putString(`Unknown command: ${args[0]}\n`);
                const availableCommands = Object.keys(this.commands).join(', ');
                this.putString(`Available commands: ${availableCommands}\n`);
            }
            return promptForNewCommand().then(loop);
        };
        return promptForNewCommand().then(loop);
    }
 
    getCommandContext(args: string[]): ShellCommandContext {
        return {
            args: args,
            getChar: this.ui.getChar,
            waitChar: () => this.waitChar(),
            putChar: this.ui.putChar,
            getLine: () => this.getLine(),
            putString: (str: string) => this.putString(str),
            env: this.env,
        };
    }
 
    getLine(
        autocomplete?: (commandStr: string) => [boolean, string],
    ): Promise<string> {
        return this.parseInput(
            (content: string, nextChar: number, ui: ShellUserInterface) => {
                if (nextChar === 13 || nextChar === 10) { // Enter
                    ui.putChar(nextChar);
                    return [true, content];
                }
                Iif (nextChar === 27 || nextChar === 3) { // Escape / Ctrl-C
                    return [true, 'exit'];
                }
                Iif (nextChar === 9 && autocomplete !== undefined) { // Tab
                    return autocomplete(content);
                }
                Iif (nextChar === 8) { // Backspace
                    ui.putChar(nextChar);
                    return [false, content.substr(0, content.length - 1)];
                }
                const newContent = `${content}${String.fromCharCode(nextChar)}`;
                this.ui.putChar(nextChar);
                return [false, newContent];
            },
            () => '',
        );
    }
 
    autocompleteCommand(commandStr: string): [boolean, string] {
        const args = commandStr.split(/\s+/);
        Iif (args.length === 1) {
            const options = this.autocompleteCommandName(args[0]);
            Iif (options.length === 1) {
                const newContent = options[0];
                const rest = newContent.substr(commandStr.length);
                [...rest].forEach((char) => {
                    this.ui.putChar(char.charCodeAt(0));
                });
                return [false, newContent];
            }
        }
        Iif (args.length > 1) {
            const command = this.commands[args[0]];
            Iif (command) {
                const options = command.autocomplete(args.slice(1));
                Iif (options.length === 1) {
                    const existingLastArg = args[args.length - 1];
                    const lengthToPreserve = commandStr.length - existingLastArg.length;
                    const newContent = `${commandStr.substr(0, lengthToPreserve)}${options[0]}`;
                    const rest = options[0].substr(existingLastArg.length);
                    [...rest].forEach((char) => {
                        this.ui.putChar(char.charCodeAt(0));
                    });
                    return [false, newContent];
                }
            }
        }
        return [false, commandStr];
    }
 
    autocompleteCommandName(arg: string): string[] {
        return Object.keys(this.commands).filter(
            (commandName) => commandName.substr(0, arg.length) === arg,
        );
    }
 
    parseInput<T>(
        parser: ShellInputParser<T>,
        init: () => T,
    ): Promise<T> {
        let content = init();
        const loop = (nextChar: number): number|Promise<number> => {
            const [shouldExit, newContent] = parser(content, nextChar, this.ui);
            content = newContent;
            if (shouldExit) {
                return nextChar;
            }
            return this.waitChar().then(loop);
        };
        return this.waitChar().then(loop).then(() => content);
    }
 
    waitChar(): Promise<number> {
        return new Promise((resolve) => {
            const poll = () => {
                const char = this.ui.getChar();
                if (char) {
                    resolve(char);
                } else {
                    setTimeout(poll, 10);
                }
            };
            poll();
        });
    }
 
    putString(strToPut: string): void {
        [...strToPut].forEach((char: string) => {
            this.ui.putChar(char.charCodeAt(0));
        });
    }
}