view src/main/kotlin/name/blackcap/passman/Console.kt @ 26:69526ae8c8de

Allow list --name to be abbreviated -n, since it is so commonly used.
author David Barts <n5jrn@me.com>
date Fri, 05 Jul 2024 10:11:31 -0700
parents ea65ab890f66
children
line wrap: on
line source

package name.blackcap.passman

fun readLine(prompt: String): String =
    doConsoleIo({ System.console()?.readLine(prompt) }, "unable to read line")

fun getPassword(prompt: String, verify: Boolean = false): CharArray {
    while (true) {
        val pw1 = _getPassword(prompt)
        if (!verify) {
            return pw1
        }
        val pw2 = _getPassword("Verification: ")
        if (pw1 contentEquals pw2) {
            return pw1
        }
        error("mismatch, try again")
    }
}

fun mustReadLine(prompt: String): String = must({ readLine(prompt) }, { it.isNotEmpty() })

fun mustGetPassword(prompt: String, verify: Boolean = false): CharArray =
    must({ getPassword(prompt, verify) }, { it.isNotEmpty() })

fun printPassword(password: CharArray) {
    print("Password: ")
    password.forEach { print(it) }
    println()
}

private fun _getPassword(prompt: String): CharArray =
    doConsoleIo({ System.console()?.readPassword(prompt) }, "unable to read password")

private fun <T> must(getter: () -> T, checker: (T) -> Boolean): T {
    while (true) {
        val got = getter()
        if (checker(got)) {
            return got
        }
        error("entry must not be empty, try again")
    }
}

private fun <T> doConsoleIo(getter: () -> T?, message: String): T {
    val ret = getter() ?: throw ConsoleException(message)
    return ret
}

class ConsoleException(message: String, cause: Throwable? = null) : MessagedException(message, cause)