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

Support absolute paths for globs #1199

Merged
merged 6 commits into from
Aug 6, 2021
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ This project adheres to [Semantic Versioning](http://semver.org/).
### Added

### Fixed

### Changed
- Support absolute paths for globs ([#1131](https://github.com/pinterest/ktlint/issues/1131))
- Fix regression from 0.41 with argument list wrapping after dot qualified expression (`argument-list-wrapping`)([#1159](https://github.com/pinterest/ktlint/issues/1159))

### Removed
Expand Down
59 changes: 31 additions & 28 deletions ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ internal fun FileSystem.fileSequence(
globs: List<String>,
rootDir: Path = Paths.get(".").toAbsolutePath().normalize()
): Sequence<Path> {
checkGlobsContainAbsolutePath(globs)

val result = mutableListOf<Path>()

val (existingFiles, actualGlobs) = globs.partition {
Expand All @@ -50,7 +48,7 @@ internal fun FileSystem.fileSequence(
actualGlobs
.filterNot { it.startsWith("!") }
.map {
getPathMatcher(it.toGlob(rootDir))
getPathMatcher(toGlob(it, rootDir))
}
}

Expand All @@ -59,7 +57,9 @@ internal fun FileSystem.fileSequence(
} else {
actualGlobs
.filter { it.startsWith("!") }
.map { getPathMatcher(it.removePrefix("!").toGlob(rootDir)) }
.map {
getPathMatcher(toGlob(it.removePrefix("!"), rootDir))
}
}

Files.walkFileTree(
Expand Down Expand Up @@ -93,37 +93,40 @@ internal fun FileSystem.fileSequence(
return result.asSequence()
}

private fun FileSystem.checkGlobsContainAbsolutePath(globs: List<String>) {
private fun FileSystem.isGlobAbsolutePath(glob: String): Boolean {
val rootDirs = rootDirectories.map { it.toString() }
globs
.map { it.removePrefix("!") }
.filter { glob ->
rootDirs.any { glob.startsWith(it) }
}
.run {
if (isNotEmpty()) {
throw IllegalArgumentException(
"KtLint does not support absolute path in globs:\n${joinToString(separator = "\n")}"
)
}
}
return rootDirs.any { glob.removePrefix("!").startsWith(it) }
}

private fun String.toGlob(
internal fun FileSystem.toGlob(
pattern: String,
rootDir: Path
): String {
val expandedPath = expandTilde(this)
val rootDirPath = rootDir
.toAbsolutePath()
.toString()
.run {
val normalizedPath = if (!endsWith(File.separator)) "$this${File.separator}" else this
normalizedPath.replace(File.separator, globSeparator)
}
return "glob:$rootDirPath$expandedPath"
val os = System.getProperty("os.name")
val expandedPath = if (os.startsWith("windows", true)) {
// Windows sometimes inserts `~` into paths when using short directory names notation, e.g. `C:\Users\USERNA~1\Documents
pattern
} else {
expandTilde(pattern)
}

val fullPath = if (isGlobAbsolutePath(expandedPath)) {
expandedPath
} else {
val rootDirPath = rootDir
.toAbsolutePath()
.toString()
.run {
val normalizedPath = if (!endsWith(File.separator)) "$this${File.separator}" else this
normalizedPath
}
"$rootDirPath$expandedPath"
}
.replace(File.separator, globSeparator)
return "glob:$fullPath"
}

internal val globSeparator: String get() {
private val globSeparator: String get() {
val os = System.getProperty("os.name")
return when {
os.startsWith("windows", ignoreCase = true) -> "\\\\"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.hamcrest.CoreMatchers
import org.junit.After
import org.junit.Assume
import org.junit.Before
import org.junit.Test

Expand Down Expand Up @@ -123,26 +124,67 @@ internal class FileUtilsFileSequenceTest {
}

@Test
fun `Should fail the search when glob contain absolute path`() {
fun `Should support unescaped slashes for Windows`() {
Assume.assumeThat(System.getProperty("os.name").toLowerCase(), CoreMatchers.startsWith("windows"))

val foundFiles = getFiles(
listOf(
"project1\\src\\**\\*.kt".normalizeGlob(),
"!project1\\src\\**\\example\\*.kt".normalizeGlob()
)
)

assertThat(foundFiles).hasSize(1)
assertThat(foundFiles).containsAll(project1Files.subList(3, 4))
}

@Test
fun `Should support absolute paths`() {
val globs = listOf(
"src/main/kotlin/One.kt".normalizeGlob(),
"!${rootDir}project1/src/main/kotlin/example/Two.kt".normalizeGlob()
"${rootDir}project1/src/main/kotlin/example/Two.kt".normalizeGlob()
)

try {
getFiles(
patterns = globs
)
fail("No exception was thrown!")
} catch (e: IllegalArgumentException) {
assertThat(e.message).contains(
globs.last().removePrefix("!")
)
}
val files = getFiles(
patterns = globs,
rootDir = tempFileSystem.getPath("${rootDir}project1".normalizePath())
)
assertThat(files).containsExactlyElementsOf(
project1Files.subList(3, 5)
)
}

@Test
fun `Should support globs containing absolute paths`() {
val globs = listOf(
"${rootDir}project1/src/**/*.kt".normalizeGlob()
)

val files = getFiles(
patterns = globs,
rootDir = tempFileSystem.getPath("${rootDir}project1".normalizePath())
)
assertThat(files).containsExactlyElementsOf(
project1Files.subList(3, 5)
)
}

@Test
fun `transforming globs with leading tilde`() {
Assume.assumeThat(System.getProperty("os.name").toLowerCase(), CoreMatchers.startsWith("linux"))

val glob = tempFileSystem.toGlob(
"~/project/src/main/kotlin/One.kt",
File(rootDir).toPath()
)
val homeDir = System.getProperty("user.home")
assertThat(glob).isEqualTo(
"glob:$homeDir/project/src/main/kotlin/One.kt"
)
}

private fun String.normalizePath() = replace('/', File.separatorChar)
private fun String.normalizeGlob(): String = replace("/", globSeparator)
private fun String.normalizeGlob(): String = replace("/", rawGlobSeparator)

private fun List<String>.createFiles() = forEach {
val filePath = tempFileSystem.getPath(it)
Expand All @@ -159,3 +201,11 @@ internal class FileUtilsFileSequenceTest {
.map { it.toString() }
.toList()
}

internal val rawGlobSeparator: String get() {
val os = System.getProperty("os.name")
return when {
os.startsWith("windows", ignoreCase = true) -> "\\"
else -> "/"
}
}