![](/img/trans.png)
[英]How do you embed runnable sample code in Dokka generated documentation
[英]Dokka: include code samples into package documentation
如何在 Dokka package 文檔中包含(經過測試的、非陳舊的)代碼示例?
更具體地說,假設我在build.gradle.kts
中有這個配置:
withType<DokkaTask> {
outputFormat = "html"
outputDirectory = "$buildDir/documentation"
includes = listOf("packageDocumentation.md")
samples = listOf("$rootDir/src/test/kotlin/some/project/TheSamples.kt")
}
然后是一些測試代碼:
package some.project
import org.junit.jupiter.api.Test
class TheSamples {
@Test
fun helloWorldSample() {
println("hello, world")
}
}
還有一個 package 文檔 Markdown 文件:
# Package some.project
This is the documentation for some package.
@sample some.project.TheSamples#helloWorldSample
,如何將println(...)
-part 包含到文檔中? 當前版本的 Dokka 是否完全支持它?
將#
換成.
或用@includeFunction
替換@sample
沒有做任何事情。
此外:
@sample
標記放置在 function 或 class 的注釋中,您想要記錄如何調用它的示例,或使用它。
@sample
將完全限定的 class 和 function 名稱作為參數。 使用 Dokka 生成 API 文檔時,該引用將替換為引用的 function 的內容。 通常你會有一個 function ,你想用測試 function 的樣本來記錄它,但是在這里,你的測試 function 可能看起來並不簡單
/**
* This is a function that I want to document with a sample.
*
* @sample some.project.TheSamples.helloWorldSample
*/
fun getHelloWorld() {
// Do stuff
}
當 dokka 處理文件時,示例代碼會附加到注釋中的信息上。 下面是dokka的HTML output的粗略近似。
得到你好世界
有趣的 getHelloWorld()
這是一個 function,我想用一個樣本來記錄。
println("hello, world")
我發現以下參考資料很有幫助:
https://livebook.manning.com/book/kotlin-in-action/appendix-b/7
https://medium.com/@rfletcher_96265/testable-samples-in-kotlin-api-docs-f7cd2da17c4f
我不明白接受的答案,所以我不得不在 Kotlinlang Slack 中詢問以試圖弄清楚。 我收到了來自 Pablo García (Casía) 的回復,幫助我理解了這一點,所以也許這對某人也有幫助。
您需要將示例目錄(或文件列表)添加到 dokka 任務配置
tasks.dokkaHtml.configure {
outputDirectory.set(buildDir.resolve("dokka"))
dokkaSourceSets {
configureEach {
samples.from("$projectDir/src/samples/kotlin/samples/samples.kt")
}
}
}
然后將示例添加到該目錄,例如:
package samples
import demo.App
class GreeterExample {
fun greeting() {
println(App().greeting())
}
}
並在您的代碼文檔中使用它:
package demo
class App {
/**
* Greeting
*
* @sample samples.GreeterExample.greeting
*
* @return Will return the string `Hello World!`
*/
fun greeting(): String = "Hello World!"
}
使用./gradlew dokkaHtml
生成 dokka output 后,您將看到
println(App().greeting())
在 dokka 樣品 output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.