diff --git a/QUICKSTART.ko.md b/QUICKSTART.ko.md index 0d104be..dd0d882 100644 --- a/QUICKSTART.ko.md +++ b/QUICKSTART.ko.md @@ -7,6 +7,7 @@ JDK 21과 [운영체제에 맞는 ZIP](docs/ko/installation.md)을 설치한 뒤 ```sh scouterctl --version scouterctl --help +scouterctl capture --help ``` 여러 줄로 적은 명령은 Bash 예시입니다. Windows에서는 각 명령을 한 줄로 입력하면 같은 옵션을 사용할 수 있습니다. diff --git a/QUICKSTART.md b/QUICKSTART.md index 5581358..a01e996 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -7,6 +7,7 @@ Install the [Linux x64 or Windows x64 command package](docs/installation.md) wit ```sh scouterctl --version scouterctl --help +scouterctl capture --help ``` ## 1. Connect to a Collector diff --git a/docs/cli-contract.md b/docs/cli-contract.md index dee3e2b..6f685e2 100644 --- a/docs/cli-contract.md +++ b/docs/cli-contract.md @@ -8,6 +8,7 @@ This guide describes the output consumed by scripts and other tools. Output sche - Command and argument errors also go to stdout as JSON. Do not assume stderr is the error API. Keep stdout and stderr separate when parsing. - Explicit interactive password input uses a terminal and a human-readable prompt on stderr. Automation should provide `SCOUTERCTL_PASSWORD` and use `--no-input`; it must not depend on prompt text. - `--help` and `--version` are plain-text stdout with exit 0, outside the JSON format. Help layout and diagnostic messages may change. Parse error codes rather than message text. +- `scouterctl COMMAND --help` shows that command's required and accepted options, combinations and an example (for example `scouterctl capture --help` or `scouterctl counter history --help`). A command-family help request such as `scouterctl counter --help` lists its commands. Help contains no ANSI escapes when output is redirected or `NO_COLOR` is set, including an empty value. - These formats apply after the JVM and CLI start successfully. A missing/incompatible JVM, process termination or an unwritable output stream can prevent a valid JSON response. Missing or malformed output must not be treated as successful execution. ## Single-result commands @@ -32,6 +33,8 @@ Completion never certifies traffic coverage, sampling, comparability or profile The example message is illustrative. `error.code` is the machine-readable identifier; `error.message` is a human-readable string. An error object contains no result data. During a stream, previously emitted records remain on stdout but are not a complete result. +Unknown options, invalid/missing option values and unsupported command-option combinations identify the offending option in `error.message` where available. Argument values are not echoed; error schema and exit codes are unchanged. + | Exit | Error code when an error object is emitted | Meaning | | --- | --- | --- | | 0 | None | Requested command completed; scope limitations still apply | diff --git a/src/main/kotlin/dev/scouterctl/bootstrap/Bootstrap.kt b/src/main/kotlin/dev/scouterctl/bootstrap/Bootstrap.kt index 01df50c..c19acd3 100644 --- a/src/main/kotlin/dev/scouterctl/bootstrap/Bootstrap.kt +++ b/src/main/kotlin/dev/scouterctl/bootstrap/Bootstrap.kt @@ -19,9 +19,11 @@ fun runCli(args: Array) { OnlineCommands(contexts, { endpoint, password -> CollectorSource.connect(endpoint, password, BuildInfo.version) }, ::CaptureStore, ::EvidenceStore, ::CounterCaptureStore, TerminalPasswordInput(), output), ) - val command = CommandLine(Cli(dispatcher, output)) + val cli = Cli(dispatcher, output) + val command = CommandLine(cli) + cli.configureHelp(command) command.commandSpec.version("scouterctl ${BuildInfo.version}") - command.setParameterExceptionHandler { _, _ -> output.failure(OperationFailure(ErrorCode.INVALID_ARGUMENT, "Invalid command arguments; use --help")) } + command.setParameterExceptionHandler { error, _ -> output.failure(argumentFailure(error)) } exitProcess(command.execute(*args)) } diff --git a/src/main/kotlin/dev/scouterctl/cli/ArgumentFailure.kt b/src/main/kotlin/dev/scouterctl/cli/ArgumentFailure.kt new file mode 100644 index 0000000..b99d2f3 --- /dev/null +++ b/src/main/kotlin/dev/scouterctl/cli/ArgumentFailure.kt @@ -0,0 +1,21 @@ +package dev.scouterctl.cli + +import dev.scouterctl.core.ErrorCode +import dev.scouterctl.core.OperationFailure +import picocli.CommandLine.Model.OptionSpec +import picocli.CommandLine.MissingParameterException +import picocli.CommandLine.ParameterException +import picocli.CommandLine.UnmatchedArgumentException + +internal fun argumentFailure(error: ParameterException): OperationFailure { + val option = (error.argSpec as? OptionSpec)?.longestName() + ?: (error as? MissingParameterException)?.missing?.filterIsInstance()?.firstOrNull()?.longestName() + val message = if (option != null) { + "Invalid or missing value for $option; use --help" + } else if (error is UnmatchedArgumentException) { + val unknown = error.unmatched.firstOrNull { it.substringBefore('=').matches(Regex("--?[A-Za-z][A-Za-z0-9-]*")) } + ?.substringBefore('=') + if (unknown == null) "Invalid command arguments; use --help" else "Unknown option $unknown; use --help" + } else "Invalid command arguments; use --help" + return OperationFailure(ErrorCode.INVALID_ARGUMENT, message) +} diff --git a/src/main/kotlin/dev/scouterctl/cli/Cli.kt b/src/main/kotlin/dev/scouterctl/cli/Cli.kt index f3b6a8c..4c8d1e7 100644 --- a/src/main/kotlin/dev/scouterctl/cli/Cli.kt +++ b/src/main/kotlin/dev/scouterctl/cli/Cli.kt @@ -16,7 +16,7 @@ import java.util.concurrent.Callable "Password: SCOUTERCTL_PASSWORD, or --interactive for hidden terminal input. Passwords are never saved.", "TCP has no native TLS; use a trusted path."]) class Cli(private val dispatcher: CommandDispatcher, private val output: JsonOutput) : Callable { - @Parameters(arity = "1..2", paramLabel = "COMMAND") lateinit var words: List + @Parameters(arity = "1..2", paramLabel = "COMMAND") var words: List = emptyList() @Mixin val connection = ConnectionOptions() @Spec lateinit var spec: CommandSpec @Option(names = ["--name"], description = ["Name for context add/use"]) var name: String? = null diff --git a/src/main/kotlin/dev/scouterctl/cli/CommandGuide.kt b/src/main/kotlin/dev/scouterctl/cli/CommandGuide.kt new file mode 100644 index 0000000..044b1f2 --- /dev/null +++ b/src/main/kotlin/dev/scouterctl/cli/CommandGuide.kt @@ -0,0 +1,70 @@ +package dev.scouterctl.cli + +internal data class CommandGuide( + val name: String, + val description: String, + val required: Set, + val optional: Set, + val example: String, + val notes: List = emptyList(), +) { + val allowed: Set get() = required + optional +} + +private val connectionOptions = setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input") +private val windowOptions = setOf("--from", "--to", "--timezone", "--object-hash") +private val xlogOptions = windowOptions + "--date" +private val pagingOptions = setOf("--page-size", "--max-pages") +private val offlineOptions = setOf("--include-text", "--no-input") +private val connectionNotes = listOf("Connection options override a saved context; otherwise host/port default to 127.0.0.1:6100.", + "Provide an account with --user or a saved context. Use SCOUTERCTL_PASSWORD, or --interactive for hidden terminal input.") +private const val windowExample = "--date 20261101 --from 2026-11-01T00:00:00Z --to 2026-11-01T00:01:00Z --timezone UTC --object-hash 42" + +internal val commandGuides = listOf( + CommandGuide("doctor", "Check Collector connectivity and authentication.", emptySet(), connectionOptions, + "doctor --host localhost --user reader --no-input", connectionNotes), + CommandGuide("auth login", "Check credentials without saving a password.", emptySet(), connectionOptions, + "auth login --host localhost --user reader --interactive", connectionNotes), + CommandGuide("context add", "Save a named connection without its password.", setOf("--name", "--user"), + setOf("--host", "--port", "--no-input"), "context add --name local --host localhost --user reader"), + CommandGuide("context list", "List saved connections and the selected context.", emptySet(), setOf("--no-input"), "context list"), + CommandGuide("context use", "Select a saved connection.", setOf("--name"), setOf("--no-input"), "context use --name local"), + CommandGuide("collector status", "Read Collector status.", emptySet(), connectionOptions, + "collector status --user reader --no-input", connectionNotes), + CommandGuide("collector config", "Read safe Collector settings; optionally select an exact key.", emptySet(), connectionOptions + "--key", + "collector config --user reader --no-input", connectionNotes), + CommandGuide("agent status", "Read Agent JVM and runtime status.", setOf("--object-hash"), connectionOptions, + "agent status --object-hash 42 --user reader --no-input", connectionNotes), + CommandGuide("agent config", "Read safe Agent settings; optionally select an exact key.", setOf("--object-hash"), connectionOptions + "--key", + "agent config --object-hash 42 --user reader --no-input", connectionNotes), + CommandGuide("object list", "List live objects, or recorded objects for --date.", emptySet(), connectionOptions + "--date", + "object list --user reader --no-input", connectionNotes), + CommandGuide("counter list", "List available real-time counters for an object.", setOf("--object-hash"), connectionOptions, + "counter list --object-hash 42 --user reader --no-input", connectionNotes), + CommandGuide("counter get", "Read one exact real-time counter.", setOf("--object-hash", "--counter"), connectionOptions, + "counter get --object-hash 42 --counter Cpu --user reader --no-input", connectionNotes), + CommandGuide("counter history", "Stream stored counter values for a dated window.", xlogOptions + "--counter", connectionOptions, + "counter history $windowExample --counter Cpu --user reader --no-input", connectionNotes), + CommandGuide("counter export", "Export stored counters in resumable chunks.", windowOptions + setOf("--counter", "--directory"), + connectionOptions + setOf("--resume", "--chunk-minutes", "--max-chunks"), + "counter export --from 2026-11-01T00:00:00Z --to 2026-11-01T00:01:00Z --timezone UTC --object-hash 42 --counter Cpu --directory counters --user reader --no-input", + connectionNotes + "Use the same query and directory with --resume; chunk boundaries split at Collector midnight."), + CommandGuide("xlog search", "Stream XLogs for a storage date and time window.", xlogOptions, connectionOptions + pagingOptions + "--include-text", + "xlog search $windowExample --user reader --no-input", connectionNotes), + CommandGuide("profile get", "Read one stored transaction profile.", setOf("--date", "--txid"), connectionOptions + "--include-text", + "profile get --date 20261101 --txid 123 --user reader --no-input", connectionNotes), + CommandGuide("capture", "Save a resumable XLog capture, optionally including profiles.", xlogOptions + "--directory", + connectionOptions + pagingOptions + setOf("--resume", "--include-profiles", "--include-text"), + "capture $windowExample --directory capture --user reader --no-input", + connectionNotes + listOf("--include-text requires --include-profiles. Text can contain sensitive values.", + "Use the same query and directory with --resume. Profile capture defaults to page size 25, maximum 100.")), + CommandGuide("inspect", "Read a captured profile offline.", setOf("--directory", "--txid"), offlineOptions, + "inspect --directory capture --txid 123"), + CommandGuide("inspect search", "Search captured requests offline.", setOf("--directory"), offlineOptions + + setOf("--limit", "--min-elapsed-ms", "--errors-only", "--service-hash", "--service-name"), + "inspect search --directory capture --errors-only", listOf("--service-name requires --include-text and stored dictionary text.")), + CommandGuide("inspect summary", "Summarize captured services offline.", setOf("--directory"), offlineOptions + setOf("--limit", "--sort"), + "inspect summary --directory capture --sort elapsed"), + CommandGuide("inspect compare", "Compare baseline and candidate captures offline.", setOf("--before", "--after"), offlineOptions + "--limit", + "inspect compare --before baseline --after candidate"), +).associateBy { it.name } diff --git a/src/main/kotlin/dev/scouterctl/cli/CommandHelp.kt b/src/main/kotlin/dev/scouterctl/cli/CommandHelp.kt new file mode 100644 index 0000000..0ec4a5e --- /dev/null +++ b/src/main/kotlin/dev/scouterctl/cli/CommandHelp.kt @@ -0,0 +1,36 @@ +package dev.scouterctl.cli + +import picocli.CommandLine +import picocli.CommandLine.Help +import picocli.CommandLine.Model.CommandSpec + +internal fun Cli.configureHelp(command: CommandLine) { + val ansi = if (System.console() == null || System.getenv("NO_COLOR") != null) Help.Ansi.OFF else Help.Ansi.AUTO + command.setColorScheme(Help.defaultColorScheme(ansi)) + command.setHelpFactory { root, colors -> Help(helpSpec(root, words.joinToString(" ")), colors) } +} + +private fun helpSpec(root: CommandSpec, name: String): CommandSpec { + val guide = commandGuides[name] + val children = commandGuides.values.filter { it.name.startsWith("$name ") } + val help = CommandSpec.create().name(if (guide == null) "scouterctl" else "scouterctl $name") + val usage = help.usageMessage().optionListHeading("Options:%n").sortOptions(false) + if (guide != null) { + val footer = listOf(" scouterctl ${guide.example}") + if (children.isEmpty()) emptyList() else + listOf("", "Subcommands:") + children.map { " ${it.name.padEnd(18)} ${it.description}" } + usage.description(guide.description, *guide.notes.toTypedArray()) + .footerHeading("%nExample:%n").footer(*footer.toTypedArray()) + root.options().filter { it.usageHelp() || it.versionHelp() || it.longestName() in guide.allowed }.forEach { option -> + help.addOption(option.toBuilder().required(option.longestName() in guide.required).build()) + } + } else { + val entries = if (name.isEmpty()) commandGuides.values else children + if (entries.isEmpty()) return root + usage.customSynopsis("scouterctl ${if (name.isEmpty()) "COMMAND" else "$name COMMAND"} [OPTIONS]") + .description(*(if (name.isEmpty()) root.usageMessage().description() else arrayOf("Scouter $name commands."))) + .footerHeading("%nCommands:%n").footer(*entries.map { " ${it.name.padEnd(18)} ${it.description}" }.toTypedArray(), + "", "Use scouterctl COMMAND --help for required options, accepted options and an example.") + root.options().filter { it.usageHelp() || it.versionHelp() }.forEach { help.addOption(it.toBuilder().build()) } + } + return help +} diff --git a/src/main/kotlin/dev/scouterctl/cli/CommandInterpreter.kt b/src/main/kotlin/dev/scouterctl/cli/CommandInterpreter.kt index df30597..654e2c5 100644 --- a/src/main/kotlin/dev/scouterctl/cli/CommandInterpreter.kt +++ b/src/main/kotlin/dev/scouterctl/cli/CommandInterpreter.kt @@ -11,12 +11,11 @@ internal fun Cli.interpret(): CommandRequest { if (command in setOf("context add", "context list", "context use")) return contextRequest(command) if (name != null) invalid("--name requires context add/use") if (command == "inspect compare") { - allowedOptions(setOf("--before", "--after", "--limit", "--include-text", "--no-input")) + allowedOptions() return OfflineRequest.Compare(required(before, "--before"), required(after, "--after"), ComparisonOptions(limit ?: 20, includeText)) } if (command == "counter export") { - allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input", - "--object-hash", "--counter", "--from", "--to", "--timezone", "--directory", "--resume", "--chunk-minutes", "--max-chunks")) + allowedOptions() val budget = maxChunks ?: 24 if (budget !in 1..10000) invalid("Use max-chunks 1..10000") val query = CounterExportQuery(Instant.parse(required(from, "--from")).toEpochMilli(), @@ -27,24 +26,20 @@ internal fun Cli.interpret(): CommandRequest { } if (chunkMinutes != null || maxChunks != null) invalid("--chunk-minutes and --max-chunks require counter export") if (command == "counter history") { - allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input", - "--object-hash", "--counter", "--date", "--from", "--to", "--timezone")) + allowedOptions() return OnlineRequest.CounterHistory(CounterHistoryQuery(required(date, "--date"), Instant.parse(required(from, "--from")).toEpochMilli(), Instant.parse(required(to, "--to")).toEpochMilli(), required(timezone, "--timezone"), required(objHash, "--object-hash"), required(counterName, "--counter")).also { it.validate() }) } if (command in setOf("counter list", "counter get")) { - allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input", "--object-hash") + - if (command == "counter get") setOf("--counter") else emptySet()) + allowedOptions() val counter = if (command == "counter get") required(counterName, "--counter") else null if (counter != null && (counter.isBlank() || counter.length > 256 || counter.any(Char::isISOControl))) invalid("Invalid counter name") return OnlineRequest.Counters(required(objHash, "--object-hash"), counter) } if (counterName != null) invalid("--counter requires counter get, counter history or counter export") if (command in setOf("collector status", "collector config", "agent status", "agent config")) { - allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input") + - (if (command.endsWith("config")) setOf("--key") else emptySet()) + - if (command.startsWith("agent ")) setOf("--object-hash") else emptySet()) + allowedOptions() settingKey?.let { if (!it.matches(Regex("[A-Za-z_][A-Za-z0-9_.-]{0,255}"))) invalid("Use a setting name for --key") } return when (command) { "collector status" -> OnlineRequest.CollectorStatus @@ -56,7 +51,7 @@ internal fun Cli.interpret(): CommandRequest { if (settingKey != null) invalid("--key requires collector config or agent config") if (before != null || after != null) invalid("--before and --after require inspect compare") if (command == "inspect summary") { - allowedOptions(setOf("--directory", "--limit", "--sort", "--include-text", "--no-input")) + allowedOptions() return OfflineRequest.Summary(required(directory, "--directory"), ServiceSummaryOptions(limit ?: 20, ServiceSort.parse(summarySort ?: "errors"), includeText)) } @@ -77,12 +72,7 @@ internal fun Cli.interpret(): CommandRequest { } private fun Cli.contextRequest(command: String): ContextRequest { - val allowed = when (command) { - "context add" -> setOf("--name", "--host", "--port", "--user", "--no-input") - "context use" -> setOf("--name", "--no-input") - else -> setOf("--no-input") - } - allowedOptions(allowed) + allowedOptions() return when (command) { "context add" -> ContextRequest.Add(name, connection.host ?: "127.0.0.1", connection.port ?: 6100, connection.user) "context use" -> ContextRequest.Use(name) @@ -94,10 +84,13 @@ private fun Cli.validateGeneralOptions(command: String) { val supported = setOf("doctor", "auth login", "object list", "xlog search", "profile get", "capture", "inspect", "inspect search") if (command !in supported) invalid("Unknown command") if (command == "auth login") { - allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input")) + allowedOptions() } if (command != "inspect search" && (limit != null || minElapsedMs != null || errorsOnly || serviceHash != null || serviceName != null)) { - invalid("Search filters require inspect search") + val option = spec.commandLine().parseResult.matchedOptions().first { + it.longestName() in setOf("--limit", "--min-elapsed-ms", "--errors-only", "--service-hash", "--service-name") + }.longestName() + invalid("$option requires inspect search") } if (includeProfiles && command != "capture") invalid("--include-profiles requires capture") if (includeText && command !in setOf("xlog search", "profile get", "inspect", "inspect search") && !(command == "capture" && includeProfiles)) { @@ -135,9 +128,10 @@ private fun Cli.query(): Query = Query(required(date, "--date"), Instant.parse(required(from, "--from")).toEpochMilli(), Instant.parse(required(to, "--to")).toEpochMilli(), required(timezone, "--timezone"), required(objHash, "--object-hash"), pageSize ?: if (includeProfiles) 25 else 1000).also { it.validate() } -private fun Cli.allowedOptions(allowed: Set) { - if (spec.commandLine().parseResult.matchedOptions().any { it.longestName() !in allowed }) { - invalid("Option is not supported by this command; use --help") +private fun Cli.allowedOptions() { + val allowed = commandGuides.getValue(words.joinToString(" ")).allowed + spec.commandLine().parseResult.matchedOptions().firstOrNull { it.longestName() !in allowed }?.let { + invalid("Option ${it.longestName()} is not supported by this command; use --help") } } private fun invalid(message: String): Nothing = throw OperationFailure(ErrorCode.INVALID_ARGUMENT, message) diff --git a/src/test/kotlin/dev/scouterctl/CliUsabilityTest.kt b/src/test/kotlin/dev/scouterctl/CliUsabilityTest.kt new file mode 100644 index 0000000..fa416ee --- /dev/null +++ b/src/test/kotlin/dev/scouterctl/CliUsabilityTest.kt @@ -0,0 +1,112 @@ +package dev.scouterctl + +import io.kotest.core.spec.style.FunSpec +import io.kotest.engine.spec.tempdir +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.string.shouldNotContain +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import java.nio.file.Files +import java.nio.file.Path +import java.util.concurrent.TimeUnit + +class CliUsabilityTest : FunSpec({ + for (noColor in listOf(false, true)) { + test("redirected help contains no ANSI even when color is forced and NO_COLOR is $noColor") { + val result = helpOutput(tempdir().toPath(), listOf("--help"), noColor) + result.exit shouldBe 0 + result.output shouldContain "scouterctl" + result.output shouldNotContain "\u001b" + result.stderr shouldBe "" + } + } + + for (noColor in listOf(null, "")) { + test("terminal help honors NO_COLOR presence even with an empty value: $noColor") { + TerminalCli(tempdir().toPath(), listOf("capture", "--help"), + command = cliJavaCommand(jvmOptions = listOf("-Dpicocli.ansi=true")), noColor = noColor).use { terminal -> + terminal.finish().exit shouldBe 0 + terminal.rawText().contains("\u001b[1m") shouldBe (noColor == null) + } + } + } + + data class HelpCase(val words: List, val required: List, val excluded: String) + for (case in listOf( + HelpCase(listOf("capture"), listOf("--directory", "--date", "--timezone", "--object-hash"), "--key"), + HelpCase(listOf("counter", "history"), listOf("--counter", "--date", "--object-hash"), "--directory"), + HelpCase(listOf("inspect", "compare"), listOf("--before", "--after"), "--host"), + )) { + test("${case.words.joinToString(" ")} help identifies its required options and excludes unrelated options") { + val result = helpOutput(tempdir().toPath(), case.words + "--help") + result.exit shouldBe 0 + result.stderr shouldBe "" + val synopsis = result.output.substringBefore("Options:") + synopsis shouldContain "scouterctl ${case.words.joinToString(" ")}" + case.required.forEach { option -> + synopsis shouldContain "$option=" + synopsis shouldNotContain "[$option=" + } + result.output shouldNotContain case.excluded + } + } + + test("inspect help also exposes its offline subcommands") { + val result = helpOutput(tempdir().toPath(), listOf("inspect", "--help")) + result.exit shouldBe 0 + for (subcommand in listOf("search", "summary", "compare")) result.output shouldContain "inspect $subcommand" + result.output shouldNotContain "--host" + } + + test("counter family help lists its commands without unrelated command options") { + val result = helpOutput(tempdir().toPath(), listOf("counter", "--help")) + result.exit shouldBe 0 + result.output shouldContain "scouterctl counter COMMAND" + for (subcommand in listOf("list", "get", "history", "export")) result.output shouldContain "counter $subcommand" + result.output shouldNotContain "--directory" + result.output shouldNotContain "agent status" + } + + test("unmatched positional values return a safe JSON error") { + val result = runOfflineCli(tempdir().toPath(), listOf("doctor", "unexpected", "secret-value")) + result.exit shouldBe 2 + result.events.single()["error"]!!.jsonObject["code"]!!.jsonPrimitive.content shouldBe "INVALID_ARGUMENT" + result.output shouldNotContain "secret-value" + result.stderr shouldBe "" + } + + for ((args, option) in listOf( + listOf("doctor", "--unknown=secret-value") to "--unknown", + listOf("doctor", "-z", "secret-value") to "-z", + listOf("doctor", "--port", "secret-value") to "--port", + listOf("doctor", "--port") to "--port", + listOf("counter", "list", "--directory", "secret-value") to "--directory", + )) { + test("invalid ${args.joinToString(" ")} identifies the option without echoing values") { + val result = runOfflineCli(tempdir().toPath(), args) + result.exit shouldBe 2 + result.stderr shouldBe "" + val error = result.events.single()["error"]!!.jsonObject + error["code"]!!.jsonPrimitive.content shouldBe "INVALID_ARGUMENT" + error["message"]!!.jsonPrimitive.content shouldContain option + result.output shouldNotContain "secret-value" + } + } +}) + +private data class HelpOutput(val exit: Int, val output: String, val stderr: String) + +private fun helpOutput(work: Path, args: List, noColor: Boolean = false): HelpOutput { + val stdout = work.resolve("stdout") + val stderr = work.resolve("stderr") + val process = ProcessBuilder(cliJavaCommand(jvmOptions = listOf("-Dpicocli.ansi=true")) + args) + .apply { + environment()["TERM"] = "xterm" + if (noColor) environment()["NO_COLOR"] = "1" else environment().remove("NO_COLOR") + }.redirectOutput(stdout.toFile()).redirectError(stderr.toFile()).start() + try { + check(process.waitFor(15, TimeUnit.SECONDS)) { "Help did not terminate" } + return HelpOutput(process.exitValue(), Files.readString(stdout), Files.readString(stderr)) + } finally { process.destroyForcibly() } +} diff --git a/src/test/kotlin/dev/scouterctl/TerminalCli.kt b/src/test/kotlin/dev/scouterctl/TerminalCli.kt index 1b8c161..5f10a25 100644 --- a/src/test/kotlin/dev/scouterctl/TerminalCli.kt +++ b/src/test/kotlin/dev/scouterctl/TerminalCli.kt @@ -10,11 +10,14 @@ import java.nio.file.Path import java.util.concurrent.Executors import java.util.concurrent.TimeUnit -internal class TerminalCli(work: Path, args: List, password: String? = null, command: List? = null) : AutoCloseable { +internal class TerminalCli(work: Path, args: List, password: String? = null, command: List? = null, + noColor: String? = null) : AutoCloseable { private val environment = System.getenv().toMutableMap().apply { remove("SCOUTERCTL_PASSWORD") put("SCOUTERCTL_CONFIG", work.resolve("config.json").toString()) put("TERM", "xterm") + remove("NO_COLOR") + if (noColor != null) put("NO_COLOR", noColor) if (password != null) put("SCOUTERCTL_PASSWORD", password) if (command != null) withCliCoverage() } @@ -36,7 +39,9 @@ internal class TerminalCli(work: Path, args: List, password: String? = n } } - fun text(): String = synchronized(bytes) { bytes.toString(Charsets.UTF_8) } + fun rawText(): String = synchronized(bytes) { bytes.toString(Charsets.UTF_8) } + + fun text(): String = rawText() .replace(Regex("\u001B\\[[0-?]*[ -/]*[@-~]"), "") .replace(Regex("\u001B\\][^\u0007]*(?:\u0007|\u001B\\\\)"), "") .replace("\r", "")