Skip to content

Instantly share code, notes, and snippets.

@abelsromero
Created June 16, 2020 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abelsromero/230ee100da0e074211aff12b3fd78b82 to your computer and use it in GitHub Desktop.
Save abelsromero/230ee100da0e074211aff12b3fd78b82 to your computer and use it in GitHub Desktop.

Asciidoctor Maven Plugin

Build Status (AppVeyor) Build Status (Travis CI) Coverage Status Maven Central

The Asciidoctor Maven Plugin is the official way to convert your AsciiDoc documentation using Asciidoctor from an Apache Maven build.

The conversion can happen in 2 flavors:

  1. as a Maven plugin: AsciiDoc files are converted at full Asciidoctor power independently from Maven site,

  2. as a Maven site integration: AsciiDoc files are integrated with Maven reports, which comes with a few limitations (see below for details).

Translations of the document are available in the following languages:
📎

You’re viewing the documentation for the upcoming release. If you’re looking for the documentation for an older release, please refer to one of the following tags:
1.6.01.5.81.5.7.11.5.61.5.51.5.31.5.2.1

Maven Plugin

Setup

As this is a typical Maven plugin, simply declare the plugin in the <plugins> section of your POM file:

Plugin declaration in pom.xml
<plugins>
    <plugin>
        <groupId>org.asciidoctor</groupId>
        <artifactId>asciidoctor-maven-plugin</artifactId>
        <version>1.5.8</version> <!--(1)-->
        ...
    </plugin>
</plugins>
  1. As this plugin tracks the version of Asciidoctor, you can use whichever version of Asciidoctor you prefer.

Execution setup
<plugin>
    ...
    <executions>
        <execution>
            <id>output-html</id>              <!--(1)-->
            <phase>generate-resources</phase> <!--(2)-->
            <goals>
                <goal>process-asciidoc</goal> <!--(3)-->
            </goals>
        </execution>
    </executions>
</plugin>
  1. This is simply an unique id for the execution

  2. The asciidoctor-maven-plugin does not run in any phase by default, so one must be specified

  3. The (only for the moment) Asciidoctor Maven plugin goal

Configuration

There are several configuration options that the Asciidoctor Maven plugin accepts, which parallel the options in Asciidoctor:

sourceDirectory

path where source files are located. By default checks for ${basedir}/src/docs/asciidoc, ${basedir}/src/asciidoc or ${basedir}/src/main/asciidoc in that order. When a custom value is set, no other paths are checked.

📎

All paths and AsciiDoc documents that start with _ are considered internal and are skipped. That is, AsciiDocs are not converted and resources are not copied from them, but you can include them normally from other AsciiDocs.
This is useful to split your sources in sets of master documents and included parts.

sourceDocumentName

an override to process a single source file; defaults to all files in ${sourceDirectory}.

sourceDocumentExtensions

(named extensions in v1.5.3 and below) a List<String> of non-standard file extensions to convert. Currently, ad, adoc, and asciidoc will be converted by default

resources

list of resource files to copy to the output directory (e.g., images, css). The configuration follows the same patterns as the maven-resources-plugin. If not set, all resources inside ${sourceDirectory} are copied.

📎

Converters that embed resources such as images into the output document need to be able to locate those resources at conversion time. For example, when generating a PDF (or HTML with the data-uri attribute set), all images need to be aggregated under a common root (i.e., image catalog). The imagesdir attribute should be overridden to point to that folder. When converting to HTML, images must be copied to the output location so that the browser can resolve those images when the user views the page.

<resources>
    <resource>
        <!-- (Mandatory) Directory to copy from. Paths are relative to maven's ${baseDir} -->
        <directory>DIRECTORY</directory>
        <!-- (Optional) Directory to copy to. By default uses the option `outputDirectory` -->
        <targetPath>OUTPUT_DIR</targetPath>
        <!-- (Optional) NOTE: SVN, GIT and other version control files are excluded by default, there's no need to add them -->
        <excludes>
            <exclude>**/.txt</exclude>
        </excludes>
        <!-- (Optional) If not set, includes all files but default exceptions mentioned -->
        <includes>
            <include>**/*.jpg</include>
            <include>**/*.gif</include>
        </includes>
    </resource>
    ...
