Skip to content

Instantly share code, notes, and snippets.

@ari
Last active August 17, 2019 22:18
Show Gist options
  • Save ari/4156d967d54289f4abf6 to your computer and use it in GitHub Desktop.
Save ari/4156d967d54289f4abf6 to your computer and use it in GitHub Desktop.
Docbook gradle build
/*
Copyright 2015 Aristedes Maniatis
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
http://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.
*/
import com.icl.saxon.TransformerFactoryImpl
import org.apache.fop.apps.*
import org.apache.tools.ant.filters.ReplaceTokens
import org.apache.xerces.jaxp.SAXParserFactoryImpl
import org.xml.sax.InputSource
import org.xml.sax.XMLReader
import javax.xml.parsers.SAXParserFactory
import javax.xml.transform.Result
import javax.xml.transform.Source
import javax.xml.transform.Transformer
import javax.xml.transform.TransformerFactory
import javax.xml.transform.sax.SAXResult
import javax.xml.transform.sax.SAXSource
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource
import java.time.LocalDate
import java.time.format.DateTimeFormatter
buildscript {
repositories {
mavenCentral()
}
dependencies {
def fopDeps = ['org.apache.xmlgraphics:fop:2.0@jar',
'org.apache.xmlgraphics:xmlgraphics-commons:2.0.1',
'org.apache.xmlgraphics:batik-bridge:1.8@jar',
'org.apache.xmlgraphics:batik-css:1.8@jar',
'org.apache.xmlgraphics:batik-dom:1.8',
'org.apache.xmlgraphics:batik-transcoder:1.8',
'org.apache.xmlgraphics:batik-gvt:1.8',
'org.apache.xmlgraphics:batik-svggen:1.8',
'org.apache.xmlgraphics:batik-svg-dom:1.8@jar',
'org.apache.avalon.framework:avalon-framework-impl:4.3.1']
classpath 'saxon:saxon:6.5.3',
'xerces:xercesImpl:2.11.0',
'apache-xerces:resolver:2.9.1',
fopDeps,
'net.sf.xslthl:xslthl:2.1.0'
classpath('xml-apis:xml-apis:1.4.01') {
force = true
}
}
}
task buildScriptDependencies(type: DependencyReportTask) {
configurations = project.buildscript.configurations
}
allprojects {
apply plugin: 'base'
version = project.hasProperty('docVersion') ? project.docVersion : 'unspecified'
configurations {
docbookxslt
}
dependencies {
repositories {
mavenCentral()
}
docbookxslt 'net.sf.docbook:docbook-xsl:1.78.1:resources@zip'
}
task explodeXSL(type: Copy) {
from zipTree(configurations.docbookxslt.singleFile)
into "${buildDir}/xslt"
}
}
subprojects {
task processXSLT(type: Copy) {
from "${rootDir}/stylesheets"
into "${buildDir}/stylesheets"
filter(ReplaceTokens,tokens: [
canonicalLink: canonicalLink,
rootDir: rootDir.absolutePath
])
}
task processSrc(type: Copy) {
from "src"
into "${buildDir}"
filter(ReplaceTokens,tokens: [
projectName: project.name,
version: version,
publishedDate: LocalDate.now().format(DateTimeFormatter.ofPattern("d MMM yyyy")),
copyrightYear : LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy"))
])
}
task docbookHtml(type: Docbook, dependsOn: [processXSLT, processSrc, parent.tasks['explodeXSL']]) {
description = 'Generates chunked docbook html output.'
outputFile = file("${buildDir}/html/index.html")
if (project.path == ":apidocs") {
stylesheet = file("${buildDir}/stylesheets/api-html.xsl")
} else {
stylesheet = file("${buildDir}/stylesheets/standard-html.xsl")
}
sourceDirectory = file( "${buildDir}" )
doLast {
copy {
into "${buildDir}/html/images"
from "src/images"
}
copy {
into "${buildDir}/html/css"
from "${rootDir}/css"
}
copy {
into "${buildDir}/html/js"
from "${rootDir}/js"
}
}
}
task docbookPdfPrepare(type: Docbook, dependsOn: [processXSLT, processSrc, parent.tasks['explodeXSL']]) {
description = 'Generates PDF fo output.'
outputFile = file("${buildDir}/pdf/index.fo")
stylesheet = file("${buildDir}/stylesheets/pdf.xsl")
sourceDirectory = file( "${buildDir}" )
}
task docbookPdf(type: DocbookPdf, dependsOn: 'docbookPdfPrepare') {
description = 'Generates PDF final output.'
sourceFile = file("${buildDir}/pdf/index.fo")
outputFile = file("${buildDir}/pdf/${project.name}.pdf")
}
task docbook(dependsOn: [docbookHtml, docbookPdf]) {
group = 'Documentation'
description = 'Generates all HTML and PDF documentation.'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.7'
}
public class Docbook extends DefaultTask {
@InputDirectory
File sourceDirectory = new File(project.getProjectDir(), "src");
@InputFile
File stylesheet
@OutputFile
File outputFile
@TaskAction
public final void transform() {
// the docbook tasks issue spurious content to the console. redirect to INFO level
// so it doesn't show up in the default log level of LIFECYCLE unless the user has
// run gradle with '-d' or '-i' switches -- in that case show them everything
switch (project.gradle.startParameter.logLevel) {
case LogLevel.DEBUG:
case LogLevel.INFO:
break;
default:
logging.captureStandardOutput(LogLevel.INFO)
logging.captureStandardError(LogLevel.INFO)
}
SAXParserFactory factory = new SAXParserFactoryImpl();
factory.setXIncludeAware(true);
XMLReader reader = factory.newSAXParser().getXMLReader();
def transformerFactory = new TransformerFactoryImpl();
File srcFile = new File(sourceDirectory, "index.xml");
InputSource inputSource = new InputSource(srcFile.getAbsolutePath());
outputFile.getParentFile().mkdirs();
Result result = new StreamResult(outputFile.getAbsolutePath());
URL url = stylesheet.toURI().toURL();
Source source = new StreamSource(url.openStream(), url.toExternalForm());
def transformer = transformerFactory.newTransformer(source);
String rootFilename = outputFile.getName();
rootFilename = rootFilename.substring(0, rootFilename.lastIndexOf('.'));
transformer.setParameter("root.filename", rootFilename);
transformer.setParameter("base.dir", outputFile.getParent() + File.separator);
transformer.setParameter('highlight.xslthl.config', 'file://' + project.getBuildDir().getAbsolutePath() + '/stylesheets/xslthl-config.xml' );
transformer.transform(new SAXSource(reader, inputSource), result);
}
}
public class DocbookPdf extends DefaultTask {
@InputFile
File sourceFile;
@OutputFile
File outputFile;
@TaskAction
public final void transform() {
FopFactory fopFactory = new FopConfParser(
new File(project.getRootDir().getAbsolutePath() + '/fonts/fop-conf.xml'),
new File(project.getProjectDir().getAbsolutePath() + '/src').toURI()
).getFopFactoryBuilder().build();
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setParameter('highlight.xslthl.config', 'file://' + project.getRootDir().getAbsolutePath() + '/stylesheets/xslthl-config.xml' );
Source src = new StreamSource(sourceFile);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
} finally {
out.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment