-
Notifications
You must be signed in to change notification settings - Fork 119
/
AsciidoctorTask.groovy
executable file
·232 lines (208 loc) · 9.02 KB
/
AsciidoctorTask.groovy
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
/*
* Copyright 2012-2013 the original author or authors.
*
* 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.
*/
package org.asciidoctor.gradle
import org.asciidoctor.Asciidoctor
import org.asciidoctor.SafeMode
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.InvalidUserDataException
import org.gradle.api.tasks.*
/**
* @author Noam Tenne
* @author Andres Almiray
* @author Tom Bujok
* @author Lukasz Pielak
* @author Dmitri Vyazelenko
* @author Dan Allen
* @author Rob Winch
*/
class AsciidoctorTask extends DefaultTask {
private static final boolean IS_WINDOWS = System.getProperty('os.name').contains('Windows')
private static final String DOUBLE_BACKLASH = '\\\\'
private static final String BACKLASH = '\\'
private static final ASCIIDOC_FILE_EXTENSION_PATTERN = ~/.*\.a((sc(iidoc)?)|d(oc)?)$/
private static final DOCINFO_FILE_PATTERN = ~/(.+\-)?docinfo(-footer)?\.[^.]+/
@Optional @InputFile File sourceDocumentName
@Optional @InputDirectory File baseDir
@InputDirectory File sourceDir
@OutputDirectory File outputDir
@Input String backend
@Input Map options = [:]
@Optional boolean logDocuments = false
Asciidoctor asciidoctor
FoPdfFacade fopdf = new FoPdfFacade()
AsciidoctorTask() {
sourceDir = project.file('src/asciidoc')
outputDir = new File(project.buildDir, 'asciidoc')
backend = AsciidoctorBackend.HTML5.id
baseDir = project.projectDir
}
/**
* Validates input values. If an input value is not valid an exception is thrown.
*/
private void validateInputs() {
if (!AsciidoctorBackend.isBuiltIn(backend)) {
logger.lifecycle("Passing through unknown backend: $backend")
}
}
private static File outputDirFor(File source, String basePath, File outputDir) {
String filePath = source.directory ? source.absolutePath : source.parentFile.absolutePath
String relativeFilePath = normalizePath(filePath) - normalizePath(basePath)
File destinationParentDir = new File("${outputDir}/${relativeFilePath}")
if (!destinationParentDir.exists()) destinationParentDir.mkdirs()
destinationParentDir
}
private static String normalizePath(String path) {
if (IS_WINDOWS) {
path = path.replace(DOUBLE_BACKLASH, BACKLASH)
path = path.replace(BACKLASH, DOUBLE_BACKLASH)
}
path
}
@TaskAction
void gititdone() {
validateInputs()
outputDir.mkdirs()
asciidoctor = asciidoctor ?: Asciidoctor.Factory.create()
processDocumentsAndResources()
}
@SuppressWarnings('CatchException')
private void processDocumentsAndResources() {
boolean isFoPdf = backend == AsciidoctorBackend.FOPDF.id
String asciidoctorBackend = isFoPdf ? AsciidoctorBackend.DOCBOOK.id : backend
try {
def fileFilter = { File file ->
// skip files & directories that begin with an underscore and docinfo files
!file.name.startsWith('_') && (file.directory || !(file.name ==~ DOCINFO_FILE_PATTERN))
}
eachFileRecurse(sourceDir, fileFilter) { File file ->
File destinationParentDir = outputDirFor(file, sourceDir.absolutePath, outputDir)
if (file.name =~ ASCIIDOC_FILE_EXTENSION_PATTERN) {
if (!sourceDocumentName || file.name == sourceDocumentName.name) {
if (logDocuments) {
logger.lifecycle("Rendering $file")
}
asciidoctor.renderFile(file, mergedOptions(
options: options,
baseDir: baseDir,
projectDir: project.projectDir,
rootDir: project.rootDir,
outputDir: destinationParentDir,
backend: asciidoctorBackend))
if(isFoPdf) {
File workingDir = new File("${outputDir}/$backend/work")
fopdf.renderFoPdf(file, workingDir, destinationParentDir)
}
}
} else {
File target = new File(destinationParentDir, file.name)
target.withOutputStream { it << file.newInputStream() }
}
}
} catch (Exception e) {
throw new GradleException('Error running Asciidoctor', e)
}
}
private static void eachFileRecurse(File dir, Closure fileFilter, Closure fileProcessor) {
dir.eachFile { File file ->
if (fileFilter(file)) {
if (file.directory) {
eachFileRecurse(file, fileFilter, fileProcessor)
} else {
fileProcessor(file)
}
}
}
}
private static Map<String, Object> mergedOptions(Map params) {
Map<String, Object> mergedOptions = [:]
mergedOptions.putAll(params.options)
mergedOptions.backend = params.backend
mergedOptions.in_place = false
mergedOptions.safe = resolveSafeModeLevel(mergedOptions.safe, 0i)
mergedOptions.to_dir = params.outputDir.absolutePath
if (params.baseDir) {
mergedOptions.base_dir = params.baseDir.absolutePath
}
if (mergedOptions.to_file) {
File toFile = new File(mergedOptions.to_file)
mergedOptions.to_file = new File(mergedOptions.remove('to_dir'), toFile.name).absolutePath
}
Map attributes = [:]
def rawAttributes = mergedOptions.get('attributes', [:])
if (rawAttributes instanceof Map) {
// copy all attributes in order to prevent changes down
// the Asciidoctor chain that could cause serialization
// problems with Gradle -> all inputs/outputs get serialized
// for caching purposes; Ruby objects are non-serializable
// Issue #14 force GString -> String as jruby will fail
// to find an exact match when invoking Asciidoctor
for (entry in rawAttributes) {
if (entry.value == null || entry.value instanceof Boolean) {
attributes[entry.key] = entry.value
} else {
attributes[entry.key] = entry.value.toString()
}
}
} else {
if (rawAttributes instanceof CharSequence) {
// replace non-escaped spaces with null character, then replace escaped spaces with space,
// finally split on the null character
rawAttributes = rawAttributes.replaceAll('([^\\\\]) ', '$1\0').replaceAll('\\\\ ', ' ').split('\0')
}
if (rawAttributes.getClass().isArray() || rawAttributes instanceof Collection) {
rawAttributes.each {
if (it instanceof CharSequence) {
def (k, v) = it.toString().split('=', 2) as List
attributes.put(k, v != null ? v : '')
} else {
// QUESTION should we just coerce it to a String?
throw new InvalidUserDataException("Unsupported type for attribute ${it}: ${it.class}")
}
}
} else {
// QUESTION should we just coerce it to a String?
throw new InvalidUserDataException("Unsupported type for attributes: ${rawAttributes.class}")
}
}
attributes.projectdir = params.projectDir.absolutePath
attributes.rootdir = params.rootDir.absolutePath
mergedOptions.attributes = attributes
// Issue #14 force GString -> String as jruby will fail
// to find an exact match when invoking Asciidoctor
for (entry in mergedOptions) {
if (entry.value instanceof CharSequence) {
mergedOptions[entry.key] = entry.value.toString()
}
}
mergedOptions
}
private static int resolveSafeModeLevel(Object safe, int defaultLevel) {
if (safe == null) {
defaultLevel
} else if (safe instanceof SafeMode) {
safe.level
} else if (safe instanceof CharSequence) {
try {
Enum.valueOf(SafeMode, safe.toString().toUpperCase()).level
} catch (IllegalArgumentException e) {
defaultLevel
}
} else {
safe.intValue()
}
}
}