</resources>
outputDirectory

locations where converted sources and copied resources will be places. Note that relative paths are added to the project root path. Defaults to ${project.build.directory}/generated-docs.

outputFile

defaults to null, used to override the name of the generated output file, can be a relative or absolute path. Useful for backends that create a single file, e.g. the pdf backend. All output will be redirected to the same file, the same way as the -o, --out-file=OUT_FILE option from the asciidoctor CLI command.

baseDir

(not Maven’s basedir) enables to set the root path for resources (e.g. included files), defaults to ${sourceDirectory}

skip

set this to true to bypass generation, defaults to false

preserveDirectories

enables to specify whether the documents should be converted in the same folder structure as in the source directory or not, defaults to false. When true, instead of generating all output in a single folder, output files are generated in the same structure. See the following example

    ├── docs                          ├── docs
    │   ├── examples.adoc             │   ├── examples.html
    │   └── examples            =>    │   └── examples
    │       ├── html.adoc             │       ├── html.html
    │       └── docbook.adoc          │       └── docbook.html
    └── index.adoc                    └── index.html
relativeBaseDir

only used when baseDir is not set, enables to specify that each AsciiDoc file must search for its resources in the same folder (for example, included files). Internally, for each AsciiDoc source, sets baseDir to the same path as the source file. Defaults to false

backend

defaults to html5

doctype

defaults to null (which trigger’s Asciidoctor’s default of article)

eruby

defaults to erb, the version used in JRuby

headerFooter

defaults to true

templateDirs

list of directories of compatible templates to be used instead of the default built-in templates, empty by default.

templateEngine

template engine to use for the custom converter templates, disabled by default (null)

templateCache

enables the built-in cache used by the template converter when reading the source of template files. Only relevant if the :template_dirs option is specified, defaults to true.

sourcemap

adds file and line number information to each parsed block (lineno and source_location attributes), defaults to false

catalogAssets

tells the parser to capture images and links in the reference table available via the references property on the document AST object (experimental), defaults to false

attributes

a Map<String,Object> of Asciidoctor attributes to pass for conversion, defaults to null

<attributes>
    <imagesdir>images</imagesdir>
    <source-highlighter>coderay</source-highlighter>
</attributes>
embedAssets

embeds the CSS file and images into the output, defaults to false

gemPaths

enables to specify the location to one or more gem installation directories (same as GEM_PATH environment var), empty by default

requires

a List<String> to specify additional Ruby libraries not packaged in AsciidoctorJ, empty by default

extensions

List of extensions to include during the conversion process (see AsciidoctorJ’s Extension API for information about the available options). For each extension, the implementation class must be specified in the className parameter, the blockName is only required when configuring a BlockProcessor, BlockMacroProcessor or InlineMacroProcessor.

extensions configuration example
<plugin>
    ...
    <executions>
        <execution>
            <configuration>
                ...
                <extensions>
                    <extension>
                        <className>org.asciidoctor.maven.SomePreprocessor</className>
                    </extension>
                    <extension>
                        <className>org.asciidoctor.maven.SomeBlockProcessor</className>
                        <blockName>yell</blockName>
                    </extension>
                </extensions>
            </configuration>
        </execution>
    </executions>
    <dependencies>
        <dependency> <!--(1)-->
            <groupId>org.asciidoctor.maven</groupId>
            <artifactId>my-asciidoctor-extensions</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
</plugin>
  1. Extensions must be included in the plugin’s execution classpath, not in the project’s.

📎
Extensions can also be integrated through the SPI interface implementation. This method does not require any configuration in the pom.xml, see Extension SPI for details.
enableVerbose

enables Asciidoctor verbose messages, defaults to false. Enable it, for example, if you want to validate internal cross references and capture the messages with the logHandler option.

logHandler

