当我们编写Groovy应用程序时,我们当然会向类中添加文档。如果我们使用Gradle来构建我们的项目,我们可以运行groovydoc
Groovy插件添加的用于生成文档的任务。我们可以通过更改groovydoc
任务。如果我们想进一步定制,我们必须采取一些额外的步骤。这groovydoc
任务使用与Groovy库捆绑在一起的GroovyDoc工具。GroovyDoc工具使用GStringTemplateEngine生成文档。默认模板文件存储在包中org.codehaus.tools.groovydoc.gstringTemplates
。包中有以下文件:
如果我们遵循相同的包结构和文件名,我们可以编写自己的模板文件。然后,当我们运行GroovyDoc工具时,我们必须确保使用自定义模板文件,而不是默认模板文件。如果我们将自定义文件放在GroovyDoc工具的类路径中,在Groovy库之前,那么我们的自定义文件就被使用了。在我们的Gradle项目中,我们可以创建一个新的包含自定义模板文件的源代码集。然后我们配置classpath
的属性groovydoc
任务,并在它前面添加我们的源集输出。这样我们可以覆盖默认的实现。
让我们改变classDocName.html
模板。我们做了一个目录src/groovydoc
。在这里,我们创建目录org/codehaus/groovy/tools/groovy/gstringTemplates/classLevel
。在目录中,我们创建文件classDocName.html
。我们使用默认的内容classDocName.html
在Groovy库中找到并做了一些小的修改。我们想添加一个Gravatar作者部分的图像。在我们的源代码中,我们必须使用@author
标记并在方括号中包含用户的电子邮件地址。例如,@author Hubert Klein Ikkink [actual-email-address]
。在我们的模板文件中,我们将查找方括号之间的值,并用<img/>
引用Gravatar图像的HTML标记。
...
<% if (classDoc.commentText()) {
def commentText = classDoc.commentText().replaceAll(/\[(.*)\]/) {
def md5 = java.security.MessageDigest.getInstance("MD5").digest(it[1].getBytes("UTF-8")).encodeHex()
"<img src=\"http://www.gravatar.com/avatar/${md5}?s=24\"/>"
}
%>
<p>${commentText}</p>
<% } %>
...
我们还包括一个自定义标题。我们通过我们的渐变构建文件设置该值,它在我们的模板文件中可用props.header
:
...
<% if (props.header) { %><div>${props.header}</div><% } %>
...
为了进行CSS更改,我们添加了文件stylesheet.css
在目录中src/groovydoc/org/codehaus/groovy/tools/groovy/gstringTemplates/topLevel
。此外,在这里我们可以使用Groovy库中的文件作为起点,并对其进行修改。
我们制作了以下Gradle构建文件来支持我们的自定义模板,并重新配置groovydoc
任务:
plugins {
id "groovy"
}
// Here we add a new SourceSet
// that has a resources directory
// at 'src/groovydoc'. This directory
// contains Groovydoc template files
// we want to override for our project.
sourceSets {
groovydoc {
resources {
srcDir 'src/groovydoc'
}
}
}
// Customize groovydoc task that is
// added by the Groovy plugin.
groovydoc {
// Set document and window titles.
docTitle = "Sample GroovyDoc"
windowTitle = "Example customizing GroovyDoc"
// Set custom header. We will include this
// in the changed classDocName.html file.
header = '''\
<img src="http://www.mrhaki.com/images/haki-logo-black-64.png"/>
<h2>Sample project</h2>
'''.stripIndent()
// Set custom footer for generated documentation.
footer = """\
<div class="custom-footer">
Generated on: ${new Date().format('yyyy-MM-dd HH:mm:ss')}
</div>""".stripIndent()
// Change classpath property and include
// the output of the SourceSet groovydoc.
// The output contains the changed stylesheet
// and template file and must be first in the classpath
// before the files that are bundled with Groovy.
classpath = sourceSets.groovydoc.output + classpath
}
repositories {
jcenter()
}
dependencies {
compile "org.codehaus.groovy:groovy-all:2.4.5"
}
当我们对stylesheet.css
运行groovydoc
任务我们看到以下示例输出:
请注意,我们有自己的自定义标题、Gravatar图像和自定义CSS。