001package org.asciidoctor.asciidoclet;
002
003import com.google.common.base.Optional;
004import com.sun.javadoc.Doc;
005import com.sun.javadoc.DocErrorReporter;
006import com.sun.javadoc.Tag;
007import org.asciidoctor.*;
008import org.asciidoctor.internal.JRubyRuntimeContext;
009import org.asciidoctor.internal.RubyUtils;
010
011import static org.asciidoctor.Asciidoctor.Factory.create;
012
013/**
014 * Doclet renderer using and configuring Asciidoctor.
015 *
016 * @author John Ericksen
017 */
018public class AsciidoctorRenderer implements DocletRenderer {
019
020    private static AttributesBuilder defaultAttributes() {
021        return AttributesBuilder.attributes()
022                .attribute("at", "@")
023                .attribute("slash", "/")
024                .attribute("icons", null)
025                .attribute("idprefix", "")
026                .attribute("idseparator", "-")
027                .attribute("javadoc", "")
028                .attribute("showtitle", true)
029                .attribute("source-highlighter", "coderay")
030                .attribute("coderay-css", "class");
031    }
032
033    private static OptionsBuilder defaultOptions() {
034        return OptionsBuilder.options()
035                .safe(SafeMode.SAFE)
036                .backend("html5");
037    }
038
039    protected static final String INLINE_DOCTYPE = "inline";
040
041    private final Asciidoctor asciidoctor;
042    private final Optional<OutputTemplates> templates;
043    private final Options options;
044
045    public AsciidoctorRenderer(DocletOptions docletOptions, DocErrorReporter errorReporter) {
046        this(docletOptions, errorReporter, OutputTemplates.create(errorReporter), create(docletOptions.gemPath()));
047    }
048
049    /**
050     * Constructor used directly for testing purposes only.
051     */
052    protected AsciidoctorRenderer(DocletOptions docletOptions, DocErrorReporter errorReporter, Optional<OutputTemplates> templates, Asciidoctor asciidoctor) {
053        this.asciidoctor = asciidoctor;
054        this.templates = templates;
055        this.options = buildOptions(docletOptions, errorReporter);
056    }
057
058    private Options buildOptions(DocletOptions docletOptions, DocErrorReporter errorReporter) {
059        OptionsBuilder opts = defaultOptions();
060        if (docletOptions.baseDir().isPresent()) opts.baseDir(docletOptions.baseDir().get());
061        if (templates.isPresent()) opts.templateDir(templates.get().templateDir());
062        opts.attributes(buildAttributes(docletOptions, errorReporter));
063        if (docletOptions.requires().size() > 0) {
064            for (String require : docletOptions.requires()) {
065                // FIXME AsciidoctorJ should provide a public API for requiring paths in the Ruby runtime
066                RubyUtils.requireLibrary(JRubyRuntimeContext.get(), require);
067            }
068        }
069        return opts.get();
070    }
071
072    private Attributes buildAttributes(DocletOptions docletOptions, DocErrorReporter errorReporter) {
073        return defaultAttributes()
074                .attributes(new AttributesLoader(asciidoctor, docletOptions, errorReporter).load())
075                .get();
076    }
077
078    /**
079     * Renders a generic document (class, field, method, etc)
080     *
081     * @param doc input
082     */
083    @Override
084    public void renderDoc(Doc doc) {
085        // hide text that looks like tags (such as annotations in source code) from Javadoc
086        doc.setRawCommentText(doc.getRawCommentText().replaceAll("@([A-Z])", "{@literal @}$1"));
087
088        StringBuilder buffer = new StringBuilder();
089        buffer.append(render(doc.commentText(), false));
090        buffer.append('\n');
091        for ( Tag tag : doc.tags() ) {
092            renderTag(tag, buffer);
093            buffer.append('\n');
094        }
095        doc.setRawCommentText(buffer.toString());
096    }
097
098    public void cleanup() {
099        if (templates.isPresent()) templates.get().delete();
100    }
101
102    /**
103     * Renders a document tag in the standard way.
104     *
105     * @param tag input
106     * @param buffer output buffer
107     */
108    private void renderTag(Tag tag, StringBuilder buffer) {
109        //print out directly
110        buffer.append(tag.name());
111        buffer.append(" ");
112        buffer.append(render(tag.text(), true));
113    }
114
115    /**
116     * Renders the input using Asciidoctor.
117     *
118     * The source is first cleaned by stripping any trailing space after an
119     * end line (e.g., `"\n "`), which gets left behind by the Javadoc
120     * processor.
121     *
122     * @param input AsciiDoc source
123     * @return content rendered by Asciidoctor
124     */
125    private String render(String input, boolean inline) {
126        options.setDocType(inline ? INLINE_DOCTYPE : null);
127        return asciidoctor.render(cleanJavadocInput(input), options);
128    }
129
130    protected static String cleanJavadocInput(String input){
131        return input.trim()
132            .replaceAll("\n ", "\n") // Newline space to accommodate javadoc newlines.
133            .replaceAll("\\{at}", "&#64;") // {at} is translated into @.
134            .replaceAll("\\{slash}", "/") // {slash} is translated into /.
135            .replaceAll("(?m)^( *)\\*\\\\/$", "$1*/") // Multi-line comment end tag is translated into */.
136            .replaceAll("\\{@literal (.*?)}", "$1"); // {@literal _} is translated into _ (standard javadoc).
137    }
138}