-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathSourceFiles.kt
More file actions
254 lines (207 loc) · 7.69 KB
/
Copy pathSourceFiles.kt
File metadata and controls
254 lines (207 loc) · 7.69 KB
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
package org.javacs.kt
import com.intellij.openapi.util.text.StringUtil.convertLineSeparators
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.Language
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.eclipse.lsp4j.TextDocumentContentChangeEvent
import org.javacs.kt.util.KotlinLSException
import org.javacs.kt.util.filePath
import org.javacs.kt.util.partitionAroundLast
import org.javacs.kt.util.describeURIs
import org.javacs.kt.util.describeURI
import java.io.BufferedReader
import java.io.StringReader
import java.io.StringWriter
import java.io.IOException
import java.io.FileNotFoundException
import java.net.URI
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
private class SourceVersion(val content: String, val version: Int, val language: Language?, val isTemporary: Boolean)
/**
* Notify SourcePath whenever a file changes
*/
private class NotifySourcePath(private val sp: SourcePath) {
private val files = mutableMapOf<URI, SourceVersion>()
operator fun get(uri: URI): SourceVersion? = files[uri]
operator fun set(uri: URI, source: SourceVersion) {
val content = convertLineSeparators(source.content)
files[uri] = source
sp.put(uri, content, source.language, source.isTemporary)
}
fun remove(uri: URI) {
files.remove(uri)
sp.delete(uri)
}
fun removeIfTemporary(uri: URI): Boolean =
if (sp.deleteIfTemporary(uri)) {
files.remove(uri)
true
} else {
false
}
fun removeAll(rm: Collection<URI>) {
files -= rm
rm.forEach(sp::delete)
}
val keys get() = files.keys
}
/**
* Keep track of the text of all files in the workspace
*/
class SourceFiles(
private val sp: SourcePath,
private val contentProvider: URIContentProvider,
private val scriptsConfig: ScriptsConfiguration
) {
private val workspaceRoots = mutableSetOf<Path>()
private var exclusions = SourceExclusions(workspaceRoots, scriptsConfig)
private val files = NotifySourcePath(sp)
private val open = mutableSetOf<URI>()
fun open(uri: URI, content: String, version: Int) {
if (isIncluded(uri)) {
files[uri] = SourceVersion(content, version, languageOf(uri), isTemporary = false)
open.add(uri)
}
}
fun close(uri: URI) {
if (uri in open) {
open.remove(uri)
val removed = files.removeIfTemporary(uri)
if (!removed) {
val disk = readFromDisk(uri, temporary = false)
if (disk != null) {
files[uri] = disk
} else {
files.remove(uri)
}
}
}
}
fun edit(uri: URI, newVersion: Int, contentChanges: List<TextDocumentContentChangeEvent>) {
if (isIncluded(uri)) {
if (!isOpen(uri)) {
// There might be a case where the file is not have been opened yet if the configuration
// is changed to include/exclude certain files. In that case, we read it from disk first.
readFromDisk(uri, temporary = false)?.let {
files[uri] = it
} ?: LOG.warn("Could not read source file '{}'", uri.path)
}
val existing = files[uri]!!
var newText = existing.content
if (newVersion <= existing.version) {
LOG.warn("Ignored {} version {}", describeURI(uri), newVersion)
return
}
for (change in contentChanges) {
if (change.range == null) newText = change.text
else newText = patch(newText, change)
}
files[uri] = SourceVersion(newText, newVersion, existing.language, existing.isTemporary)
}
}
fun createdOnDisk(uri: URI) {
changedOnDisk(uri)
}
fun deletedOnDisk(uri: URI) {
if (isSource(uri)) {
files.remove(uri)
}
}
fun changedOnDisk(uri: URI) {
if (isSource(uri)) {
files[uri] = readFromDisk(uri, files[uri]?.isTemporary ?: true)
?: throw KotlinLSException("Could not read source file '$uri' after being changed on disk")
}
}
private fun readFromDisk(uri: URI, temporary: Boolean): SourceVersion? = try {
val content = contentProvider.contentOf(uri)
SourceVersion(content, -1, languageOf(uri), isTemporary = temporary)
} catch (e: FileNotFoundException) {
null
} catch (e: IOException) {
LOG.warn("Exception while reading source file {}", describeURI(uri))
null
}
private fun isSource(uri: URI): Boolean = isIncluded(uri) && languageOf(uri) != null
private fun languageOf(uri: URI): Language? {
val fileName = uri.filePath?.fileName?.toString() ?: return null
return when {
fileName.endsWith(".kt") || fileName.endsWith(".kts") -> KotlinLanguage.INSTANCE
else -> null
}
}
fun addWorkspaceRoot(root: Path) {
LOG.info("Searching $root using exclusions: ${exclusions.excludedPatterns}")
val addSources = findSourceFiles(root)
logAdded(addSources, root)
for (uri in addSources) {
readFromDisk(uri, temporary = false)?.let {
files[uri] = it
} ?: LOG.warn("Could not read source file '{}'", uri.path)
}
workspaceRoots.add(root)
updateExclusions()
}
fun removeWorkspaceRoot(root: Path) {
val rmSources = files.keys.filter { it.filePath?.startsWith(root) ?: false }
logRemoved(rmSources, root)
files.removeAll(rmSources)
workspaceRoots.remove(root)
updateExclusions()
}
private fun findSourceFiles(root: Path): Set<URI> {
val sourceMatcher = FileSystems.getDefault().getPathMatcher("glob:*.{kt,kts}")
return SourceExclusions(listOf(root), scriptsConfig)
.walkIncluded()
.filter { sourceMatcher.matches(it.fileName) }
.map(Path::toUri)
.toSet()
}
fun updateExclusions() {
exclusions = SourceExclusions(workspaceRoots, scriptsConfig)
LOG.info("Updated exclusions: ${exclusions.excludedPatterns}")
}
private fun isOpen(uri: URI): Boolean = (uri in open)
fun isIncluded(uri: URI): Boolean = exclusions.isURIIncluded(uri)
}
private fun patch(sourceText: String, change: TextDocumentContentChangeEvent): String {
val range = change.range
val reader = BufferedReader(StringReader(sourceText))
val writer = StringWriter()
// Skip unchanged lines
var line = 0
while (line < range.start.line) {
writer.write(reader.readLine() + '\n')
line++
}
// Skip unchanged chars
for (character in 0 until range.start.character) {
writer.write(reader.read())
}
// Write replacement text
writer.write(change.text)
// Skip replaced text
for (i in 0 until (range.end.line - range.start.line)) {
reader.readLine()
}
if (range.start.line == range.end.line) {
reader.skip((range.end.character - range.start.character).toLong())
} else {
reader.skip(range.end.character.toLong())
}
// Write remaining text
while (true) {
val next = reader.read()
if (next == -1) return writer.toString()
else writer.write(next)
}
}
private fun logAdded(sources: Collection<URI>, rootPath: Path?) {
LOG.info("Adding {} under {} to source path", describeURIs(sources), rootPath)
}
private fun logRemoved(sources: Collection<URI>, rootPath: Path?) {
LOG.info("Removing {} under {} to source path", describeURIs(sources), rootPath)
}