我有一个带有多个子命令的 CLI,其中一些子命令有一个可选标志-f
,可以使用该标志指定输入文件,例如
@CommandLine.Command(name = "get", description = ["Get something"])
class GetUserCommand: Runnable {
@Option(names = ["-f", "--file"], description = ["Input file"])
var filename: String? = null
override fun run() {
var content = read_file(filename)
}
}
@CommandLine.Command(name = "query", description = ["Query something"])
class QueryUserCommand: Runnable {
@Option(names = ["-f", "--file"], description = ["Input file"])
var filename: String? = null
override fun run() {
var content = read_file(filename)
}
}
输入文件格式可能因命令而异。理想情况下,如果文件被指定为参数,我想自动解析文件。此外,每个命令的文件内容可能不同(但将是特定格式,CSV 或 JSON)。
例如我想要这样的东西
data class First(val col1, val col2)
data class Second(val col1, val col2, val col3)
class CustomOption(// regular @Option parameters, targetClass=...) {
// do generic file parsing
}
@CommandLine.Command(name = "get", description = ["Get something"])
class GetUserCommand: Runnable {
@CustomOption(names = ["-f", "--file"], description = ["Input file"], targetClass=First))
var content: List<First> = emptyList()
override fun run() {
// content now contains the parse file
}
}
@CommandLine.Command(name = "query", description = ["Query something"])
class QueryUserCommand: Runnable {
@CustomOption(names = ["-f", "--file"], description = ["Input file"], targetClass=Second))
var content: List<Second> = emptyList()
override fun run() {
// content now contains the parse file
}
}
如果这是可能的或如何做到这一点,有人会知道吗?