enables processing options for Asciidoctor messages (e.g. errors on missing included files), to either hide messages or setup build fail conditions based on them. Options are:

  • outputToConsole: Boolean, defaults to true. Redirects all Asciidoctor messages to Maven’s console logger as INFO during conversion.

  • failIf: build fail conditions, disabled by default. Allows setting one or many conditions that when met, abort the Maven build with BUILD FAILURE status.

    📎

    Note that the plugin matches that all conditions are met together. Unless you are controlling a very specific case, setting one condition should be enough.
    Also, messages matching fail conditions will be sent to Maven’s logger as ERROR. So, when enabling outputToConsole, some messages will appear duplicated as both INFO and ERROR.

    Currently, two conditions can be defined:

    • severity: severity of the Asciidoctor message, in order: INFO,WARN,ERROR,FATAL,UNKNOWN. Build will fail if a message is found of severity equal or higher.

    • containsText: text to search inside messages. Build will fail if the text is found.
      For example, set include to fail on any issue related to included files regardless the severity level.

      example: fail on any message
      <logHandler>
          <outputToConsole>false</outputToConsole> <!--(1)-->
          <failIf>
              <severity>DEBUG</severity> <!--(2)-->
          </failIf>
      </logHandler>
      1. Do not show messages as INFO in Maven output

      2. Build will fail on any message of severity DEBUG or higher, that includes all. All matching messages will appear as ERROR in Maven output.

📎

Since version 1.5.8 of AsciidoctorJ set enableVerbose to true option to validate internal cross references, this is being improved to avoid false positives See #2722 if your are interested in the details.

Built-in attributes

There are various attributes Asciidoctor recognizes. Below is a list of them and what they do.

title

An override for the title of the document.

📎
This attribute, for backwards compatibility, can still be used in the top level configuration options.

Many other attributes are possible. Refer to the catalog of document attributes in the Asciidoctor user manual for a complete list.

More will be added in the future to take advantage of other options and attributes of Asciidoctor. Any setting in the attributes section that conflicts with an explicitly named attribute configuration will be overidden by the explicitly named attribute configuration. These settings can all be changed in the <configuration> section of the plugin section:

Plugin configuration options
<plugin>
    <configuration>
        <sourceDirectory>src/docs/asciidoc</sourceDirectory>
        <outputDirectory>target/docs/asciidoc</outputDirectory>
        <backend>html</backend>
        <doctype>book</doctype>
        <attributes>
            <toc>left</toc>
            <icons>font</icons>
            <stylesheet>my-theme.css</stylesheet>
        </attributes>
    </configuration>
</plugin>

Passing POM properties

It is possible to pass properties defined in the POM to the Asciidoctor processor. This is handy for example to include in the generated document the POM artifact version number.

This is done by creating a custom AsciiDoc property in the attributes section of the configuration. The AsciiDoc property value is defined in the usual Maven way: ${property.name}.

<attributes>
    <project-version>${project.version}</project-version>
</attributes>

The custom AsciiDoc property can then be used in the document like this:

The latest version of the project is {project-version}.

Setting boolean values

Boolean attributes in asciidoctor, such as sectnums, linkcss or copycss can be set with a value of true and unset with a value of false.

Examples

In the <attributes> part of the Asciidoctor Maven Plugin configuration:

<sectnums>true</sectnums>
<linkcss>false</linkcss>

You can find more information and many examples ready to copy-paste in the Asciidoctor Maven examples project.

Command line configuration

Configuration options can be set (but not replaced) using system properties directly in the command line as follows:

mvn generate-resources -Dasciidoctor.sourceDirectory=src/docs -Dasciidoctor.outputDirectory=target/docs

All options follow the naming convention `asciidoctor.` + option_name.

In order to provide a higher degree of flexibility attributes configuration follows a different behavior. Attributes defined through the command line are added to the ones already found in the XML configuration. The result of it is that attributes and other configuration options can be updated if they are added to the command line as attributes. For example, the following configuration could be modified with the command options as seen below.

<configuration>
    <backend>html5</backend>
    <attributes>
        <toc>left</toc>
    </attributes>
</configuration>
mvn generate-resources -Dasciidoctor.attributes=toc=right
mvn generate-resources -Dasciidoctor.attributes="toc=right source-highlighter=highlight.js imagesdir=my_images"

