All files / lib cli.ts

100% Statements 33/33
100% Branches 4/4
100% Functions 10/10
100% Lines 26/26

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  1x   3x 1x 4x 1x 3x 3x   3x                             1x   6x 6x     1x 1x         3x 3x   3x 3x 3x 3x 3x     1x 1x 1x     1x 1x   1x  
import { StdIoReaderInterface } from "lib/std-io-reader"
import { getMessageForError } from "./env/error"
 
const bgCyan = (message: string): string => `\x1b[46m${message}\x1b[0m`
const fgRed = (message: string): string => `\x1b[31m${message}\x1b[0m`
const fgYellow = (message: string): string => `\x1b[33m${message}\x1b[0m`
const buildQuestion = (name: string, defaultValue: string): string => {
    const hasDefaultValue = defaultValue.trim().length > 0
    const defaultValueNote = hasDefaultValue ? ` (${fgYellow(defaultValue)})` : ''
 
    return `${bgCyan(name)}${defaultValueNote}: `
}
 
export interface EnvironmentVariable {
    name: string
    value: string
}
 
export interface CliPrompterInterface {
    promptUserAboutNewVariables: () => void
    promptUserForEnvironmentVariable: (environmentVariable: EnvironmentVariable) => Promise<EnvironmentVariable>
    printError: (error: Error) => void
    printWarning: (warning: string) => void
}
 
export class CliPrompter implements CliPrompterInterface {
    public constructor(
        private console: Console,
        private stdIoReader: StdIoReaderInterface
    ) {}
 
    public promptUserAboutNewVariables() {
        this.console.warn(fgYellow(
            'New environment variables were found. When prompted, please enter their values.'
        ))
    }
 
    public async promptUserForEnvironmentVariable({ name, value: defaultValue }: EnvironmentVariable): Promise<EnvironmentVariable> {
        const question: string = buildQuestion(name, defaultValue)
        // TODO maybe trim inputValue before returning it
        const inputValue: string = await this.stdIoReader.promptUser(question)
        const blankValueProvided = inputValue.trim().length === 0
        const value = blankValueProvided ? defaultValue : inputValue
        this.stdIoReader.pause()
        return { name, value }
    }
 
    public printError(error: Error) {
        const message = getMessageForError(error)
        this.console.error(fgRed(message))
    }
 
    public printWarning(warning: string) {
        this.console.error(fgYellow(warning))
    }
}