Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve ktlint performances when the input patterns are absolute paths #1144

Merged
merged 1 commit into from
Jun 15, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import java.io.File
import java.nio.file.FileSystem
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.SimpleFileVisitor
Expand All @@ -23,28 +24,44 @@ internal fun FileSystem.fileSequence(
): Sequence<Path> {
checkGlobsContainAbsolutePath(globs)

val pathMatchers = if (globs.isEmpty()) {
val result = mutableListOf<Path>()

val (existingFiles, actualGlobs) = globs.partition {
try {
Files.isRegularFile(rootDir.resolve(it))
} catch (e: InvalidPathException) {
// Windows throws an exception when you pass a glob to Path#resolve.
false
}
}
existingFiles.mapTo(result) { rootDir.resolve(it) }

// Return early and don't traverse the file system if all the input globs are absolute paths
if (result.isNotEmpty() && actualGlobs.isEmpty()) {
return result.asSequence()
}

val pathMatchers = if (actualGlobs.isEmpty()) {
setOf(
getPathMatcher("glob:**$globSeparator*.kt"),
getPathMatcher("glob:**$globSeparator*.kts")
)
} else {
globs
actualGlobs
.filterNot { it.startsWith("!") }
.map {
getPathMatcher(it.toGlob(rootDir))
}
}

val negatedPathMatchers = if (globs.isEmpty()) {
val negatedPathMatchers = if (actualGlobs.isEmpty()) {
emptySet()
} else {
globs
actualGlobs
.filter { it.startsWith("!") }
.map { getPathMatcher(it.removePrefix("!").toGlob(rootDir)) }
}

val result = mutableListOf<Path>()
Files.walkFileTree(
rootDir,
object : SimpleFileVisitor<Path>() {
Expand Down