-
Notifications
You must be signed in to change notification settings - Fork 330
/
AsciidoctorEngine.java
211 lines (184 loc) · 7.91 KB
/
AsciidoctorEngine.java
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
package org.jbake.parser;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.AttributesBuilder;
import org.asciidoctor.Options;
import org.asciidoctor.ast.DocumentHeader;
import org.jbake.app.configuration.JBakeConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static org.asciidoctor.AttributesBuilder.attributes;
import static org.asciidoctor.OptionsBuilder.options;
import static org.asciidoctor.SafeMode.UNSAFE;
/**
* Renders documents in the asciidoc format using the Asciidoctor engine.
*
* @author Cédric Champeau
*/
public class AsciidoctorEngine extends MarkupEngine {
private static final Logger LOGGER = LoggerFactory.getLogger(AsciidoctorEngine.class);
public static final String JBAKE_PREFIX = "jbake-";
public static final String REVDATE_KEY = "revdate";
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private Asciidoctor engine;
/* comma separated file paths to additional gems */
private static final String OPT_GEM_PATH = "gemPath";
/* comma separated gem names */
private static final String OPT_REQUIRES = "requires";
public AsciidoctorEngine() {
Class engineClass = Asciidoctor.class;
assert engineClass != null;
}
private Asciidoctor getEngine(Options options) {
try {
lock.readLock().lock();
if (engine == null) {
lock.readLock().unlock();
try {
lock.writeLock().lock();
if (engine == null) {
LOGGER.info("Initializing Asciidoctor engine...");
if (options.map().containsKey(OPT_GEM_PATH)) {
engine = Asciidoctor.Factory.create(String.valueOf(options.map().get(OPT_GEM_PATH)));
} else {
engine = Asciidoctor.Factory.create();
}
if (options.map().containsKey(OPT_REQUIRES)) {
String[] requires = String.valueOf(options.map().get(OPT_REQUIRES)).split(",");
if (requires.length != 0) {
for (String require : requires) {
engine.requireLibrary(require);
}
}
}
LOGGER.info("Asciidoctor engine initialized.");
}
} finally {
lock.readLock().lock();
lock.writeLock().unlock();
}
}
} finally {
lock.readLock().unlock();
}
return engine;
}
@Override
public void processHeader(final ParserContext context) {
Options options = getAsciiDocOptionsAndAttributes(context);
final Asciidoctor asciidoctor = getEngine(options);
DocumentHeader header = asciidoctor.readDocumentHeader(context.getFile());
Map<String, Object> documentModel = context.getDocumentModel();
if (header.getDocumentTitle() != null) {
documentModel.put("title", header.getDocumentTitle().getCombined());
}
Map<String, Object> attributes = header.getAttributes();
for (Map.Entry<String, Object> attribute : attributes.entrySet()) {
String key = attribute.getKey();
Object value = attribute.getValue();
if (hasJBakePrefix(key)) {
String pKey = key.substring(6);
if(canCastToString(value)) {
storeHeaderValue(pKey, (String) value, documentModel);
} else {
documentModel.put(pKey, value);
}
}
if (hasRevdate(key) && canCastToString(value)) {
String dateFormat = context.getConfig().getDateFormat();
DateFormat df = new SimpleDateFormat(dateFormat);
try {
Date date = df.parse((String) value);
context.setDate(date);
} catch (ParseException e) {
LOGGER.error("Unable to parse revdate. Expected {}", dateFormat, e);
}
}
if (key.equals("jbake-tags")) {
if (canCastToString(value)) {
context.setTags(((String) value).split(","));
} else {
LOGGER.error("Wrong value of 'jbake-tags'. Expected a String got '{}'", getValueClassName(value));
}
} else {
documentModel.put(key, attributes.get(key));
}
}
}
private boolean canCastToString(Object value) {
return value instanceof String;
}
private String getValueClassName(Object value) {
return (value == null) ? "null" : value.getClass().getCanonicalName();
}
private boolean hasRevdate(String key) {
return key.equals(REVDATE_KEY);
}
private boolean hasJBakePrefix(String key) {
return key.startsWith(JBAKE_PREFIX);
}
// TODO: write tests with options and attributes
@Override
public void processBody(ParserContext context) {
StringBuilder body = new StringBuilder(context.getBody().length());
if (!context.hasHeader()) {
for (String line : context.getFileLines()) {
body.append(line).append("\n");
}
context.setBody(body.toString());
}
processAsciiDoc(context);
}
private void processAsciiDoc(ParserContext context) {
Options options = getAsciiDocOptionsAndAttributes(context);
final Asciidoctor asciidoctor = getEngine(options);
context.setBody(asciidoctor.render(context.getBody(), options));
}
private Options getAsciiDocOptionsAndAttributes(ParserContext context) {
JBakeConfiguration config = context.getConfig();
List<String> asciidoctorAttributes = config.getAsciidoctorAttributes();
final AttributesBuilder attributes = attributes(asciidoctorAttributes.toArray(new String[asciidoctorAttributes.size()]));
if (config.getExportAsciidoctorAttributes()) {
final String prefix = config.getAttributesExportPrefixForAsciidoctor();
for (final Iterator<String> it = config.getKeys(); it.hasNext(); ) {
final String key = it.next();
if (!key.startsWith("asciidoctor")) {
attributes.attribute(prefix + key.replace(".", "_"), config.get(key));
}
}
}
final List<String> optionsSubset = config.getAsciidoctorOptionKeys();
final Options options = options().attributes(attributes.get()).get();
for (final String optionKey : optionsSubset) {
Object optionValue = config.getAsciidoctorOption(optionKey);
if (optionKey.equals(Options.TEMPLATE_DIRS)) {
List<String> dirs = getAsList(optionValue);
if (!dirs.isEmpty()) {
options.setTemplateDirs(String.valueOf(dirs));
}
} else {
options.setOption(optionKey, optionValue);
}
}
options.setBaseDir(context.getFile().getParentFile().getAbsolutePath());
options.setSafe(UNSAFE);
return options;
}
private List<String> getAsList(Object asciidoctorOption) {
List<String> values = new ArrayList<>();
if (asciidoctorOption instanceof List) {
values.addAll((List<String>) asciidoctorOption);
} else if (asciidoctorOption instanceof String) {
values.add(String.valueOf(asciidoctorOption));
}
return values;
}
}