-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathGeneratePluginDocsTask.kt
More file actions
248 lines (204 loc) · 9.86 KB
/
GeneratePluginDocsTask.kt
File metadata and controls
248 lines (204 loc) · 9.86 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
/*
* Copyright (C) 2025 The ORT Project Copyright Holders <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
import groovy.json.JsonSlurper
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.file.FileTree
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
abstract class GeneratePluginDocsTask : DefaultTask() {
init {
group = "Documentation"
description = "Generate documentation for the plugins."
}
@get:InputFiles
abstract var inputFiles: FileTree
@OutputDirectory
val outputDirectory = project.layout.projectDirectory.file("website/docs/plugins").asFile
@Internal
val jsonSlurper = JsonSlurper()
@TaskAction
fun generatePluginDocs() {
if (inputFiles.files.isEmpty()) {
throw GradleException("No plugin descriptions found, make sure to provide input files to this task.")
}
logger.lifecycle("Generating plugin documentation.")
generatePluginDocs("advisors", "advisor")
generatePluginDocs("license-fact-providers")
generatePluginDocs("package-configuration-providers")
generatePluginDocs("package-curation-providers")
generatePluginDocs("package-managers", "analyzer")
generatePluginDocs("reporters", "reporter")
generatePluginDocs("scanners", "scanner")
logger.lifecycle("Found a total of ${inputFiles.count()} plugins.")
}
private fun generatePluginDocs(pluginType: String, tool: String? = null) {
val plugins = inputFiles.filter { "plugins/$pluginType" in it.invariantSeparatorsPath }
val dir = outputDirectory.resolve(pluginType).apply { mkdirs() }
val pluginTypeParts = pluginType.split('-')
val pluginTypeCamelCase = pluginTypeParts.joinToString("") { it.replaceFirstChar(Char::uppercase) }
.replaceFirstChar(Char::lowercase)
logger.lifecycle("Found ${plugins.count()} ${pluginTypeParts.joinToString(" ")}:")
plugins.sorted().forEach { file ->
val json = checkNotNull(jsonSlurper.parse(file) as? Map<*, *>)
val descriptor = checkNotNull(json["descriptor"] as? Map<*, *>)
val outputFile = dir.resolve("${descriptor["displayName"]}.md")
val markdown = buildString {
// Set max heading level so that option sections are visible in the TOC.
appendLine("---")
appendLine("toc_max_heading_level: 4")
appendLine("---")
appendLine()
// Write header.
appendLine("# ${descriptor["displayName"]}")
appendLine()
appendLine("![${descriptor["id"]}](https://img.shields.io/badge/Plugin_ID-${descriptor["id"]}-gold)")
appendLine()
appendLine("***${descriptor["summary"]}***")
appendLine()
descriptor["description"].takeIf { it != null && it != descriptor["summary"]}?.also {
appendLine("## Description")
appendLine()
appendLine(convertKdocLinks(it as String))
appendLine()
}
val allOptions = ((descriptor["options"]) as List<*>).map { it as Map<*, *> }
if (allOptions.isEmpty()) return@buildString
val (options, secrets) = allOptions.partition { it["type"] != "SECRET" }
appendLine("## Configuration")
appendLine()
// Write example configuration.
appendLine("### Example")
appendLine()
fun appendOptionsAndSecrets(startIndent: Int, pluginType: String) {
val indent = if (tool != null) {
append(" ".repeat(startIndent))
appendLine("$tool:")
startIndent + 2
} else {
startIndent
}
val i = " ".repeat(indent)
appendLine("$i$pluginType:")
appendLine("$i ${descriptor["id"]}:")
fun appendOptions(options: List<Map<*, *>>) {
options.forEach {
val defaultValue = it["default"]
val type = it["type"]
val isStringValue = type == "SECRET" || type == "STRING" || type == "STRING_LIST"
append("$i ${it["name"]}: ")
if (defaultValue != null) {
if (isStringValue) append("\"")
append(defaultValue)
if (isStringValue) append("\"")
} else {
append("<OPTIONAL_$type>")
}
appendLine()
}
}
if (options.isNotEmpty()) {
appendLine("$i options:")
appendOptions(options)
}
if (secrets.isNotEmpty()) {
appendLine("$i secrets:")
appendOptions(secrets)
}
}
appendLine("Use the following syntax to configure this plugin globally as part of `config.yml`:")
appendLine()
appendLine("```yaml")
appendLine("ort:")
appendOptionsAndSecrets(2, pluginTypeCamelCase)
appendLine("```")
appendLine()
if (tool == "analyzer") {
appendLine("Use the following syntax to configure this plugin in a repository's `.ort.yml`:")
appendLine()
appendLine("```yaml")
// See https://github.com/oss-review-toolkit/ort/issues/5715.
appendOptionsAndSecrets(0, pluginTypeParts.joinToString("_"))
appendLine("```")
appendLine()
appendLine(
"If the plugin is configured in both locations, the configurations are merged, with options " +
"from `.ort.yml` taking precedence over those from `config.yml`."
)
appendLine()
}
appendLine("### Options")
appendLine()
// Write option descriptions.
allOptions.forEach { option ->
val type = option["type"]
appendLine("#### ${option["name"]}")
appendLine()
appendLine("")
if (option["isRequired"] == true) {
appendLine("")
}
option["default"]?.also {
val escaped = it.toString()
.replace("-", "--")
.replace("_", "__")
.replace(" ", "_")
appendLine("")
}
val aliases = option["aliases"] as List<*>
if (aliases.isNotEmpty()) {
appendLine()
append("***Alias")
if (aliases.size > 1) append("es")
appendLine(":** ${aliases.joinToString { "`$it`" }}*")
}
val enumEntries = (option["enumEntries"] as List<*>?)?.map { it as Map<*, *> }
if (enumEntries?.isNotEmpty() == true) {
appendLine()
appendLine("**Possible values:**")
appendLine(enumEntries.joinToString { entry ->
buildString {
append("`${entry["alternativeName"] ?: entry["name"]}`")
val aliases = entry["aliases"] as List<*>
if (aliases.isNotEmpty()) {
append(" (alias")
if (aliases.size > 1) append("es")
append(": ${aliases.joinToString { "`$it`" }})")
}
}
})
}
appendLine()
appendLine(option["description"])
appendLine()
}
}
logger.lifecycle("Writing docs for ${descriptor["id"]} to ${outputFile.absolutePath}.")
outputFile.writeText(markdown)
}
}
}
private val KDOC_LINK_REGEX = Regex("""\[([^]]+)](?:\[([^]]+)])?(?!\()""")
/** Convert KDoc symbol links into inline code blocks. */
fun convertKdocLinks(input: String) = input.replace(KDOC_LINK_REGEX) {
val (text, target) = it.destructured
if (target.isNotEmpty()) "$text (`$target`)" else "`$text`"
}