comparison src/main/kotlin/name/blackcap/passman/Main.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 eafa3779aef8
comparison
equal deleted inserted replaced
-1:000000000000 0:a6cfdffcaa94
1 package name.blackcap.passman
2
3 import java.io.BufferedReader
4 import java.io.InputStreamReader
5 import java.util.*
6 import java.util.stream.Collectors
7 import kotlin.reflect.jvm.javaMethod
8 import kotlin.reflect.jvm.kotlinFunction
9 import kotlin.system.exitProcess
10
11 fun main(args: Array<String>) {
12 if (args.isEmpty()) {
13 error("expecting subcommand")
14 exitProcess(2)
15 }
16 val subcommand = args[0];
17 val scArgs = args.sliceArray(1 until args.size)
18 runSubcommand(subcommand, scArgs)
19 }
20
21 fun runSubcommand(name: String, args: Array<String>): Unit {
22 val instance = getInstanceForClass(getClassForSubcommand(name))
23 if (instance == null) {
24 die("$name - unknown subcommand", 2)
25 } else {
26 instance.run(args)
27 }
28 }
29
30 fun getClassForSubcommand(name: String): Class<Subcommand>? = try {
31 val shortName = name.replace('-', '_')
32 .lowercase()
33 .replaceFirstChar { it.titlecase(Locale.getDefault()) }
34 Class.forName("$MAIN_PACKAGE.${shortName}Subcommand") as? Class<Subcommand>
35 /* val ret = Class.forName("$MAIN_PACKAGE.$shortName")
36 if (ret.isInstance(Subcommand::class.java)) { ret as Class<Subcommand> } else { null } */
37 } catch (e: ClassNotFoundException) {
38 null
39 }
40
41 fun getInstanceForClass(klass: Class<Subcommand>?) = try {
42 klass?.getDeclaredConstructor()?.newInstance()
43 } catch (e: ReflectiveOperationException) {
44 null
45 }