Skip to content

Commit

Permalink
* Replace CLI options --debug, --trace, --verbose and -v are …
Browse files Browse the repository at this point in the history
…with `--log-level=<level>` or the short version `-l=<level>. (#1658)

Closes #1652
Closes #1632
  • Loading branch information
paul-dingemans authored Oct 12, 2022
1 parent 28ff448 commit c9c86f4
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 31 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Please search in the [issues](https://github.com/pinterest/ktlint/issues) before
## Observed Behavior
<!---Tell us what happens instead of the expected behavior -->
<!--- Provide the exact command which was executed but please -->
<!--- ensure that the flag "--verbose" is added to the -->
<!--- ensure that the flag "--log-level=debug" is added to the -->
<!--- command as well. Provide the output of this command. -->

## Steps to Reproduce
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ Calling this API with a file path results in the `.editorconfig` files that will

### Changed
* Update Kotlin development version to `1.7.20` and Kotlin version to `1.7.20`.
* CLI options `--debug`, `--trace`, `--verbose` and `-v` are replaced with `--log-level=<level>` or the short version `-l=<level>, see [CLI log-level](https://pinterest.github.io/ktlint/install/cli/#logging). ([#1632](https://github.com/pinterest/ktlint/issue/1632))
* In CLI, disable logging entirely by setting `--log-level=none` or `-l=none` ([#1652](https://github.com/pinterest/ktlint/issue/1652))


## [0.47.1] - 2022-09-07

Expand Down
2 changes: 1 addition & 1 deletion docs/extensions/custom-rule-set.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ $ echo 'var v = 0' > test.kt
```
```shell title="Running the ktlint-ruleset-template" hl_lines="1 40 43"
$ ktlint -R build/libs/ktlint-ruleset-template.jar --debug --relative test.kt
$ ktlint -R build/libs/ktlint-ruleset-template.jar --log-level=debug --relative test.kt
18:13:21.026 [main] DEBUG com.pinterest.ktlint.internal.RuleSetsLoader - JAR ruleset provided with path "/../ktlint/ktlint-ruleset-template/build/libs/ktlint-ruleset-template.jar"
18:13:21.241 [main] DEBUG com.pinterest.ktlint.Main - Discovered reporter with "baseline" id.
Expand Down
17 changes: 11 additions & 6 deletions docs/install/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ ktlint "src/**/*.kt" "!src/**/*Test.kt"
ktlint "src/**/*.kt" "!src/**/generated/**"
```

### Error reporting
### Violation reporting

`ktlint` supports different type of reporters. When not specified the `plain` reporter is used. Optionally the `plain` reporter can group the violations per file.
`ktlint` supports different type of reporters for lint violations. When not specified the `plain` reporter is used. Optionally the `plain` reporter can group the violations per file.

```shell title="Style violation grouped by file"
$ ktlint --reporter=plain?group_by_file
Expand All @@ -118,6 +118,12 @@ If resolving all existing errors in a project is unwanted, it is possible to cre
ktlint --baseline=ktlint-baseline.xml # Baseline is created when not existing
```

### Logging

Logging information is written to `stdout`. The amount of logging can be influenced by setting the minimal log level using option `--log-level` or `-l` to one of values `trace`, `debug`, `info`, `warn`, `error`, or `none` to suppress all logging.

By default, the `info` log level is used meaning that all log lines at level `info`, `warn` and `error` are shown while suppressing log lines at level `debug` or `trace`.

### Rule configuration (`.editorconfig`)

Some rules can be tweaked via the [`editorconfig file`](https://pinterest.github.io/ktlint/rules/configuration/).
Expand Down Expand Up @@ -145,7 +151,7 @@ ktlint --editorconfig=/path/to/.editorconfig

### Stdin && stdout

With command below, the input is read from `stdin` and the violations are printed to `stderr`.
With command below, the input is read from `stdin` and the violations are printed to `stderr`. Logging is written to `stdout`.

```shell title="Lint from stdin"
ktlint --stdin
Expand All @@ -157,7 +163,8 @@ When combined with the `--format` option, the formatted code is written to `stdo
ktlint --stdin -F
```

!!! tip Suppress error output
!!! tip Suppress logging and error output
Logging output printed to `stdout` can be suppressed by setting `--log-level=none` (see [logging](#logging)).
Output printed to `stderr` can be suppressed in different ways. To ignore all error output, add `2> /dev/null` to the end of the command line. Otherwise, specify a [reporter](#error-reporting) to write the error output to a file.


Expand Down Expand Up @@ -192,8 +199,6 @@ ktlint installGitPrePushHook
`--patterns-from-stdin[=<delimiter>]`: Reads additional patterns from `stdin`, where the patterns are separated by `<delimiter>`. If `=<delimiter>` is omitted, newline is used as fallback delimiter. If an empty string is given, the `NUL` byte is used as delimiter instead.
Options `--stdin` and `--patterns-from-stdin` are mutually exclusive, only one of them can be given at a time.

`-v`, `--verbose` or `--debug`: Turn on debug output. Also option `--trace` is available, but this is meant for ktlint library developers.

`-V` or `--version`: Prints version information and exit.

### Microsoft Windows users
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import java.util.concurrent.ConcurrentHashMap

public class PlainReporter(
private val out: PrintStream,
private val verbose: Boolean = false,
private val groupByFile: Boolean = false,
private val shouldColorOutput: Boolean = false,
private val outputColor: Color = Color.DARK_GRAY,
Expand Down Expand Up @@ -42,7 +41,7 @@ public class PlainReporter(
out.println(
" $line${
":${if (pad) String.format("%-3s", col) else "$col"}".colored()
} $detail${if (verbose) " ($ruleId)".colored() else ""}",
} $detail ${"($ruleId)".colored()}",
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ public class PlainReporterProvider : ReporterProvider<PlainReporter> {
override fun get(out: PrintStream, opt: Map<String, String>): PlainReporter =
PlainReporter(
out,
verbose = opt["verbose"]?.emptyOrTrue() ?: false,
groupByFile = opt["group_by_file"]?.emptyOrTrue() ?: false,
shouldColorOutput = opt["color"]?.emptyOrTrue() ?: false,
outputColor = getColor(opt["color_name"]),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,10 @@ class PlainReporterTest {
assertThat(String(out.toByteArray())).isEqualTo(
"""
/one-fixed-and-one-not.kt
1:1 <"&'>
1:1 <"&'> (rule-1)
/two-not-fixed.kt
1:10 I thought I would again
2:20 A single thin straight line
1:10 I thought I would again (rule-1)
2:20 A single thin straight line (rule-2)
""".trimIndent().replace("\n", System.lineSeparator()),
)
Expand Down
4 changes: 2 additions & 2 deletions ktlint-ruleset-template/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ tasks.register<JavaExec>("ktlint") {
dependsOn(tasks.classes)
group = LifecycleBasePlugin.VERIFICATION_GROUP
mainClass.set("com.pinterest.ktlint.Main")
// adding compiled classes to the classpath so that ktlint would validate project"s sources
// adding compiled classes to the classpath so that ktlint would validate project's sources
// using its own ruleset (in other words to dogfood)
classpath(ktlint, sourceSets.main.map { it.output })
args("--debug", "src/**/*.kt")
args("--log-level=debug", "src/**/*.kt")
}.let {
tasks.check.configure {
dependsOn(it)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,17 @@ internal class KtlintCommandLine {

@Option(
names = ["--debug"],
description = ["Turn on debug output"],
description = ["Turn on debug output. Deprecated, use '--log-level=debug' instead."],
)
var debug: Boolean = false
@Deprecated(message = "Replaced with minLogLevel")
var debugOld: Boolean? = null

@Option(
names = ["--trace"],
description = ["Turn on trace output"],
description = ["Turn on trace output. Deprecated, use '--log-level=trace' instead."],
)
var trace: Boolean = false
@Deprecated(message = "Replaced with minLogLevel")
var trace: Boolean? = null

@Option(
names = ["--disabled_rules"],
Expand Down Expand Up @@ -194,9 +196,10 @@ internal class KtlintCommandLine {

@Option(
names = ["--verbose", "-v"],
description = ["Show error codes"],
description = ["Show error codes. Deprecated, use '--log-level=info' instead."],
)
private var verbose: Boolean = false
@Deprecated(message = "Replaced with minLogLevel")
private var verbose: Boolean? = null

@Option(
names = ["--editorconfig"],
Expand Down Expand Up @@ -224,14 +227,32 @@ internal class KtlintCommandLine {
@Parameters(hidden = true)
private var patterns = ArrayList<String>()

@Option(
names = ["--log-level", "-l"],
description = ["Defines the minimum log level (trace, debug, info, warn, error) or none to suppress all logging"],
converter = [LogLevelConverter::class],
)
private var minLogLevel: Level = Level.INFO

private val tripped = AtomicBoolean()
private val fileNumber = AtomicInteger()
private val errorNumber = AtomicInteger()

internal var debug: Boolean = false
get() = Level.DEBUG.isGreaterOrEqual(minLogLevel)
private set

fun run() {
if (verbose) {
debug = true
if (debugOld != null || trace != null || verbose != null) {
if (minLogLevel == Level.OFF) {
minLogLevel = Level.ERROR
}
configureLogger().error {
"Options '--debug', '--trace', '--verbose' and '-v' are deprecated and replaced with option '--log-level=<level>' or '-l=<level>'."
}
exitProcess(1)
}

logger = configureLogger()

assertStdinAndPatternsFromStdinOptionsMutuallyExclusive()
Expand Down Expand Up @@ -311,11 +332,7 @@ internal class KtlintCommandLine {
KotlinLogging
.logger {}
.setDefaultLoggerModifier { logger ->
(logger.underlyingLogger as Logger).level = when {
trace -> Level.TRACE
debug -> Level.DEBUG
else -> Level.INFO
}
(logger.underlyingLogger as Logger).level = minLogLevel
}
.initKtLintKLogger()

Expand Down Expand Up @@ -471,7 +488,6 @@ internal class KtlintCommandLine {
reporterId,
split.lastOrNull { it.startsWith("artifact=") }?.let { it.split("=")[1] },
mapOf(
"verbose" to verbose.toString(),
"color" to color.toString(),
"color_name" to colorName,
"format" to format.toString(),
Expand Down Expand Up @@ -541,7 +557,7 @@ internal class KtlintCommandLine {
"",
"Internal Error (${e.ruleId}) in file '$filename' at position '${e.line}:${e.col}. " +
"Please create a ticket at https://github.com/pinterest/ktlint/issues " +
"(if possible, please re-run with the --debug flag to get the stacktrace " +
"(if possible, please re-run with the --log-level=debug flag to get the stacktrace " +
"and provide the source code that triggered an error)",
)
}
Expand Down Expand Up @@ -676,3 +692,17 @@ internal class KtlintCommandLine {
val output: String?,
)
}

private class LogLevelConverter : CommandLine.ITypeConverter<Level> {
@Throws(Exception::class)
override fun convert(value: String?): Level =
when (value?.uppercase()) {
"TRACE" -> Level.TRACE
"DEBUG" -> Level.DEBUG
"INFO" -> Level.INFO
"WARN" -> Level.WARN
"ERROR" -> Level.ERROR
"NONE" -> Level.OFF
else -> Level.INFO
}
}

0 comments on commit c9c86f4

Please sign in to comment.