forked from pinterest/ktlint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileUtils.kt
272 lines (246 loc) · 8.69 KB
/
FileUtils.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package com.pinterest.ktlint.internal
import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.core.RuleProvider
import com.pinterest.ktlint.core.api.EditorConfigDefaults
import com.pinterest.ktlint.core.api.EditorConfigOverride
import com.pinterest.ktlint.core.initKtLintKLogger
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
import java.nio.file.attribute.BasicFileAttributes
import kotlin.io.path.isDirectory
import kotlin.system.exitProcess
import kotlin.system.measureTimeMillis
import mu.KotlinLogging
import org.jetbrains.kotlin.util.prefixIfNot
private val logger = KotlinLogging.logger {}.initKtLintKLogger()
internal val workDir: String = File(".").canonicalPath
private val tildeRegex = Regex("^(!)?~")
private const val NEGATION_PREFIX = "!"
private val userHome = System.getProperty("user.home")
private val defaultKotlinFileExtensions = setOf("kt", "kts")
internal val defaultPatterns = defaultKotlinFileExtensions.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.
*/
internal fun FileSystem.fileSequence(
patterns: List<String>,
rootDir: Path = Paths.get(".").toAbsolutePath().normalize(),
): Sequence<Path> {
val result = mutableListOf<Path>()
val (existingFiles, patternsExclusiveExistingFiles) = patterns.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() && patternsExclusiveExistingFiles.isEmpty()) {
return result.asSequence()
}
val globs = expand(patternsExclusiveExistingFiles, rootDir)
val pathMatchers = if (globs.isEmpty()) {
defaultPatterns
.map { getPathMatcher("glob:$it") }
.toSet()
} else {
globs
.filterNot { it.startsWith(NEGATION_PREFIX) }
.map { getPathMatcher(it) }
}
val negatedPathMatchers = if (globs.isEmpty()) {
emptySet()
} else {
globs
.filter { it.startsWith(NEGATION_PREFIX) }
.map { getPathMatcher(it.removePrefix(NEGATION_PREFIX)) }
}
logger.debug {
"""
Start walkFileTree for rootDir: '$rootDir'
include:
${pathMatchers.map { " - $it" }}
exlcude:
${negatedPathMatchers.map { " - $it" }}
""".trimIndent()
}
val duration = measureTimeMillis {
Files.walkFileTree(
rootDir,
object : SimpleFileVisitor<Path>() {
override fun visitFile(
filePath: Path,
fileAttrs: BasicFileAttributes,
): FileVisitResult {
if (negatedPathMatchers.none { it.matches(filePath) } &&
pathMatchers.any { it.matches(filePath) }
) {
logger.trace { "- File: $filePath: Include" }
result.add(filePath)
} else {
logger.trace { "- File: $filePath: Ignore" }
}
return FileVisitResult.CONTINUE
}
override fun preVisitDirectory(
dirPath: Path,
dirAttr: BasicFileAttributes,
): FileVisitResult {
return if (Files.isHidden(dirPath)) {
logger.trace { "- Dir: $dirPath: Ignore" }
FileVisitResult.SKIP_SUBTREE
} else {
logger.trace { "- Dir: $dirPath: Traverse" }
FileVisitResult.CONTINUE
}
}
},
)
}
logger.debug { "Discovered ${result.count()} files to be processed in $duration ms" }
return result.asSequence()
}
private fun FileSystem.expand(
patterns: List<String>,
rootDir: Path,
) =
patterns
.map { it.expandTildeToFullPath() }
.map {
if (onWindowsOS) {
// By definition the globs should use "/" as separator. Out of courtesy replace "\" with "/"
it.replace(File.separator, "/")
} else {
it
}
}.flatMap { path -> toGlob(path, rootDir) }
private fun FileSystem.toGlob(
path: String,
rootDir: Path,
): List<String> {
val negation = if (path.startsWith(NEGATION_PREFIX)) {
NEGATION_PREFIX
} else {
""
}
val pathWithoutNegationPrefix = path.removePrefix(NEGATION_PREFIX)
val resolvedPath = try {
rootDir.resolve(pathWithoutNegationPrefix)
} catch (e: InvalidPathException) {
// Windows throws an exception when you pass a glob to Path#resolve.
null
}
val expandedGlobs = if (resolvedPath != null && resolvedPath.isDirectory()) {
getDefaultPatternsForPath(resolvedPath)
} else if (isGlobAbsolutePath(pathWithoutNegationPrefix)) {
listOf(pathWithoutNegationPrefix)
} else {
listOf(pathWithoutNegationPrefix.prefixIfNot("**/"))
}
return expandedGlobs.map { "${negation}glob:$it" }
}
private fun getDefaultPatternsForPath(path: Path?) = defaultKotlinFileExtensions
.flatMap {
listOf(
"$path/*.$it",
"$path/**/*.$it",
)
}
private fun FileSystem.isGlobAbsolutePath(glob: String) =
rootDirectories
.map { it.toString() }
.any { glob.startsWith(it) }
/**
* List of paths to Java `jar` files.
*/
internal typealias JarFiles = List<String>
internal fun JarFiles.toFilesURIList() = map {
val jarFile = File(it.expandTildeToFullPath())
if (!jarFile.exists()) {
logger.error { "File $it does not exist" }
exitProcess(1)
}
jarFile.toURI().toURL()
}
// a complete solution would be to implement https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html
// this implementation takes care only of the most commonly used case (~/)
internal fun String.expandTildeToFullPath(): String =
if (onWindowsOS) {
// Windows sometimes inserts `~` into paths when using short directory names notation, e.g. `C:\Users\USERNA~1\Documents
this
} else {
replaceFirst(tildeRegex, userHome)
}
private val onWindowsOS
get() =
System
.getProperty("os.name")
.startsWith("windows", true)
internal fun File.location(
relative: Boolean,
) = if (relative) this.toRelativeString(File(workDir)) else this.path
/**
* Run lint over common kotlin file or kotlin script file.
*/
internal fun lintFile(
fileName: String,
fileContents: String,
ruleProviders: Set<RuleProvider>,
editorConfigDefaults: EditorConfigDefaults,
editorConfigOverride: EditorConfigOverride,
editorConfigPath: String? = null,
debug: Boolean = false,
lintErrorCallback: (LintError) -> Unit = {},
) = KtLint.lint(
KtLint.ExperimentalParams(
fileName = fileName,
text = fileContents,
ruleProviders = ruleProviders,
script = !fileName.endsWith(".kt", ignoreCase = true),
editorConfigDefaults = editorConfigDefaults,
editorConfigOverride = editorConfigOverride,
editorConfigPath = editorConfigPath,
cb = { e, _ ->
lintErrorCallback(e)
},
debug = debug,
isInvokedFromCli = true,
),
)
/**
* Format a kotlin file or script file
*/
internal fun formatFile(
fileName: String,
fileContents: String,
ruleProviders: Set<RuleProvider>,
editorConfigDefaults: EditorConfigDefaults,
editorConfigOverride: EditorConfigOverride,
editorConfigPath: String?,
debug: Boolean,
cb: (e: LintError, corrected: Boolean) -> Unit,
): String =
KtLint.format(
KtLint.ExperimentalParams(
fileName = fileName,
text = fileContents,
ruleProviders = ruleProviders,
script = !fileName.endsWith(".kt", ignoreCase = true),
editorConfigDefaults = editorConfigDefaults,
editorConfigOverride = editorConfigOverride,
editorConfigPath = editorConfigPath,
cb = cb,
debug = debug,
isInvokedFromCli = true,
),
)