Skip to content

Commit c9c86f4

Browse files
* Replace CLI options --debug, --trace, --verbose and -v are with --log-level=<level> or the short version `-l=<level>. (#1658)
Closes #1652 Closes #1632
1 parent 28ff448 commit c9c86f4

File tree

9 files changed

+67
-31
lines changed

9 files changed

+67
-31
lines changed

.github/ISSUE_TEMPLATE/bug_report.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Please search in the [issues](https://github.com/pinterest/ktlint/issues) before
1616
## Observed Behavior
1717
<!---Tell us what happens instead of the expected behavior -->
1818
<!--- Provide the exact command which was executed but please -->
19-
<!--- ensure that the flag "--verbose" is added to the -->
19+
<!--- ensure that the flag "--log-level=debug" is added to the -->
2020
<!--- command as well. Provide the output of this command. -->
2121

2222
## Steps to Reproduce

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ Calling this API with a file path results in the `.editorconfig` files that will
2727

2828
### Changed
2929
* Update Kotlin development version to `1.7.20` and Kotlin version to `1.7.20`.
30+
* 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))
31+
* In CLI, disable logging entirely by setting `--log-level=none` or `-l=none` ([#1652](https://github.com/pinterest/ktlint/issue/1652))
32+
3033

3134
## [0.47.1] - 2022-09-07
3235

docs/extensions/custom-rule-set.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ $ echo 'var v = 0' > test.kt
2020
```
2121
2222
```shell title="Running the ktlint-ruleset-template" hl_lines="1 40 43"
23-
$ ktlint -R build/libs/ktlint-ruleset-template.jar --debug --relative test.kt
23+
$ ktlint -R build/libs/ktlint-ruleset-template.jar --log-level=debug --relative test.kt
2424
2525
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"
2626
18:13:21.241 [main] DEBUG com.pinterest.ktlint.Main - Discovered reporter with "baseline" id.

docs/install/cli.md

+11-6
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,9 @@ ktlint "src/**/*.kt" "!src/**/*Test.kt"
9696
ktlint "src/**/*.kt" "!src/**/generated/**"
9797
```
9898

99-
### Error reporting
99+
### Violation reporting
100100

101-
`ktlint` supports different type of reporters. When not specified the `plain` reporter is used. Optionally the `plain` reporter can group the violations per file.
101+
`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.
102102

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

121+
### Logging
122+
123+
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.
124+
125+
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`.
126+
121127
### Rule configuration (`.editorconfig`)
122128

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

146152
### Stdin && stdout
147153

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

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

