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>.

Closes pinterest#1632

* Allow disabling logging in CLI by setting `--log-level=none` or `-l=none`.

Closes pinterest#1652
  • Loading branch information
paul-dingemans committed Sep 23, 2022
1 parent 4a91d2d commit 6b7739d
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 36 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 @@ -15,6 +15,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).

### Changed

* 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
11 changes: 6 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@ task ktlint(type: JavaExec, group: LifecycleBasePlugin.VERIFICATION_GROUP) {
// Exclude sources which contain lint violations for the purpose of testing.
'!ktlint/src/test/resources/**',
'--baseline=ktlint/src/test/resources/test-baseline.xml',
// Experimental rules run by default run on the ktlint code base itself. Experimental rules should not be released if
// we are not pleased ourselves with the results on the ktlint code base.
'--experimental'
// Do not run with option "--verbose" or "-v" as the lint violations are difficult to spot between the amount of
// debug output lines.
// Experimental rules run by default run on the ktlint code base itself. Experimental rules should not be released
// if we are not pleased ourselves with the results on the ktlint code base.
'--experimental',
// Run with log-level error so that all lint violations can be spotted easily and are not drowned in a lot of log
// lines.
'--log-level=error'
}

// Deployment tasks
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 @@ -189,8 +196,6 @@ ktlint installGitPrePushHook

`--relative`: Print files relative to the working directory (e.g. dir/file.kt instead of /home/user/project/dir/file.kt)

`-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.get().output
args("--debug", "src/**/*.kt")
args("--log-level=debug", "src/**/*.kt")
}.let {
tasks.check.get().dependsOn(it)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import kotlin.system.exitProcess
import mu.KLogger
import mu.KotlinLogging
import org.jetbrains.kotlin.utils.addToStdlib.applyIf
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
Expand Down Expand Up @@ -111,15 +112,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 @@ -177,9 +180,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 @@ -207,14 +211,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()

// Set default value to patterns only after the logger has been configured to avoid a warning about initializing
Expand Down Expand Up @@ -289,11 +311,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 @@ -440,7 +458,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 @@ -510,7 +527,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 @@ -633,3 +650,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 6b7739d

Please sign in to comment.