import { ansi } from './ansi'; import type { ISize } from './callback'; /** * Collection of environment variables that are known to a shell and are passed in and out of * commands. */ export class Environment extends Map { constructor(color: boolean, shellId: string, browsingContextId: string | undefined) { super(); if (shellId) { this.set('COCKLE_SHELL_ID', shellId); } if (browsingContextId) { this.set('COCKLE_BROWSING_CONTEXT_ID', browsingContextId); } if (color) { this.set('PS1', ansi.styleGreen + 'js-shell:' + ansi.styleReset + ' '); this.set('TERM', 'xterm-256color'); this.set('TERMINFO', '/usr/local/share/terminfo'); // Needed for nano } else { this.set('PS1', 'js-shell: '); } } /** * Copy environment variables into a command before it is run. */ copyIntoCommand(target: { [key: string]: string }) { for (const [key, value] of this.entries()) { target[key] = value; } } getNumber(key: string): number | null { const str = this.get(key); if (str === null) { return null; } const number = Number(str); return isNaN(number) ? null : number; } getPrompt(): string { return this.get('PS1') ?? '$ '; } get color(): boolean { return this.has('TERM'); } names(): string[] { const re = /^[A-Za-z_]/; return Array.from(this.keys()).filter(name => re.test(name)); } setSize(size: ISize): void { const { rows, columns } = size; if (rows >= 1) { const rowsString = rows.toString(); this.set('LINES', rowsString); } else { this.delete('LINES'); } if (columns >= 1) { const columnsString = columns.toString(); this.set('COLUMNS', columnsString); } else { this.delete('COLUMNS'); } } }