Note that in the second case we need to use quotes due to the spaces.

Multiple outputs for the same file

Maven has the ability to execute a Mojo multiple times. Instead of reinventing the wheel inside the Mojo, we’ll push this off to Maven to handle the multiple executions. An example of this setup is below:

Multiple configuration extract
<plugin>
    <groupId>org.asciidoctor</groupId>
    <artifactId>asciidoctor-maven-plugin</artifactId>
    <version>1.5.8</version>
    <executions>
        <execution> <!--(1)-->
            <id>output-html</id>
            <phase>generate-resources</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>html</backend>
                <attributes>
                    <toc/>
                    <linkcss>false</linkcss>
                    <source-highlighter>coderay</source-highlighter>
                </attributes>
            </configuration>
        </execution>
        <execution> <!--(2)-->
            <id>output-docbook</id>
            <phase>generate-resources</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>docbook</backend>
                <doctype>book</doctype>
            </configuration>
        </execution>
    </executions>
    <configuration>  <!--(3)-->
        <sourceDirectory>src/main/asciidoc</sourceDirectory>
        <headerFooter>true</headerFooter>
    </configuration>
</plugin>
  1. First execution, converts documents to HTML.

  2. Second execution, converts documents to DocBook.

  3. Any configuration outside the executions section is inherited by each execution. This allows an easier way to share common configuration options.

Maven Site Integration

Setup

To author your Maven-generated site in AsciiDoc, you must first add a dependency on the Asciidoctor plugin to your maven-site-plugin declaration (which more precisely adds a Doxia Parser Module).

Maven v3.2.1 or above required, and since asciidoctor-maven-plugin v1.5.6 only maven-site-plugin v3.4 or above is supported.
Maven site integration
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.9.0</version>
            <dependencies>
                <dependency><!-- add Asciidoctor Doxia Parser Module -->
                    <groupId>org.asciidoctor</groupId>
                    <artifactId>asciidoctor-maven-plugin</artifactId>
                    <version>1.5.8</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

The Asciidoctor Doxia module follows the maven-site-plugin conventions for file location, and delegates all resource management to it.

First, all of your AsciiDoc-based files should be placed in src/site/asciidoc with an extension of .adoc. These files will be converted into the target/site directory. For example, the file src/site/asciidoc/usage.adoc will be converted into target/site/usage.html.

Then, all resources (images, css, etc.) should be placed in src/site/resources. These will be automatically copied into target/site.

Also note that AsciiDoc files are converted to embeddable HTML and inserted into the site’s page layout. This disables certain features such as the sidebar toc.

Make sure you add a menu item for each page so you can access it from the site navigation:

site.xml
<body>
    ...
    <menu name="User guide">
        <item href="usage.html" name="Usage" />
    </menu>
    ...
</body>

Configuration

