comparison 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
comparison
equal deleted inserted replaced
-1:000000000000 0:a6cfdffcaa94
1 package name.blackcap.passman
2
3 fun readLine(prompt: String): String =
4 doConsoleIo({ System.console()?.readLine(prompt) }, "unable to read line")
5
6 fun getPassword(prompt: String, verify: Boolean = false): CharArray {
7 while (true) {
8 val pw1 = _getPassword(prompt)
9 if (!verify) {
10 return pw1
11 }
12 val pw2 = _getPassword("Verification: ")
13 if (pw1 contentEquals pw2) {
14 return pw1
15 }
16 error("mismatch, try again")
17 }
18 }
19
20 fun mustReadLine(prompt: String): String = must({ readLine(prompt) }, { it.isNotEmpty() })
21
22 fun mustGetPassword(prompt: String, verify: Boolean = false): CharArray =
23 must({ getPassword(prompt, verify) }, { it.isNotEmpty() })
24
25 fun printPassword(password: CharArray) {
26 print("Password: ")
27 password.forEach { print(it) }
28 println()
29 }
30
31 private fun _getPassword(prompt: String): CharArray =
32 doConsoleIo({ System.console()?.readPassword(prompt) }, "unable to read password")
33
34 private fun <T> must(getter: () -> T, checker: (T) -> Boolean): T {
35 while (true) {
36 var got = getter()
37 if (checker(got)) {
38 return got
39 }
40 error("entry must not be empty, try again")
41 }
42 }
43
44 private fun <T> doConsoleIo(getter: () -> T?, message: String): T {
45 val ret = getter()
46 if (ret == null) {
47 die(message)
48 }
49 return ret!!
50 }