-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathYamlPath.kt
More file actions
47 lines (39 loc) · 1.47 KB
/
YamlPath.kt
File metadata and controls
47 lines (39 loc) · 1.47 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
package dev.protsenko.securityLinter.utils
import com.intellij.psi.PsiElement
import org.jetbrains.yaml.psi.YAMLDocument
import org.jetbrains.yaml.psi.YAMLMapping
import org.jetbrains.yaml.psi.YAMLSequence
object YamlPath {
fun findByYamlPath(
path: String,
document: YAMLDocument,
): PsiElement? {
val matchedElement: YAMLMapping = document.children[0] as? YAMLMapping ?: return null
return findByYamlPath(path, matchedElement)
}
fun findByYamlPath(
path: String,
matchedElement: YAMLMapping,
): PsiElement? {
val searchTokens = path.split(".")
var startElement: PsiElement? = matchedElement
var countMatches = 0
for (token in searchTokens) {
if (token.endsWith("]")) {
val yamlKey = token.substringBefore("[")
val sequence =
(startElement as? YAMLMapping)?.getKeyValueByKey(yamlKey)?.value as? YAMLSequence ?: break
val index = token.substringAfter("[").substringBefore("]").toIntOrNull() ?: break
startElement = sequence.items.getOrNull(index)?.value as? YAMLMapping
countMatches++
} else {
startElement = (startElement as? YAMLMapping)?.getKeyValueByKey(token)?.value ?: break
countMatches++
}
}
if (countMatches == searchTokens.size) {
return startElement
}
return null
}
}