As of version 1.5.3 of the plugin, you can configure Asciidoctor by specifying configuration properties in the plugin declaration, just like with the main plugin goal. There are two important differences, however.

  1. All the configuration for Asciidoctor in the site integration must be nested inside an <asciidoc> element. This is necessary since the <configuration> element is used to configure more than just the Asciidoctor integration.

    Here’s an example that shows how to set options, attributes and ignore partial AsciiDoc files (i.e., files that begin with an underscore).

    Maven site integration with Asciidoctor configuration
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.9.0</version>
        <configuration>
            <asciidoc>
                <templateDirs>
                    <dir>src/site/asciidoc/templates</dir>
                </templateDirs>
                <requires>
                    <require>asciidoctor-diagram</require>
                </requires>
                <attributes>
                    <source-highlighter>coderay</source-highlighter>
                    <coderay-css>style</coderay-css>
                </attributes>
            </asciidoc>
            <moduleExcludes>
                <asciidoc>**/_*.adoc</asciidoc>
            </moduleExcludes>
        </configuration>
        <dependencies>
            <dependency>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.8</version>
            </dependency>
        </dependencies>
    </plugin>

    The Asciidoctor base directory (i.e., document root) is configured as src/site/asciidoc by default, though this can be overridden. To do so, you can use either maven-site-plugin siteDirectory or Asciidoctor baseDir configuration options. Note that the first will affect the default resources directory also.

    You’ll notice in the example that excludes have been added for certain AsciiDoc files. This prevents the site integration from processing partial files (i.e., includes) as individual pages. You can tune this pattern to your liking. There’s currently no way (that we can tell) to configure this automatically.

  2. For simplicity and the fact that resources are managed by maven-site-plugin, not all options found in the asciidoctor-maven-plugin are available in the <asciidoc> element.

    The supported ones are:

    baseDir

    Same as the plugin’s baseDir. Sets the root path for resources. Not set by default, AsciiDoc documents will be searched in src/site/asciidoc. External resources should be located in src/site/resources.

    📎
    Consider using maven-site-plugin’s siteDirectory instead for better integration with the site functions (ie. resource copying).
    templatesDirs (also template_dirs)

    Built-in templates are supported by specifying one or more template directories. This feature enables you to provide custom templates for converting any node in the tree (e.g., document, section, listing, etc). Custom templates can be extremely helpful when trying to customize the appearance of your site. Each path to add should be enclosed in a <dir> element.

    requires

    Same as the plugin’s requires.
    Specifies additional Ruby libraries not packaged in AsciidoctorJ, empty by default.

    attributes

    Similar to the plugin’s attributes.
    Allows defining a set of Asciidoctor attributes to be passed to the conversion.
    In addition to those attributes found in this section, any maven property is also passed as attribute (replacing . by -).

    <properties>
      <my-site.version>2.3.0</my-site.version> (1)
    </properties>
    1. Will be passed as my-site-version to the converter

    logHandler

    Sames as the plugin’s requires.
    Enables processing of Asciidoctor messages. For example to hide them, enable finer detail or fail the build on certain scenarios (e.g. missing included files). For conciseness the options are not reproduced here, please to see all options refer to the main plugin logHandler configuration.

    Due to limitations in how Maven site integration works, it is not possible to provide the filename in the error message. We are aware this is not ideal and are tracking any development on the Maven side towards this goal (DOXIA-555).

Hacking

Developer setup for hacking on this project isn’t very difficult. The requirements are very small:

  • Java 8 or higher

  • Maven 3

Everything else will be brought in by Maven. This is a typical Maven Java project, nothing special. You should be able to use IntelliJ, Eclipse, or Netbeans without any issue for hacking on the project.

Building

Standard Maven build:

mvn clean install

Testing

Unit tests are written with Spock. This will be downloaded by Maven and can be run from IntelliJ without any additional setup. Tests are run simply by:

mvn clean test

Or any of the other goals which run tests.

Integration tests under src/it are run using maven-invoker-plugin and the runt-its profile. To only run them without excluding unit tests, use:

mvn clean verify -DskipTests -Prun-its

To run all tests at once just use mvn clean verify -DskipTests -Prun-its.

Tips & Tricks

Generate your documentation in separate folders per version

Use Maven project.version property to create dedicated custom output directories.

<configuration>
    ...
    <outputDirectory>target/generated-docs/${project.version}</outputDirectory>
    ...
</configuration>

Enable section numbering

Enable section numbering in the build using the attributes section.

<configuration>
    ...
    <attributes>
        ...
        <sectnums>true</sectnums>
        ...
    </attributes>
    ...
</configuration>

Add version and build date to the header

Automatically add version details to header and footer to all documents.

<properties>
   <maven.build.timestamp.format>yyyy-MM-dd HH</maven.build.timestamp.format>  (1)
</properties>

<configuration>
    ...
    <attributes>
        ...
        <revnumber>${project.version}</revnumber>
        <revdate>${maven.build.timestamp}</revdate>
        <organization>${project.organization.name}</organization>
    </attributes>
    ...
</configuration>
  1. Add maven.build.timestamp.format to the pom’s properties section to set a custom date format.

Show Asciidoctor version

If you are not sure what version of the Asciidoctor converter is being used. You can obtain it using the version attribute like in the example blow.

Asciidoctor version: {asciidoctor-version}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment