diff src/main/kotlin/name/blackcap/passman/Console.kt @ 0:a6cfdffcaa94

Initial commit, incomplete but it runs sorta.
author David Barts <n5jrn@me.com>
date Sun, 11 Sep 2022 16:11:37 -0700
parents
children ea65ab890f66
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/main/kotlin/name/blackcap/passman/Console.kt	Sun Sep 11 16:11:37 2022 -0700
@@ -0,0 +1,50 @@
+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) {
+        var 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()
+    if (ret == null) {
+        die(message)
+    }
+    return ret!!
+}