160-
!!! tip Suppress error output
166+
!!! tip Suppress logging and error output
167+
Logging output printed to `stdout` can be suppressed by setting `--log-level=none` (see [logging](#logging)).
161168
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.
162169

163170

@@ -192,8 +199,6 @@ ktlint installGitPrePushHook
192199
`--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.
193200
Options `--stdin` and `--patterns-from-stdin` are mutually exclusive, only one of them can be given at a time.
194201

195-
`-v`, `--verbose` or `--debug`: Turn on debug output. Also option `--trace` is available, but this is meant for ktlint library developers.
196-
197202
`-V` or `--version`: Prints version information and exit.
198203

199204
### Microsoft Windows users

ktlint-reporter-plain/src/main/kotlin/com/pinterest/ktlint/reporter/plain/PlainReporter.kt

+1-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import java.util.concurrent.ConcurrentHashMap
1111

1212
public class PlainReporter(
1313
private val out: PrintStream,
14-
private val verbose: Boolean = false,
1514
private val groupByFile: Boolean = false,
1615
private val shouldColorOutput: Boolean = false,
1716
private val outputColor: Color = Color.DARK_GRAY,
@@ -42,7 +41,7 @@ public class PlainReporter(
4241
out.println(
4342
" $line${
4443
":${if (pad) String.format("%-3s", col) else "$col"}".colored()
45-
} $detail${if (verbose) " ($ruleId)".colored() else ""}",
44+
} $detail ${"($ruleId)".colored()}",
4645
)
4746
}
4847
}

ktlint-reporter-plain/src/main/kotlin/com/pinterest/ktlint/reporter/plain/PlainReporterProvider.kt

-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ public class PlainReporterProvider : ReporterProvider<PlainReporter> {
1111
override fun get(out: PrintStream, opt: Map<String, String>): PlainReporter =
1212
PlainReporter(
1313
out,
14-
verbose = opt["verbose"]?.emptyOrTrue() ?: false,
1514
groupByFile = opt["group_by_file"]?.emptyOrTrue() ?: false,
1615
shouldColorOutput = opt["color"]?.emptyOrTrue() ?: false,
1716
outputColor = getColor(opt["color_name"]),

ktlint-reporter-plain/src/test/kotlin/com/pinterest/ktlint/reporter/plain/PlainReporterTest.kt

+3-3
Original file line numberDiff line numberDiff line change
@@ -172,10 +172,10 @@ class PlainReporterTest {
172172
assertThat(String(out.toByteArray())).isEqualTo(
173173
"""
174174
/one-fixed-and-one-not.kt
175-
1:1 <"&'>
175+
1:1 <"&'> (rule-1)
176176
/two-not-fixed.kt
177-
1:10 I thought I would again
178-
2:20 A single thin straight line
177+
1:10 I thought I would again (rule-1)
178+
2:20 A single thin straight line (rule-2)
179179
180180
""".trimIndent().replace("\n", System.lineSeparator()),
181181
)

ktlint-ruleset-template/build.gradle.kts

+2-2
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,10 @@ tasks.register<JavaExec>("ktlint") {
4444
dependsOn(tasks.classes)
4545
group = LifecycleBasePlugin.VERIFICATION_GROUP
4646
mainClass.set("com.pinterest.ktlint.Main")
47-
// adding compiled classes to the classpath so that ktlint would validate project"s sources
47+
// adding compiled classes to the classpath so that ktlint would validate project's sources
4848
// using its own ruleset (in other words to dogfood)
4949
classpath(ktlint, sourceSets.main.map { it.output })
50-
args("--debug", "src/**/*.kt")
50+
args("--log-level=debug", "src/**/*.kt")
5151
}.let {
5252
tasks.check.configure {
5353
dependsOn(it)

ktlint/src/main/kotlin/com/pinterest/ktlint/internal/KtlintCommandLine.kt

+45-15
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,17 @@ internal class KtlintCommandLine {
116116

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

123124
@Option(
124125
names = ["--trace"],
125-
description = ["Turn on trace output"],
126+
description = ["Turn on trace output. Deprecated, use '--log-level=trace' instead."],
126127
)
127-
var trace: Boolean = false
128+
@Deprecated(message = "Replaced with minLogLevel")
129+
var trace: Boolean? = null
128130

129131
@Option(
130132
names = ["--disabled_rules"],
@@ -194,9 +196,10 @@ internal class KtlintCommandLine {
194196

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

201204
@Option(
202205
names = ["--editorconfig"],
@@ -224,14 +227,32 @@ internal class KtlintCommandLine {
224227
@Parameters(hidden = true)
225228
private var patterns = ArrayList<String>()
226229

230+
@Option(
231+
names = ["--log-level", "-l"],
232+
description = ["Defines the minimum log level (trace, debug, info, warn, error) or none to suppress all logging"],
233+
converter = [LogLevelConverter::class],
234+
)
235+
private var minLogLevel: Level = Level.INFO
236+
227237
private val tripped = AtomicBoolean()
228238
private val fileNumber = AtomicInteger()
229239
private val errorNumber = AtomicInteger()
230240

241+
internal var debug: Boolean = false
242+
get() = Level.DEBUG.isGreaterOrEqual(minLogLevel)
243+
private set
244+
231245
fun run() {
232-
if (verbose) {
233-
debug = true
246+
if (debugOld != null || trace != null || verbose != null) {
247+
if (minLogLevel == Level.OFF) {
248+
minLogLevel = Level.ERROR
249+
}
250+
configureLogger().error {
251+
"Options '--debug', '--trace', '--verbose' and '-v' are deprecated and replaced with option '--log-level=<level>' or '-l=<level>'."
252+
}
253+
exitProcess(1)
234254
}
255+
235256
logger = configureLogger()
236257

237258
assertStdinAndPatternsFromStdinOptionsMutuallyExclusive()
@@ -311,11 +332,7 @@ internal class KtlintCommandLine {
311332
KotlinLogging
312333
.logger {}
313334
.setDefaultLoggerModifier { logger ->
314-
(logger.underlyingLogger as Logger).level = when {
315-
trace -> Level.TRACE
316-
debug -> Level.DEBUG
317-
else -> Level.INFO
318-
}
335+
(logger.underlyingLogger as Logger).level = minLogLevel
319336
}
320337
.initKtLintKLogger()
321338

@@ -471,7 +488,6 @@ internal class KtlintCommandLine {
471488
reporterId,
472489
split.lastOrNull { it.startsWith("artifact=") }?.let { it.split("=")[1] },
473490
mapOf(
474-
"verbose" to verbose.toString(),
475491
"color" to color.toString(),
476492
"color_name" to colorName,
477493
"format" to format.toString(),
@@ -541,7 +557,7 @@ internal class KtlintCommandLine {
541557
"",
542558
"Internal Error (${e.ruleId}) in file '$filename' at position '${e.line}:${e.col}. " +
543559
"Please create a ticket at https://github.com/pinterest/ktlint/issues " +
544-
"(if possible, please re-run with the --debug flag to get the stacktrace " +
560+
"(if possible, please re-run with the --log-level=debug flag to get the stacktrace " +
545561
"and provide the source code that triggered an error)",
546562
)
547563
}
@@ -676,3 +692,17 @@ internal class KtlintCommandLine {
676692
val output: String?,
677693
)
678694
}
695+
696+
private class LogLevelConverter : CommandLine.ITypeConverter<Level> {
697+
@Throws(Exception::class)
698+
override fun convert(value: String?): Level =
699+
when (value?.uppercase()) {
700+
"TRACE" -> Level.TRACE
701+
"DEBUG" -> Level.DEBUG
702+
"INFO" -> Level.INFO
703+
"WARN" -> Level.WARN
704+
"ERROR" -> Level.ERROR
705+
"NONE" -> Level.OFF
706+
else -> Level.INFO
707+
}
708+
}

0 commit comments

Comments
 (0)