aboutsummaryrefslogtreecommitdiff
path: root/plugins/base/src/main/kotlin/parsers/moduleAndPackage/parseModuleAndPackageDocumentationFragments.kt
blob: 7dcaccfa40d4cb33709141b2ba52034f778ef127 (plain)
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
package org.jetbrains.dokka.base.parsers.moduleAndPackage

import org.jetbrains.dokka.base.parsers.moduleAndPackage.ModuleAndPackageDocumentation.Classifier.*
import java.io.File


internal fun parseModuleAndPackageDocumentationFragments(source: File): List<ModuleAndPackageDocumentationFragment> {
    return parseModuleAndPackageDocumentationFragments(ModuleAndPackageDocumentationFile(source))
}

internal fun parseModuleAndPackageDocumentationFragments(
    source: ModuleAndPackageDocumentationSource
): List<ModuleAndPackageDocumentationFragment> {
    val fragmentStrings = source.documentation.split(Regex("(|^)#\\s*(?=(Module|Package))"))
    return fragmentStrings
        .filter(String::isNotBlank)
        .map { fragmentString -> parseModuleAndPackageDocFragment(source, fragmentString) }
}

private fun parseModuleAndPackageDocFragment(
    source: ModuleAndPackageDocumentationSource,
    fragment: String
): ModuleAndPackageDocumentationFragment {
    val firstLineAndDocumentation = fragment.split("\r\n", "\n", "\r", limit = 2)
    val firstLine = firstLineAndDocumentation[0]

    val classifierAndName = firstLine.split(Regex("\\s+"), limit = 2)

    val classifier = when (classifierAndName[0].trim()) {
        "Module" -> Module
        "Package" -> Package
        else -> throw IllegalStateException("Unexpected classifier ${classifierAndName[0]}")
    }

    if (classifierAndName.size != 2 && classifier == Module) {
        throw IllegalModuleAndPackageDocumentation(source, "Missing Module name")
    }

    val name = classifierAndName.getOrNull(1)?.trim().orEmpty()
    if (classifier == Package && name.contains(Regex("\\s"))) {
        throw IllegalModuleAndPackageDocumentation(
            source, "Package name cannot contain whitespace in '$firstLine'"
        )
    }

    return ModuleAndPackageDocumentationFragment(
        name = name,
        classifier = classifier,
        documentation = firstLineAndDocumentation.getOrNull(1)?.trim().orEmpty(),
        source = source
    )
}