-
Notifications
You must be signed in to change notification settings - Fork 173
/
JRubyAsciidoctor.java
524 lines (414 loc) · 19.1 KB
/
JRubyAsciidoctor.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package org.asciidoctor.jruby.internal;
import org.asciidoctor.Attributes;
import org.asciidoctor.Options;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.jruby.AsciidoctorJRuby;
import org.asciidoctor.jruby.ast.impl.DocumentHeaderImpl;
import org.asciidoctor.jruby.ast.impl.NodeConverter;
import org.asciidoctor.jruby.converter.internal.ConverterRegistryExecutor;
import org.asciidoctor.jruby.extension.internal.ExtensionRegistryExecutor;
import org.asciidoctor.jruby.log.internal.JULLogHandler;
import org.asciidoctor.jruby.log.internal.JavaLogger;
import org.asciidoctor.jruby.log.internal.LogHandlerRegistryExecutor;
import org.asciidoctor.jruby.syntaxhighlighter.internal.SyntaxHighlighterRegistryExecutor;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.log.LogRecord;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyInstanceConfig;
import org.jruby.RubyModule;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
public class JRubyAsciidoctor implements AsciidoctorJRuby, LogHandler {
private static final Logger logger = Logger.getLogger(JRubyAsciidoctor.class.getName());
private static final String GEM_PATH = "GEM_PATH";
protected RubyGemsPreloader rubyGemsPreloader;
protected Ruby rubyRuntime;
private RubyClass extensionGroupClass;
private List<LogHandler> logHandlers = new ArrayList<>();
public JRubyAsciidoctor() {
this(createRubyRuntime(Collections.singletonMap(GEM_PATH, null), new ArrayList<>(), null));
processRegistrations(this);
}
private JRubyAsciidoctor(final Ruby rubyRuntime) {
this.rubyRuntime = rubyRuntime;
InputStream inputStream = getClass().getResourceAsStream("asciidoctorclass.rb");
final String script = IOUtils.readFull(inputStream);
this.rubyRuntime.evalScriptlet(script);
this.rubyGemsPreloader = new RubyGemsPreloader(this.rubyRuntime);
this.logHandlers.add(new JULLogHandler());
RubyOutputStreamWrapper.getOrCreateOutputStreamWrapperClass(this.rubyRuntime);
}
public static JRubyAsciidoctor create() {
return create((String) null);
}
public static JRubyAsciidoctor create(String gemPath) {
return processRegistrations(createJRubyAsciidoctorInstance(Collections.singletonMap(GEM_PATH, gemPath), new ArrayList<>(), null));
}
public static JRubyAsciidoctor create(List<String> loadPaths) {
return processRegistrations(createJRubyAsciidoctorInstance(null, loadPaths, null));
}
public static JRubyAsciidoctor create(ClassLoader classloader) {
return processRegistrations(createJRubyAsciidoctorInstance(null, new ArrayList<>(), classloader));
}
public static JRubyAsciidoctor create(ClassLoader classloader, String gemPath) {
return processRegistrations(createJRubyAsciidoctorInstance(Collections.singletonMap(GEM_PATH, gemPath), new ArrayList<>(), classloader));
}
public static JRubyAsciidoctor create(List<String> loadPaths, String gemPath) {
return processRegistrations(createJRubyAsciidoctorInstance(Collections.singletonMap(GEM_PATH, gemPath), loadPaths, null));
}
private static JRubyAsciidoctor processRegistrations(JRubyAsciidoctor asciidoctor) {
registerExtensions(asciidoctor);
registerConverters(asciidoctor);
registerSyntaxHighlighters(asciidoctor);
registerLogHandlers(asciidoctor);
JavaLogger.install(asciidoctor.getRubyRuntime(), asciidoctor);
return asciidoctor;
}
private static void registerConverters(AsciidoctorJRuby asciidoctor) {
new ConverterRegistryExecutor(asciidoctor).registerAllConverters();
}
private static void registerExtensions(AsciidoctorJRuby asciidoctor) {
new ExtensionRegistryExecutor(asciidoctor).registerAllExtensions();
}
private static void registerSyntaxHighlighters(AsciidoctorJRuby asciidoctor) {
new SyntaxHighlighterRegistryExecutor(asciidoctor).registerAllSyntaxHighlighter();
}
private static void registerLogHandlers(AsciidoctorJRuby asciidoctor) {
new LogHandlerRegistryExecutor(asciidoctor).registerAllLogHandlers();
}
private static JRubyAsciidoctor createJRubyAsciidoctorInstance(Map<String, String> environmentVars, List<String> loadPaths, ClassLoader classloader) {
Ruby rubyRuntime = createRubyRuntime(environmentVars, loadPaths, classloader);
return new JRubyAsciidoctor(rubyRuntime);
}
private static Ruby createRubyRuntime(Map<String, String> environmentVars, List<String> loadPaths, ClassLoader classloader) {
Map<String, String> env = environmentVars != null ? new HashMap<>(environmentVars) : new HashMap<>();
RubyInstanceConfig config = createOptimizedConfiguration();
if (classloader != null) {
config.setLoader(classloader);
}
injectEnvironmentVariables(config, env);
return JavaEmbedUtils.initialize(loadPaths, config);
}
private static void injectEnvironmentVariables(RubyInstanceConfig config, Map<String, String> environmentVars) {
EnvironmentInjector environmentInjector = new EnvironmentInjector(config);
environmentInjector.inject(environmentVars);
}
private static RubyInstanceConfig createOptimizedConfiguration() {
return new RubyInstanceConfig();
}
@Override
public void close() {
if (rubyRuntime != null) {
rubyRuntime.tearDown();
}
}
@Override
public void registerLogHandler(final LogHandler logHandler) {
if (!this.logHandlers.contains(logHandler)) {
this.logHandlers.add(logHandler);
}
}
@Override
public void unregisterLogHandler(final LogHandler logHandler) {
this.logHandlers.remove(logHandler);
}
public Ruby getRubyRuntime() {
return rubyRuntime;
}
private DocumentHeader toDocumentHeader(Document document) {
Document documentImpl = (Document) NodeConverter.createASTNode(document);
return DocumentHeaderImpl.createDocumentHeader(
documentImpl.getStructuredDoctitle(),
documentImpl.getDoctitle(),
documentImpl.getAuthors(),
document.getAttributes());
}
@SuppressWarnings("unchecked")
@Override
public DocumentHeader readDocumentHeader(File file) {
RubyHash rubyHash = getParseHeaderOnlyOption();
Document document = (Document) NodeConverter.createASTNode(getAsciidoctorModule().callMethod("load_file", rubyRuntime.newString(file.getAbsolutePath()), rubyHash));
return toDocumentHeader(document);
}
@Override
public DocumentHeader readDocumentHeader(String content) {
RubyHash rubyHash = getParseHeaderOnlyOption();
Document document = (Document) NodeConverter.createASTNode(getAsciidoctorModule().callMethod("load", rubyRuntime.newString(content), rubyHash));
return toDocumentHeader(document);
}
@Override
public DocumentHeader readDocumentHeader(Reader contentReader) {
String content = IOUtils.readFull(contentReader);
return this.readDocumentHeader(content);
}
private RubyHash getParseHeaderOnlyOption() {
Map<String, Object> options = new HashMap<>();
options.put("parse_header_only", true);
return RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options);
}
private List<String> convertAllFiles(Map<String, Object> options, final Iterable<File> asciidoctorFiles) {
List<String> asciidoctorContent = new ArrayList<>();
for (File asciidoctorFile : asciidoctorFiles) {
String renderedFile = convertFile(asciidoctorFile, options);
if (renderedFile != null) {
asciidoctorContent.add(renderedFile);
}
}
return asciidoctorContent;
}
@Override
public void requireLibrary(String... library) {
requireLibraries(Arrays.asList(library));
}
@Override
public void requireLibraries(Collection<String> libraries) {
if (libraries != null) {
for (String library : libraries) {
RubyUtils.requireLibrary(rubyRuntime, library);
}
}
}
@Override
public JavaExtensionRegistry javaExtensionRegistry() {
return new JavaExtensionRegistryImpl(this);
}
public RubyExtensionRegistry rubyExtensionRegistry() {
return new RubyExtensionRegistryImpl(rubyRuntime);
}
@Override
public JavaConverterRegistry javaConverterRegistry() {
return new JavaConverterRegistryImpl(this);
}
@Override
public SyntaxHighlighterRegistry syntaxHighlighterRegistry() {
return new SyntaxHighlighterRegistryImpl(this);
}
@Override
public void unregisterAllExtensions() {
getExtensionsModule().callMethod("unregister_all");
}
@Override
public void shutdown() {
this.rubyRuntime.tearDown();
}
@Override
public String asciidoctorVersion() {
return RubyUtils.rubyToJava(rubyRuntime, getAsciidoctorModule().getConstant("VERSION"), String.class);
}
private RubyModule getExtensionsModule() {
return getAsciidoctorModule()
.defineOrGetModuleUnder("Extensions");
}
private RubyModule getAsciidoctorModule() {
return rubyRuntime.getModule("Asciidoctor");
}
@Override
public String convert(String content, Map<String, Object> options) {
return convert(content, options, String.class);
}
public <T> T convert(String content, Map<String, Object> options, Class<T> expectedResult) {
this.rubyGemsPreloader.preloadRequiredLibraries(options);
logger.fine(String.join(" ", AsciidoctorUtils.toAsciidoctorCommand(options, "-")));
if (AsciidoctorUtils.isOptionWithAttribute(options, Attributes.SOURCE_HIGHLIGHTER, "pygments")) {
logger.fine("In order to use Pygments with Asciidoctor, you need to install Pygments (and Python, if you don't have it yet). Read https://asciidoctor.org/news/#syntax-highlighting-with-pygments.");
}
String currentDirectory = rubyRuntime.getCurrentDirectory();
if (options.containsKey(Options.BASEDIR)) {
rubyRuntime.setCurrentDirectory((String) options.get(Options.BASEDIR));
}
final Object toFileOption = options.get(Options.TO_FILE);
if (toFileOption instanceof OutputStream) {
options.put(Options.TO_FILE, RubyOutputStreamWrapper.wrap(getRubyRuntime(), (OutputStream) toFileOption));
}
RubyHash rubyHash = RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options);
try {
IRubyObject object = getAsciidoctorModule().callMethod("convert",
rubyRuntime.newString(content), rubyHash);
if (NodeConverter.NodeType.DOCUMENT_CLASS.isInstance(object)) {
// If a document is rendered to a file Asciidoctor returns the document, we return null
return null;
}
return RubyUtils.rubyToJava(rubyRuntime, object, expectedResult);
} catch (RaiseException e) {
logger.severe(e.getException().getClass().getCanonicalName());
throw new AsciidoctorCoreException(e);
} finally {
// we restore current directory to its original value.
rubyRuntime.setCurrentDirectory(currentDirectory);
}
}
@Override
public String convert(String content, Options options) {
return convert(content, options, String.class);
}
@Override
public <T> T convert(String content, Options options, Class<T> expectedResult) {
return convert(content, options.map(), expectedResult);
}
@Override
public String convert(String content, OptionsBuilder options) {
return convert(content, options, String.class);
}
@Override
public <T> T convert(String content, OptionsBuilder options, Class<T> expectedResult) {
return convert(content, options.asMap(), expectedResult);
}
@Override
public void convert(Reader contentReader, Writer rendererWriter, Map<String, Object> options) throws IOException {
String content = IOUtils.readFull(contentReader);
String renderedContent = convert(content, options);
IOUtils.writeFull(rendererWriter, renderedContent);
}
@Override
public void convert(Reader contentReader, Writer rendererWriter, Options options) throws IOException {
this.convert(contentReader, rendererWriter, options.map());
}
@Override
public void convert(Reader contentReader, Writer rendererWriter, OptionsBuilder options) throws IOException {
this.convert(contentReader, rendererWriter, options.asMap());
}
@Override
public String convertFile(File file, Map<String, Object> options) {
return convertFile(file, options, String.class);
}
@Override
public <T> T convertFile(File file, Map<String, Object> options, Class<T> expectedResult) {
this.rubyGemsPreloader.preloadRequiredLibraries(options);
logger.fine(String.join(" ", AsciidoctorUtils.toAsciidoctorCommand(options, file.getAbsolutePath())));
String currentDirectory = rubyRuntime.getCurrentDirectory();
if (options.containsKey(Options.BASEDIR)) {
rubyRuntime.setCurrentDirectory((String) options.get(Options.BASEDIR));
}
final Object toFileOption = options.get(Options.TO_FILE);
if (toFileOption instanceof OutputStream) {
options.put(Options.TO_FILE, RubyOutputStreamWrapper.wrap(getRubyRuntime(), (OutputStream) toFileOption));
}
RubyHash rubyHash = RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options);
try {
IRubyObject object = getAsciidoctorModule().callMethod("convert_file",
rubyRuntime.newString(file.getAbsolutePath()), rubyHash);
if (NodeConverter.NodeType.DOCUMENT_CLASS.isInstance(object)) {
// If a document is rendered to a file Asciidoctor returns the document, we return null
return null;
}
return RubyUtils.rubyToJava(rubyRuntime, object, expectedResult);
} catch (RaiseException e) {
logger.severe(e.getMessage());
throw new AsciidoctorCoreException(e);
} finally {
// we restore current directory to its original value.
rubyRuntime.setCurrentDirectory(currentDirectory);
}
}
@Override
public String convertFile(File file, Options options) {
return convertFile(file, options, String.class);
}
@Override
public <T> T convertFile(File file, Options options, Class<T> expectedResult) {
return convertFile(file, options.map(), expectedResult);
}
@Override
public String convertFile(File file, OptionsBuilder options) {
return convertFile(file, options.asMap(), String.class);
}
@Override
public <T> T convertFile(File file, OptionsBuilder options, Class<T> expectedResult) {
return convertFile(file, options.asMap(), expectedResult);
}
@Override
public String[] convertDirectory(Iterable<File> directoryWalker, Map<String, Object> options) {
List<String> asciidoctorContent = convertAllFiles(options, directoryWalker);
return asciidoctorContent.toArray(new String[0]);
}
@Override
public String[] convertDirectory(Iterable<File> directoryWalker, Options options) {
return convertDirectory(directoryWalker, options.map());
}
@Override
public String[] convertDirectory(Iterable<File> directoryWalker, OptionsBuilder options) {
return convertDirectory(directoryWalker, options.asMap());
}
@Override
public String[] convertFiles(Collection<File> files, Map<String, Object> options) {
List<String> asciidoctorContent = convertAllFiles(options, files);
return asciidoctorContent.toArray(new String[0]);
}
@Override
public String[] convertFiles(Collection<File> asciidoctorFiles, Options options) {
return convertFiles(asciidoctorFiles, options.map());
}
@Override
public String[] convertFiles(Collection<File> files, OptionsBuilder options) {
return convertFiles(files, options.asMap());
}
@Override
public Document load(String content, Map<String, Object> options) {
RubyHash rubyHash = RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options);
return (Document) NodeConverter.createASTNode(getAsciidoctorModule().callMethod("load",
rubyRuntime.newString(content), rubyHash));
}
@Override
public Document load(String content, Options options) {
RubyHash rubyHash = RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options.map());
return (Document) NodeConverter.createASTNode(getAsciidoctorModule().callMethod("load",
rubyRuntime.newString(content), rubyHash));
}
@Override
public Document loadFile(File file, Map<String, Object> options) {
RubyHash rubyHash = RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options);
return (Document) NodeConverter.createASTNode(getAsciidoctorModule().callMethod("load_file",
rubyRuntime.newString(file.getAbsolutePath()), rubyHash));
}
@Override
public Document loadFile(File file, Options options) {
RubyHash rubyHash = RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options.map());
return (Document) NodeConverter.createASTNode(getAsciidoctorModule().callMethod("load_file",
rubyRuntime.newString(file.getAbsolutePath()), rubyHash));
}
@Override
public ExtensionGroup createGroup() {
return createGroup(UUID.randomUUID().toString());
}
@Override
public ExtensionGroup createGroup(String groupName) {
return new ExtensionGroupImpl(groupName, this, getExtensionGroupClass());
}
private RubyClass getExtensionGroupClass() {
if (this.extensionGroupClass == null) {
extensionGroupClass = ExtensionGroupImpl.createExtensionGroupClass(rubyRuntime);
}
return extensionGroupClass;
}
@Override
public void log(LogRecord logRecord) {
for (LogHandler logHandler : logHandlers) {
logHandler.log(logRecord);
}
}
}