Skip to content

Commit

Permalink
Disabling default patterns if the option --patterns-from-stdin is g…
Browse files Browse the repository at this point in the history
…iven (#1801)

Fixes issue #1793.

Co-authored-by: paul-dingemans <[email protected]>
  • Loading branch information
mfederczuk and paul-dingemans authored Feb 13, 2023
1 parent 6fc6f44 commit 984b94f
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 30 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).

### Changed

* Disable the default patterns if the option `--patterns-from-stdin` is specified ([#1793](https://github.com/pinterest/ktlint/issues/1793))
* Update Kotlin development version to `1.8.20-Beta` and Kotlin version to `1.8.10`.
* Revert to matrix build to speed up build, especially for the Windows related build ([#1786](https://github.com/pinterest/ktlint/pull/1787))

Expand Down
1 change: 1 addition & 0 deletions docs/install/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ ktlint installGitPrePushHook
`--relative`: Print files relative to the working directory (e.g. dir/file.kt instead of /home/user/project/dir/file.kt)

`--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.
If this option is given, then the default patterns are disabled.
Options `--stdin` and `--patterns-from-stdin` are mutually exclusive, only one of them can be given at a time.

`-V` or `--version`: Prints version information and exit.
Expand Down
16 changes: 4 additions & 12 deletions ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import org.jetbrains.kotlin.util.prefixIfNot

private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()

internal val WORK_DIR: String = File(".").canonicalPath
private val WORK_DIR: String = File(".").canonicalPath

private val TILDE_REGEX = Regex("^(!)?~")
private const val NEGATION_PREFIX = "!"
Expand All @@ -35,7 +35,7 @@ internal val DEFAULT_PATTERNS = DEFAULT_KOTLIN_FILE_EXTENSIONS.map { "**/*.$it"

/**
* Transform the [patterns] to a sequence of files. Each element in [patterns] can be a glob, a file or directory path
* relative to the [rootDir] or a absolute file or directory path.
* relative to the [rootDir] or an absolute file or directory path.
*/
internal fun FileSystem.fileSequence(
patterns: List<String>,
Expand All @@ -60,23 +60,15 @@ internal fun FileSystem.fileSequence(

val globs = expand(patternsExclusiveExistingFiles, rootDir)

val pathMatchers = if (globs.isEmpty()) {
DEFAULT_PATTERNS
.map { getPathMatcher("glob:$it") }
.toSet()
} else {
val pathMatchers =
globs
.filterNot { it.startsWith(NEGATION_PREFIX) }
.map { getPathMatcher(it) }
}

val negatedPathMatchers = if (globs.isEmpty()) {
emptySet()
} else {
val negatedPathMatchers =
globs
.filter { it.startsWith(NEGATION_PREFIX) }
.map { getPathMatcher(it.removePrefix(NEGATION_PREFIX)) }
}

LOGGER.debug {
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ internal class KtlintCommandLine {
private var baselinePath: String = ""

@Parameters(hidden = true)
private var patterns = ArrayList<String>()
private var patterns = emptyList<String>()

@Option(
names = ["--log-level", "-l"],
Expand Down Expand Up @@ -287,16 +287,7 @@ internal class KtlintCommandLine {
}

assertStdinAndPatternsFromStdinOptionsMutuallyExclusive()

val stdinPatterns: Set<String> = readPatternsFromStdin()
patterns.addAll(stdinPatterns)

// Set default value to patterns only after the logger has been configured to avoid a warning about initializing
// the logger multiple times
if (patterns.isEmpty()) {
logger.info { "Enable default patterns $DEFAULT_PATTERNS" }
patterns = ArrayList(DEFAULT_PATTERNS)
}
patterns = patterns.replaceWithPatternsFromStdinOrDefaultPatternsWhenEmpty()

val start = System.currentTimeMillis()

Expand Down Expand Up @@ -350,6 +341,31 @@ internal class KtlintCommandLine {
}
}

private fun List<String>.replaceWithPatternsFromStdinOrDefaultPatternsWhenEmpty(): List<String> {
val localStdinDelimiter: String? = stdinDelimiter
return when {
localStdinDelimiter != null -> {
val stdinPatterns: Set<String> = readPatternsFromStdin(localStdinDelimiter.ifEmpty { "\u0000" })
if (isNotEmpty() && stdinPatterns.isNotEmpty()) {
logger.warn {
"Patterns specified at command line (${this@KtlintCommandLine.patterns}) and patterns from 'stdin' due to flag '--patterns-from-stdin' " +
"($stdinPatterns) are merged"
}
}
// Note: it is okay in case both the original patterns and the patterns from stdin are empty
this.plus(stdinPatterns)
}
this.isEmpty() -> {
logger.info { "Enable default patterns $DEFAULT_PATTERNS" }
DEFAULT_PATTERNS
}
else -> {
// Keep original patterns
this
}
}
}

// Do not convert to "val" as the function depends on PicoCli options which are not fully instantiated until the "run" method is started
internal fun ruleProviders(): Set<RuleProvider> =
rulesetJarPaths
Expand Down Expand Up @@ -381,7 +397,7 @@ internal class KtlintCommandLine {
if (stdin && stdinDelimiter != null) {
throw ParameterException(
commandSpec.commandLine(),
"Options --stdin and --patterns-from-stdin mutually exclusive",
"Options --stdin and --patterns-from-stdin are mutually exclusive",
)
}
}
Expand Down Expand Up @@ -598,10 +614,8 @@ internal class KtlintCommandLine {
map
}

private fun readPatternsFromStdin(): Set<String> {
val delimiter: String = stdinDelimiter
?.ifEmpty { "\u0000" }
?: return emptySet()
private fun readPatternsFromStdin(delimiter: String): Set<String> {
require(delimiter.isNotEmpty())

return String(System.`in`.readBytes())
.split(delimiter)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ internal class PrintASTSubCommand : Runnable {
printAST(fileContent = String(System.`in`.readBytes()))
} else {
FileSystems.getDefault()
.fileSequence(patterns)
.fileSequence(patterns.ifEmpty { DEFAULT_PATTERNS })
.map { it.toFile() }
.forEach {
printAST(
Expand Down
39 changes: 39 additions & 0 deletions ktlint/src/test/kotlin/com/pinterest/ktlint/SimpleCLITest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,27 @@ class SimpleCLITest {
}
}

@Test
fun `Given some code with an error but no patterns given return from lint with the error exit code and error output (default patterns)`(
@TempDir
tempDir: Path,
) {
CommandLineTestRunner(tempDir)
.run(
"too-many-empty-lines",
emptyList(),
) {
SoftAssertions()
.apply {
assertErrorExitCode()
assertThat(normalOutput)
.containsLineMatching("Enable default patterns")
.containsLineMatching("Needless blank line(s)")
}
.assertAll()
}
}

@Test
fun `Given some code with an error which can be autocorrected then return from from with the normal exit code`(
@TempDir
Expand Down Expand Up @@ -153,6 +174,24 @@ class SimpleCLITest {
}
}

@Test
fun `Issue 1793 - Given some code with an error and no patterns read in from stdin then return nothing `(
@TempDir
tempDir: Path,
) {
CommandLineTestRunner(tempDir)
.run(
"too-many-empty-lines",
listOf("--patterns-from-stdin"),
stdin = ByteArrayInputStream(ByteArray(0)),
) {
assertNormalExitCode()
assertThat(normalOutput)
.doesNotContainLineMatching("Enable default patterns")
.containsLineMatching("No files matched []")
}
}

@Test
fun `Issue 1608 - --relative and --reporter=sarif should play well together`(
@TempDir
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ internal class FileUtilsTest {
}

private fun getFiles(
patterns: List<String> = emptyList(),
patterns: List<String> = DEFAULT_PATTERNS,
rootDir: Path = tempFileSystem.rootDirectories.first(),
): List<String> = tempFileSystem
.fileSequence(patterns, rootDir)
Expand Down

0 comments on commit 984b94f

Please sign in to comment.