Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

asciidoc markup generator #3845

Merged
merged 16 commits into from
Sep 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
|-|-|
**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client), **Kotlin**, **Lua**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs)
**Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin** (Spring Boot, Ktor), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra)
**API documentation generators** | **HTML**, **Confluence Wiki**
**API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**
**Configuration files** | [**Apache2**](https://httpd.apache.org/)
**Others** | **GraphQL**, **JMeter**, **MySQL Schema**

Expand Down
31 changes: 31 additions & 0 deletions bin/asciidoc-documentation-petstore.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/sh

SCRIPT="$0"

while [ -h "$SCRIPT" ] ; do
ls=$(ls -ld "$SCRIPT")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=$(dirname "$SCRIPT")/"$link"
fi
done

if [ ! -d "${APP_DIR}" ]; then
APP_DIR=$(dirname "$SCRIPT")/..
APP_DIR=$(cd "${APP_DIR}"; pwd)
fi

executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"

if [ ! -f "$executable" ]
then
mvn clean package
fi

# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/openapi-generator/src/main/resources/asciidoc-documentation --additional-properties=specDir=modules/openapi-generator/src/main/resources/asciidoc-documentation,snippetDir=. -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g asciidoc -o samples/documentation/asciidoc"

java ${JAVA_OPTS} -jar ${executable} ${ags}
10 changes: 10 additions & 0 deletions bin/windows/asciidoc-documentation-petstore.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate --artifact-id "asciidoc-petstore-documentation" -t modules\openapi-generator\src\main\resources\asciidoc-documentation --additional-properties=specDir=modules\openapi-generator\src\main\resources\asciidoc-documentation,snippetDir=. -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g asciidoc -o samples\documentation\asciidoc

java %JAVA_OPTS% -jar %executable% %ags%
1 change: 1 addition & 0 deletions docs/generators.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ The following generators are available:


## DOCUMENTATION generators
* [asciidoc](generators/asciidoc)
* [cwiki](generators/cwiki)
* [dynamic-html](generators/dynamic-html)
* [html](generators/html)
Expand Down
25 changes: 25 additions & 0 deletions docs/generators/asciidoc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

---
id: generator-opts-documentation-asciidoc
title: Config Options for asciidoc
sidebar_label: asciidoc
---

| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|appName|short name of the application| |null|
|appDescription|description of the application| |null|
|infoUrl|a URL where users can get more information about the application| |null|
|infoEmail|an email address to contact for inquiries about the application| |null|
|licenseInfo|a short description of the license| |null|
|licenseUrl|a URL pointing to the full license| |null|
|invokerPackage|root package for generated code| |null|
|groupId|groupId in generated pom.xml| |null|
|artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |null|
|artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |null|
|snippetDir|path with includable markup snippets (e.g. test output generated by restdoc, default: .| |.|
|specDir|path with includable markup spec files (e.g. handwritten additional docs, default: .| |..|
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
package org.openapitools.codegen.languages;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add the copyright header in a separate PR.


import org.openapitools.codegen.*;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;

import io.swagger.v3.oas.models.OpenAPI;

/**
* basic asciidoc markup generator.
*
* @see <a href="https://asciidoctor.org">asciidoctor</a>
*/
public class AsciidocDocumentationCodegen extends DefaultCodegen implements CodegenConfig {

private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocDocumentationCodegen.class);

public static final String SPEC_DIR = "specDir";
public static final String SNIPPET_DIR = "snippetDir";

/**
* Lambda emitting an asciidoc "include::filename.adoc[]" if file is found in
* path. Use:
*
* <pre>
* {{#includemarkup}}{{name}}/description.adoc{{/includemarkup}}
* </pre>
*/
public class IncludeMarkupLambda implements Mustache.Lambda {

private long includeCount = 0;
private long notFoundCount = 0;
private String basePath;

public IncludeMarkupLambda(final String basePath) {
this.basePath = basePath;
}

public String resetCounter() {
String msg = "included: " + includeCount + " notFound: " + notFoundCount + " from " + basePath;
includeCount = 0;
notFoundCount = 0;
return msg;
}

@Override
public void execute(final Template.Fragment frag, final Writer out) throws IOException {

final String relativeFileName = AsciidocDocumentationCodegen.sanitize(frag.execute());
final Path filePathToInclude = Paths.get(basePath, relativeFileName).toAbsolutePath();

if (Files.isRegularFile(filePathToInclude)) {
LOGGER.debug(
"including " + ++includeCount + ". file into markup from: " + filePathToInclude.toString());
out.write("\ninclude::" + relativeFileName + "[]\n");
} else {
LOGGER.debug(++notFoundCount + ". file not found, skip include for: " + filePathToInclude.toString());
out.write("\n// markup not found, no include ::" + relativeFileName + "[]\n");
}
}
}

/**
* Lambda emitting an asciidoc "http link" if file is found in path. Use:
*
* <pre>
* {{#snippetLink}}markup until koma, /{{name}}.json{{/snippetLink}}
* </pre>
*/
public class LinkMarkupLambda implements Mustache.Lambda {

private long linkedCount = 0;
private long notFoundLinkCount = 0;
private String basePath;

public LinkMarkupLambda(final String basePath) {
this.basePath = basePath;
}

public String resetCounter() {
String msg = "linked:" + linkedCount + " notFound: " + notFoundLinkCount + " from " + basePath;
linkedCount = 0;
notFoundLinkCount = 0;
return msg;
}

@Override
public void execute(final Template.Fragment frag, final Writer out) throws IOException {

final String content = frag.execute();
final String[] tokens = content.split(",", 2);

final String linkName = tokens.length > 0 ? tokens[0] : "";

final String relativeFileName = AsciidocDocumentationCodegen
.sanitize(tokens.length > 1 ? tokens[1] : linkName);

final Path filePathToLinkTo = Paths.get(basePath, relativeFileName).toAbsolutePath();

if (Files.isRegularFile(filePathToLinkTo)) {
LOGGER.debug("linking " + ++linkedCount + ". file into markup from: " + filePathToLinkTo.toString());
out.write("\n" + linkName + " link:" + relativeFileName + "[]\n");
} else {
LOGGER.debug(++notFoundLinkCount + ". file not found, skip link for: " + filePathToLinkTo.toString());
out.write("\n// file not found, no " + linkName + " link :" + relativeFileName + "[]\n");
}
}
}

protected String invokerPackage = "org.openapitools.client";
protected String groupId = "org.openapitools";
protected String artifactId = "openapi-client";
protected String artifactVersion = "1.0.0";

private IncludeMarkupLambda includeSpecMarkupLambda;
private IncludeMarkupLambda includeSnippetMarkupLambda;
private LinkMarkupLambda linkSnippetMarkupLambda;

public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}

/**
* extracted filter value should be relative to be of use as link or include
* file.
*
* @param name filename to sanitize
* @return trimmed and striped path part or empty string.
*/
static String sanitize(final String name) {
String sanitized = name == null ? "" : name.trim();
return sanitized.startsWith(File.separator) || sanitized.startsWith("/") ? sanitized.substring(1) : sanitized;
}

public String getName() {
return "asciidoc";
}

public String getHelp() {
return "Generates asciidoc markup based documentation.";
}

public String getSpecDir() {
return additionalProperties.get("specDir").toString();
}

public String getSnippetDir() {
return additionalProperties.get("snippetDir").toString();
}

public AsciidocDocumentationCodegen() {
super();

LOGGER.trace("start asciidoc codegen");

outputFolder = "generated-code" + File.separator + "asciidoc";
embeddedTemplateDir = templateDir = "asciidoc-documentation";

defaultIncludes = new HashSet<String>();

cliOptions.add(new CliOption("appName", "short name of the application"));
cliOptions.add(new CliOption("appDescription", "description of the application"));
cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application"));
cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application"));
cliOptions.add(new CliOption("licenseInfo", "a short description of the license"));
cliOptions.add(new CliOption(CodegenConstants.LICENSE_URL, "a URL pointing to the full license"));
cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC));

cliOptions.add(new CliOption(SNIPPET_DIR,
"path with includable markup snippets (e.g. test output generated by restdoc, default: .")
.defaultValue("."));
cliOptions.add(new CliOption(SPEC_DIR,
"path with includable markup spec files (e.g. handwritten additional docs, default: .")
.defaultValue(".."));

additionalProperties.put("appName", "OpenAPI Sample description");
additionalProperties.put("appDescription", "A sample OpenAPI documentation");
additionalProperties.put("infoUrl", "https://openapi-generator.tech");
additionalProperties.put("infoEmail", "team@openapitools.org");
additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put(CodegenConstants.LICENSE_URL, "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);

supportingFiles.add(new SupportingFile("index.mustache", "", "index.adoc"));
reservedWords = new HashSet<String>();

languageSpecificPrimitives = new HashSet<String>();
importMapping = new HashMap<String, String>();

}

@Override
public String escapeQuotationMark(String input) {
return input; // just return the original string
}

@Override
public String escapeUnsafeCharacters(String input) {
return input; // just return the original string
}

@Override
public void processOpts() {
super.processOpts();

String specDir = this.additionalProperties.get(SPEC_DIR) + "";
if (!Files.isDirectory(Paths.get(specDir))) {
LOGGER.warn("base part for include markup lambda not found: " + specDir + " as "
+ Paths.get(specDir).toAbsolutePath());
}
;

this.includeSpecMarkupLambda = new IncludeMarkupLambda(specDir);
additionalProperties.put("specinclude", this.includeSpecMarkupLambda);

String snippetDir = this.additionalProperties.get(SNIPPET_DIR) + "";
if (!Files.isDirectory(Paths.get(snippetDir))) {
LOGGER.warn("base part for include markup lambda not found: " + snippetDir + " as "
+ Paths.get(snippetDir).toAbsolutePath());
}
;

this.includeSnippetMarkupLambda = new IncludeMarkupLambda(snippetDir);
additionalProperties.put("snippetinclude", this.includeSnippetMarkupLambda);

this.linkSnippetMarkupLambda = new LinkMarkupLambda(snippetDir);
additionalProperties.put("snippetlink", this.linkSnippetMarkupLambda);
}

@Override
public void processOpenAPI(OpenAPI openAPI) {
if (this.includeSpecMarkupLambda != null) {
LOGGER.info("specs: " + ": " + this.includeSpecMarkupLambda.resetCounter());
}
if (this.includeSnippetMarkupLambda != null) {
LOGGER.info("snippets: " + ": " + this.includeSnippetMarkupLambda.resetCounter());
}
super.processOpenAPI(openAPI);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,5 @@ org.openapitools.codegen.languages.TypeScriptJqueryClientCodegen
org.openapitools.codegen.languages.TypeScriptNodeClientCodegen
org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen
org.openapitools.codegen.languages.FsharpGiraffeServerCodegen

org.openapitools.codegen.languages.AsciidocDocumentationCodegen
Loading