From def23015fa28dafc2efa3ad6e42b31098b666522 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Tue, 27 Aug 2019 00:11:01 +0200 Subject: [PATCH 01/14] basic asciidoc markup generation --- bin/asciidoc-documentation-petstore.sh | 31 +++++++ .../asciidoc-documentation-petstore.bat | 10 +++ .../AsciidocDocumentationCodegen.java | 87 +++++++++++++++++++ .../org.openapitools.codegen.CodegenConfig | 2 + .../asciidoc-documentation/index.mustache | 79 +++++++++++++++++ .../asciidoc-documentation/model.mustache | 28 ++++++ .../asciidoc-documentation/param.mustache | 6 ++ .../asciidoc-documentation/params.mustache | 53 +++++++++++ 8 files changed, 296 insertions(+) create mode 100644 bin/asciidoc-documentation-petstore.sh create mode 100644 bin/windows/asciidoc-documentation-petstore.bat create mode 100644 modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java create mode 100644 modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache create mode 100644 modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache create mode 100644 modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache create mode 100644 modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache diff --git a/bin/asciidoc-documentation-petstore.sh b/bin/asciidoc-documentation-petstore.sh new file mode 100644 index 000000000000..fa0d403a3d8a --- /dev/null +++ b/bin/asciidoc-documentation-petstore.sh @@ -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 -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g asciidoc -o samples/documentation/petstore/asciidoc" + +java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/windows/asciidoc-documentation-petstore.bat b/bin/windows/asciidoc-documentation-petstore.bat new file mode 100644 index 000000000000..f81202b24512 --- /dev/null +++ b/bin/windows/asciidoc-documentation-petstore.bat @@ -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 -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g asciidoc -o samples\documentation\petstore\asciidoc + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java new file mode 100644 index 000000000000..e7a8050f678c --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -0,0 +1,87 @@ +package org.openapitools.codegen.languages; + +import org.openapitools.codegen.*; + +import java.io.File; +import java.util.HashMap; +import java.util.HashSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** basic asciidoc generator. + * @see asciidoctor + */ +public class AsciidocDocumentationCodegen extends DefaultCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "projectName"; + + static Logger LOGGER = LoggerFactory.getLogger(AsciidocDocumentationCodegen.class); + + protected String invokerPackage = "org.openapitools.client"; + protected String groupId = "org.openapitools"; + protected String artifactId = "openapi-client"; + protected String artifactVersion = "1.0.0"; + + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "asciidoc"; + } + + public String getHelp() { + return "Generates a asciidoc documentation."; + } + + public AsciidocDocumentationCodegen() { + super(); + + LOGGER.info("start asciidoc codegen"); + + outputFolder = "generated-code" + File.separator + "asciidoc"; + embeddedTemplateDir = templateDir = "asciidoc-documentation"; + + defaultIncludes = new HashSet(); + + 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("licenseUrl", "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)); + + 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("licenseUrl", "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(); + + languageSpecificPrimitives = new HashSet(); + importMapping = new HashMap(); + + } + + @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 + } +} diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index f6ca902864db..d5aa2dac2370 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -112,3 +112,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 diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache new file mode 100644 index 000000000000..c330fa8855cd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -0,0 +1,79 @@ += {{{appName}}} +{{infoEmail}} +{{#version}}{{{version}}}{{/version}} +:toc: left +:numbered: +:toclevels: 3 +:source-highlighter: highlightjs + +[abstract] +.Abstract +{{{appDescription}}} + +== Endpoints + +{{#apiInfo}} +{{#apis}} +{{#operations}} + +[.{{baseName}}] +=== {{baseName}} + +{{#operation}} + +[.{{nickname}}] +==== {{nickname}} + +`{{httpMethod}} {{path}}` + +{{{summary}}} + +{{#notes}} +===== Description + +{{{notes}}} +{{/notes}} + +{{> params}} + +===== Return Type + +{{#hasReference}} +{{^returnSimpleType}}{{returnContainer}}[{{/returnSimpleType}}<<{{returnBaseType}}>>{{^returnSimpleType}}]{{/returnSimpleType}} +{{/hasReference}} + +{{^hasReference}} +{{#returnType}}<<{{returnType}}>>{{/returnType}} +{{^returnType}}-{{/returnType}} +{{/hasReference}} + +{{#hasProduces}} +===== Content Type + +{{#produces}} +* {{{mediaType}}} +{{/produces}} +{{/hasProduces}} + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + +{{#responses}} + +| {{code}} +| {{message}} +| {{#dataType}} <<{{dataType}}>>{{/dataType}} + +{{/responses}} +|=== + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +{{> model}} diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache new file mode 100644 index 000000000000..7a6ccd9fbd3e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache @@ -0,0 +1,28 @@ +[#models] +== Models + +{{#models}} + {{#model}} + +[#{{classname}}] +==== _{{classname}}_ {{title}} + +{{unescapedDescription}} + +[.fields-{{classname}}] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +{{#vars}} +| {{name}} +| {{^required}}X{{/required}} +| {{dataType}} {{#isContainer}} of <<{{complexType}}>>{{/isContainer}} +| {{description}} +| {{{dataFormat}}} {{#isEnum}}Enum: {{#_enum}}{{this}},{{/_enum}}{{/isEnum}} + +{{/vars}} +|=== + + {{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache new file mode 100644 index 000000000000..51c4447d8033 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache @@ -0,0 +1,6 @@ +| {{paramName}} +| {{description}} {{#baseType}}<<{{baseType}}>>{{/baseType}} +| {{^required}}-{{/required}}{{#required}}X{{/required}} +| {{defaultValue}} +| {{{pattern}}} + diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache new file mode 100644 index 000000000000..bc895ee93f1d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache @@ -0,0 +1,53 @@ +===== Parameters + +{{#hasPathParams}} +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#pathParams}} +{{>param}} +{{/pathParams}} +|=== +{{/hasPathParams}} + +{{#hasBodyParam}} +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#bodyParams}} +{{>param}} +{{/bodyParams}} +|=== +{{/hasBodyParam}} + +{{#hasHeaderParams}} +====== Header Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#headerParams}} +{{>param}} +{{/headerParams}} +|=== +{{/hasHeaderParams}} + +{{#hasQueryParams}} +====== Query Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#queryParams}} +{{>param}} +{{/queryParams}} +|=== +{{/hasQueryParams}} From 15e8ceb2d4202dc3246a5314270e89097372e923 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Wed, 28 Aug 2019 00:57:16 +0200 Subject: [PATCH 02/14] asciidoc markup include processing with mustache filter --- .../AsciidocDocumentationCodegen.java | 89 +++++++++++++++++-- .../asciidoc-documentation/index.mustache | 11 +++ .../asciidoc-documentation/stubs/empty.adoc | 1 + 3 files changed, 95 insertions(+), 6 deletions(-) create mode 100644 modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index e7a8050f678c..63fb17cd6df7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -3,25 +3,82 @@ 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; -/** basic asciidoc generator. +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; + +import io.swagger.v3.oas.models.OpenAPI; + +/** basic asciidoc markup generator. * @see asciidoctor */ public class AsciidocDocumentationCodegen extends DefaultCodegen implements CodegenConfig { - public static final String PROJECT_NAME = "projectName"; - static Logger LOGGER = LoggerFactory.getLogger(AsciidocDocumentationCodegen.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocDocumentationCodegen.class); + /** + * Lambda emitting an asciidoc "include::filename.adoc[]" if file is found in path. + * Use: + *
{{#includeMarkup}}{{name}}/description.adoc{{/includeMarkup}}
+ */ + public class IncludeMarkupLambda implements Mustache.Lambda { + + /** {{includeMarkup}} */ + public static final String includeMarkupTag = "includemarkup"; + + private CodegenConfig config; + + private long includeCount = 0; + private long notFoundCount = 0; + + public IncludeMarkupLambda(final CodegenConfig config) { + this.config = config; + } + + public String resetCounter( ) { + String msg = "included:" + includeCount + " notFound: " + notFoundCount; + includeCount = 0; + notFoundCount = 0; + return msg; + } + + @Override + public void execute(final Template.Fragment frag, final Writer out) throws IOException { + + String basePath = config.templateDir() != null ? config.templateDir() : "."; + if( !Files.isDirectory(Paths.get(config.templateDir()))) { + LOGGER.warn("base part for include markup lambda not found: " + basePath); + }; + + final String relativeFileName = frag.execute(); + final Path filePathToInclude = Paths.get(basePath, relativeFileName); + + if(Files.isRegularFile(filePathToInclude)) { + LOGGER.debug("including " + ++includeCount + ". file into markup: " + filePathToInclude.toAbsolutePath().toString()); + out.write("\ninclude::" + relativeFileName + "[]\n"); + } else { + LOGGER.debug(++notFoundCount + ". file not found, skip include into markup: " + filePathToInclude.toAbsolutePath().toString()); + out.write("\n// markup not included, not found: include::" + 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 includeMarkupLambda; public CodegenType getTag() { return CodegenType.DOCUMENTATION; @@ -32,13 +89,13 @@ public String getName() { } public String getHelp() { - return "Generates a asciidoc documentation."; + return "Generates asciidoc markup based documentation."; } public AsciidocDocumentationCodegen() { super(); - LOGGER.info("start asciidoc codegen"); + LOGGER.trace("start asciidoc codegen"); outputFolder = "generated-code" + File.separator + "asciidoc"; embeddedTemplateDir = templateDir = "asciidoc-documentation"; @@ -84,4 +141,24 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { return input; // just return the original string } + + @Override + public void processOpts() { + super.processOpts(); + // addMustacheLambdas() does not work. + this.includeMarkupLambda = new IncludeMarkupLambda(this); + additionalProperties.put(IncludeMarkupLambda.includeMarkupTag, this.includeMarkupLambda ); + } + + @Override + public void processOpenAPI(OpenAPI openAPI) { + if(this.includeMarkupLambda != null) { + LOGGER.info( + IncludeMarkupLambda.includeMarkupTag + + ": " + + this.includeMarkupLambda.resetCounter()); + } + super.processOpenAPI(openAPI); + } + } diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache index c330fa8855cd..140cdc65042c 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -5,11 +5,14 @@ :numbered: :toclevels: 3 :source-highlighter: highlightjs +:keywords: openapi, rest, {{appName}} [abstract] .Abstract {{{appDescription}}} +{{#includemarkup}}stubs/empty.adoc{{/includemarkup}} + == Endpoints {{#apiInfo}} @@ -29,6 +32,9 @@ {{{summary}}} {{#notes}} + +{{#includemarkup}}{{baseName}}/{{nickname}}/operation-spec.adoc{{/includemarkup}} + ===== Description {{{notes}}} @@ -71,6 +77,11 @@ {{/responses}} |=== +===== Samples + +{{#includemarkup}}{{baseName}}/{{nickname}}/http-request.adoc{{/includemarkup}} +{{#includemarkup}}{{baseName}}/{{nickname}}/http-response.adoc{{/includemarkup}} + {{/operation}} {{/operations}} {{/apis}} diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc b/modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc new file mode 100644 index 000000000000..5d3959a037b8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc @@ -0,0 +1 @@ +// openapi generator built documentation, see https://github.com/OpenAPITools/openapi-generator From 12f2e92c53c5ac64aed599b199ca6a2d41bc6ed3 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Fri, 30 Aug 2019 00:23:46 +0200 Subject: [PATCH 03/14] asciidoc tests, separate include filters --- .../asciidoc-documentation-petstore.bat | 2 +- .../AsciidocDocumentationCodegen.java | 84 ++++++++----- .../asciidoc-documentation/index.mustache | 12 +- .../asciidoc-documentation/model.mustache | 4 +- .../asciidoc/AsciidocGeneratorTest.java | 112 ++++++++++++++++++ .../asciidoc/IncludeMarkupFilterTest.java | 46 +++++++ 6 files changed, 225 insertions(+), 35 deletions(-) create mode 100644 modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java create mode 100644 modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java diff --git a/bin/windows/asciidoc-documentation-petstore.bat b/bin/windows/asciidoc-documentation-petstore.bat index f81202b24512..b930e5b05de9 100644 --- a/bin/windows/asciidoc-documentation-petstore.bat +++ b/bin/windows/asciidoc-documentation-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) 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 -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g asciidoc -o samples\documentation\petstore\asciidoc +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\petstore\asciidoc java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index 63fb17cd6df7..f605962c95dc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -25,28 +25,27 @@ 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: *
{{#includeMarkup}}{{name}}/description.adoc{{/includeMarkup}}
*/ public class IncludeMarkupLambda implements Mustache.Lambda { - - /** {{includeMarkup}} */ - public static final String includeMarkupTag = "includemarkup"; - - private CodegenConfig config; private long includeCount = 0; private long notFoundCount = 0; + private String basePath; - public IncludeMarkupLambda(final CodegenConfig config) { - this.config = config; + public IncludeMarkupLambda(final String basePath) { + this.basePath = basePath; } public String resetCounter( ) { - String msg = "included:" + includeCount + " notFound: " + notFoundCount; + String msg = "included:" + includeCount + " notFound: " + notFoundCount + " from " + basePath; includeCount = 0; notFoundCount = 0; return msg; @@ -54,20 +53,15 @@ public String resetCounter( ) { @Override public void execute(final Template.Fragment frag, final Writer out) throws IOException { - - String basePath = config.templateDir() != null ? config.templateDir() : "."; - if( !Files.isDirectory(Paths.get(config.templateDir()))) { - LOGGER.warn("base part for include markup lambda not found: " + basePath); - }; final String relativeFileName = frag.execute(); final Path filePathToInclude = Paths.get(basePath, relativeFileName); if(Files.isRegularFile(filePathToInclude)) { - LOGGER.debug("including " + ++includeCount + ". file into markup: " + filePathToInclude.toAbsolutePath().toString()); + LOGGER.debug("including " + ++includeCount + ". file into markup from: " + filePathToInclude.toAbsolutePath().toString()); out.write("\ninclude::" + relativeFileName + "[]\n"); } else { - LOGGER.debug(++notFoundCount + ". file not found, skip include into markup: " + filePathToInclude.toAbsolutePath().toString()); + LOGGER.debug(++notFoundCount + ". file not found, skip include for: " + relativeFileName); out.write("\n// markup not included, not found: include::" + relativeFileName + "[]\n"); } } @@ -78,7 +72,8 @@ public void execute(final Template.Fragment frag, final Writer out) throws IOExc protected String artifactId = "openapi-client"; protected String artifactVersion = "1.0.0"; - private IncludeMarkupLambda includeMarkupLambda; + private IncludeMarkupLambda includeSpecMarkupLambda; + private IncludeMarkupLambda includeSnippetMarkupLambda; public CodegenType getTag() { return CodegenType.DOCUMENTATION; @@ -91,6 +86,14 @@ public String getName() { 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(); @@ -107,23 +110,32 @@ public AsciidocDocumentationCodegen() { 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("licenseUrl", "a URL pointing to the full 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("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + 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(); @@ -145,18 +157,36 @@ public String escapeUnsafeCharacters(String input) { @Override public void processOpts() { super.processOpts(); - // addMustacheLambdas() does not work. - this.includeMarkupLambda = new IncludeMarkupLambda(this); - additionalProperties.put(IncludeMarkupLambda.includeMarkupTag, this.includeMarkupLambda ); + + 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 ); } @Override public void processOpenAPI(OpenAPI openAPI) { - if(this.includeMarkupLambda != null) { + if(this.includeSpecMarkupLambda != null) { + LOGGER.info("specs: " + + ": " + + this.includeSpecMarkupLambda.resetCounter()); + } + if(this.includeSnippetMarkupLambda != null) { LOGGER.info( - IncludeMarkupLambda.includeMarkupTag + + "snippets: " + ": " + - this.includeMarkupLambda.resetCounter()); + this.includeSnippetMarkupLambda.resetCounter()); } super.processOpenAPI(openAPI); } diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache index 140cdc65042c..adbd13e711c7 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -6,12 +6,14 @@ :toclevels: 3 :source-highlighter: highlightjs :keywords: openapi, rest, {{appName}} +:specDir: {{specDir}} +:snippetDir: {{snippetDir}} [abstract] .Abstract {{{appDescription}}} -{{#includemarkup}}stubs/empty.adoc{{/includemarkup}} +{{#specinclude}}stubs/empty.adoc{{/specinclude}} == Endpoints @@ -33,7 +35,7 @@ {{#notes}} -{{#includemarkup}}{{baseName}}/{{nickname}}/operation-spec.adoc{{/includemarkup}} +{{#specinclude}}{{baseName}}/{{nickname}}/operation-spec.adoc{{/specinclude}} ===== Description @@ -72,15 +74,15 @@ | {{code}} | {{message}} -| {{#dataType}} <<{{dataType}}>>{{/dataType}} +| {{^simpleType}}{{dataType}}[<<{{baseType}}>>]{{/simpleType}} {{#simpleType}}<<{{dataType}}>>{{/simpleType}} {{/responses}} |=== ===== Samples -{{#includemarkup}}{{baseName}}/{{nickname}}/http-request.adoc{{/includemarkup}} -{{#includemarkup}}{{baseName}}/{{nickname}}/http-response.adoc{{/includemarkup}} +{{#snippetinclude}}{{baseName}}/{{nickname}}/{{httpMethod}}/http-request.adoc{{/snippetinclude}} +{{#snippetinclude}}{{baseName}}/{{nickname}}/{{httpMethod}}/http-response.adoc{{/snippetinclude}} {{/operation}} {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache index 7a6ccd9fbd3e..d1b13074c392 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache @@ -16,10 +16,10 @@ {{#vars}} | {{name}} -| {{^required}}X{{/required}} +| {{#required}}X{{/required}} | {{dataType}} {{#isContainer}} of <<{{complexType}}>>{{/isContainer}} | {{description}} -| {{{dataFormat}}} {{#isEnum}}Enum: {{#_enum}}{{this}},{{/_enum}}{{/isEnum}} +| {{{dataFormat}}} {{#isEnum}}Enum: _ {{#_enum}}{{this}}, {{/_enum}}{{/isEnum}} _ {{/vars}} |=== diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java new file mode 100644 index 000000000000..e7bbb8cf2694 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java @@ -0,0 +1,112 @@ +package org.openapitools.codegen.asciidoc; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.commons.io.FileUtils; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.MockDefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.languages.AsciidocDocumentationCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +import io.swagger.v3.oas.models.OpenAPI; + +public class AsciidocGeneratorTest { + + + @Test + public void testSpecSchema() throws Exception { + final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/ping.yaml"); + + AsciidocDocumentationCodegen codeGen = new AsciidocDocumentationCodegen(); + codeGen.preprocessOpenAPI(openAPI); + + Assert.assertEquals(openAPI.getInfo().getTitle(), "ping test"); + } + + @Test + public void testGenerateMarkupFileWithAsciidocGenerator() throws Exception { + + File output = Files.createTempDirectory("test").toFile(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("asciidoc") + .setInputSpec("src/test/resources/3_0/ping.yaml") + .setOutputDir(output.getAbsolutePath()) + .addAdditionalProperty("snippetDir", "MY-SNIPPET-DIR") + .addAdditionalProperty("specDir", "MY-SPEC-DIR"); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + MockDefaultGenerator generator = new MockDefaultGenerator(); + generator.opts(clientOptInput).generate(); + + Map generatedFiles = generator.getFiles(); + TestUtils.ensureContainsFile(generatedFiles, output, "index.adoc"); + } + + @Test + public void testGenerateAsciidocMarkupContent() throws Exception { + final File output = Files.createTempDirectory("test").toFile(); + output.mkdirs(); + output.deleteOnExit(); + + final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/ping.yaml"); + CodegenConfig codegenConfig = new AsciidocDocumentationCodegen(); + codegenConfig.setOutputDir(output.getAbsolutePath()); + ClientOptInput clientOptInput = new ClientOptInput().openAPI(openAPI).config(codegenConfig); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + boolean markupFileGenerated = false; + for (File file : files) { + if (file.getName().equals("index.adoc")) { + markupFileGenerated = true; + String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); + // check on some basic asciidoc markup content + Assert.assertTrue(markupContent.contains("= ping test"), "expected = header in: " + markupContent.substring(0, 50)); + Assert.assertTrue(markupContent.contains(":toc: "), "expected = :toc: " + markupContent.substring(0, 50)); + } + } + Assert.assertTrue(markupFileGenerated, "Default api file is not generated!"); + } + + + @Test + public void testAdditionalDirectoriesGeneratoreHeaderAttributes() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + + Map props = new TreeMap(); + props.put("specDir", "spec"); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("asciidoc") + .setInputSpec("src/test/resources/3_0/ping.yaml") + .setOutputDir(output.getAbsolutePath()) + .addAdditionalProperty("specDir", "SPEC-DIR") + .addAdditionalProperty("snippetDir", "MY/SNIPPET/DIR"); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + boolean markupFileGenerated = false; + for (File file : files) { + if (file.getName().equals("index.adoc")) { + markupFileGenerated = true; + String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); + Assert.assertTrue(markupContent.contains(":specDir: SPEC-DIR"), "expected :specDir: in: " + markupContent.substring(0, 250)); + Assert.assertTrue(markupContent.contains(":snippetDir: MY/SNIPPET/DIR"), "expected :snippetDir: in: " + markupContent.substring(0, 250)); + } + } + Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!"); + + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java new file mode 100644 index 000000000000..035e113efeaf --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java @@ -0,0 +1,46 @@ +package org.openapitools.codegen.asciidoc; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +import org.mockito.MockitoAnnotations; +import org.openapitools.codegen.languages.AsciidocDocumentationCodegen; +import org.openapitools.codegen.templating.mustache.LambdaTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import org.testng.Assert; + +public class IncludeMarkupFilterTest extends LambdaTest { + + @BeforeMethod + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testMarkupFilterDoesNotIncludeMissingFile() { + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + final Map ctx = context("specinclude", generator.new IncludeMarkupLambda("DOES_NOT_EXIST")); + + final String result = execute("{{#specinclude}}not.an.existing.file.adoc{{/specinclude}}", ctx); + Assert.assertTrue(result.contains("// markup not included, not found"), "unexpected filtered " + result); + } + + @Test + public void testMarkupIncludesFoundFileOk() throws IOException { + + File tempFile = File.createTempFile("IncludeMarkupFilterTestDummyfile", "-adoc"); + tempFile.deleteOnExit(); + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + final Map ctx = context("snippetinclude", generator.new IncludeMarkupLambda(tempFile.getParent())); + + final String result = execute("{{#snippetinclude}}" + tempFile.getName() + "{{/snippetinclude}}", ctx); + Assert.assertTrue(result.contains("include::"), "unexpected filtered: " + result); + Assert.assertTrue(result.contains(tempFile.getName()), "unexpected filtered: " + result); + } + +} From d938eca9b14425251eb10ae0c09200a2d37ba6aa Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Fri, 30 Aug 2019 00:29:32 +0200 Subject: [PATCH 04/14] asciidoc petstore sample --- bin/asciidoc-documentation-petstore.sh | 2 +- .../asciidoc-documentation-petstore.bat | 2 +- .../asciidoc/.openapi-generator-ignore | 23 + .../asciidoc/.openapi-generator/VERSION | 1 + samples/documentation/asciidoc/index.adoc | 1659 +++++++++++++++++ 5 files changed, 1685 insertions(+), 2 deletions(-) create mode 100644 samples/documentation/asciidoc/.openapi-generator-ignore create mode 100644 samples/documentation/asciidoc/.openapi-generator/VERSION create mode 100644 samples/documentation/asciidoc/index.adoc diff --git a/bin/asciidoc-documentation-petstore.sh b/bin/asciidoc-documentation-petstore.sh index fa0d403a3d8a..2d3d4adb40a4 100644 --- a/bin/asciidoc-documentation-petstore.sh +++ b/bin/asciidoc-documentation-petstore.sh @@ -26,6 +26,6 @@ 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 -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g asciidoc -o samples/documentation/petstore/asciidoc" +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} diff --git a/bin/windows/asciidoc-documentation-petstore.bat b/bin/windows/asciidoc-documentation-petstore.bat index b930e5b05de9..1cf9fddb696d 100644 --- a/bin/windows/asciidoc-documentation-petstore.bat +++ b/bin/windows/asciidoc-documentation-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) 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\petstore\asciidoc +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% diff --git a/samples/documentation/asciidoc/.openapi-generator-ignore b/samples/documentation/asciidoc/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/documentation/asciidoc/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/documentation/asciidoc/.openapi-generator/VERSION b/samples/documentation/asciidoc/.openapi-generator/VERSION new file mode 100644 index 000000000000..717311e32e3c --- /dev/null +++ b/samples/documentation/asciidoc/.openapi-generator/VERSION @@ -0,0 +1 @@ +unset \ No newline at end of file diff --git a/samples/documentation/asciidoc/index.adoc b/samples/documentation/asciidoc/index.adoc new file mode 100644 index 000000000000..e90df86635df --- /dev/null +++ b/samples/documentation/asciidoc/index.adoc @@ -0,0 +1,1659 @@ += OpenAPI Petstore +team@openapitools.org +1.0.0 +:toc: left +:numbered: +:toclevels: 3 +:source-highlighter: highlightjs +:keywords: openapi, rest, OpenAPI Petstore +:specDir: modules\openapi-generator\src\main\resources\asciidoc-documentation +:snippetDir: . + +[abstract] +.Abstract +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + + +include::stubs/empty.adoc[] + + +== Endpoints + + +[.Pet] +=== Pet + + +[.addPet] +==== addPet + +`POST /pet` + +Add a new pet to the store + + +===== Parameters + + +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| body +| Pet object that needs to be added to the store <> +| X +| +| + + +|=== + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 405 +| Invalid input +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/addPet/POST/http-request.adoc[] + + +// markup not included, not found: include::Pet/addPet/POST/http-response.adoc[] + + + +[.deletePet] +==== deletePet + +`DELETE /pet/{petId}` + +Deletes a pet + + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| petId +| Pet id to delete +| X +| null +| + + +|=== + + +====== Header Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| apiKey +| +| - +| null +| + + +|=== + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 400 +| Invalid pet value +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/deletePet/DELETE/http-request.adoc[] + + +// markup not included, not found: include::Pet/deletePet/DELETE/http-response.adoc[] + + + +[.findPetsByStatus] +==== findPetsByStatus + +`GET /pet/findByStatus` + +Finds Pets by status + + + +// markup not included, not found: include::Pet/findPetsByStatus/operation-spec.adoc[] + + +===== Description + +Multiple status values can be provided with comma separated strings + +===== Parameters + + + + +====== Query Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| status +| Status values that need to be considered for filter <> +| X +| null +| + + +|=== + + +===== Return Type + +array[<>] + + +===== Content Type + +* application/xml +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| List[<>] + + +| 400 +| Invalid status value +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/findPetsByStatus/GET/http-request.adoc[] + + +// markup not included, not found: include::Pet/findPetsByStatus/GET/http-response.adoc[] + + + +[.findPetsByTags] +==== findPetsByTags + +`GET /pet/findByTags` + +Finds Pets by tags + + + +// markup not included, not found: include::Pet/findPetsByTags/operation-spec.adoc[] + + +===== Description + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +===== Parameters + + + + +====== Query Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| tags +| Tags to filter by <> +| X +| null +| + + +|=== + + +===== Return Type + +array[<>] + + +===== Content Type + +* application/xml +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| List[<>] + + +| 400 +| Invalid tag value +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/findPetsByTags/GET/http-request.adoc[] + + +// markup not included, not found: include::Pet/findPetsByTags/GET/http-response.adoc[] + + + +[.getPetById] +==== getPetById + +`GET /pet/{petId}` + +Find pet by ID + + + +// markup not included, not found: include::Pet/getPetById/operation-spec.adoc[] + + +===== Description + +Returns a single pet + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| petId +| ID of pet to return +| X +| null +| + + +|=== + + + + + +===== Return Type + +<> + + +===== Content Type + +* application/xml +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| <> + + +| 400 +| Invalid ID supplied +| <<>> + + +| 404 +| Pet not found +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/getPetById/GET/http-request.adoc[] + + +// markup not included, not found: include::Pet/getPetById/GET/http-response.adoc[] + + + +[.updatePet] +==== updatePet + +`PUT /pet` + +Update an existing pet + + +===== Parameters + + +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| body +| Pet object that needs to be added to the store <> +| X +| +| + + +|=== + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 400 +| Invalid ID supplied +| <<>> + + +| 404 +| Pet not found +| <<>> + + +| 405 +| Validation exception +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/updatePet/PUT/http-request.adoc[] + + +// markup not included, not found: include::Pet/updatePet/PUT/http-response.adoc[] + + + +[.updatePetWithForm] +==== updatePetWithForm + +`POST /pet/{petId}` + +Updates a pet in the store with form data + + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| petId +| ID of pet that needs to be updated +| X +| null +| + + +|=== + + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 405 +| Invalid input +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/updatePetWithForm/POST/http-request.adoc[] + + +// markup not included, not found: include::Pet/updatePetWithForm/POST/http-response.adoc[] + + + +[.uploadFile] +==== uploadFile + +`POST /pet/{petId}/uploadImage` + +uploads an image + + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| petId +| ID of pet to update +| X +| null +| + + +|=== + + + + + +===== Return Type + +<> + + +===== Content Type + +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| <> + +|=== + +===== Samples + + +// markup not included, not found: include::Pet/uploadFile/POST/http-request.adoc[] + + +// markup not included, not found: include::Pet/uploadFile/POST/http-response.adoc[] + + + +[.Store] +=== Store + + +[.deleteOrder] +==== deleteOrder + +`DELETE /store/order/{orderId}` + +Delete purchase order by ID + + + +// markup not included, not found: include::Store/deleteOrder/operation-spec.adoc[] + + +===== Description + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| orderId +| ID of the order that needs to be deleted +| X +| null +| + + +|=== + + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 400 +| Invalid ID supplied +| <<>> + + +| 404 +| Order not found +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Store/deleteOrder/DELETE/http-request.adoc[] + + +// markup not included, not found: include::Store/deleteOrder/DELETE/http-response.adoc[] + + + +[.getInventory] +==== getInventory + +`GET /store/inventory` + +Returns pet inventories by status + + + +// markup not included, not found: include::Store/getInventory/operation-spec.adoc[] + + +===== Description + +Returns a map of status codes to quantities + +===== Parameters + + + + + + +===== Return Type + + +<> + + +===== Content Type + +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| Map[<>] + +|=== + +===== Samples + + +// markup not included, not found: include::Store/getInventory/GET/http-request.adoc[] + + +// markup not included, not found: include::Store/getInventory/GET/http-response.adoc[] + + + +[.getOrderById] +==== getOrderById + +`GET /store/order/{orderId}` + +Find purchase order by ID + + + +// markup not included, not found: include::Store/getOrderById/operation-spec.adoc[] + + +===== Description + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| orderId +| ID of pet that needs to be fetched +| X +| null +| + + +|=== + + + + + +===== Return Type + +<> + + +===== Content Type + +* application/xml +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| <> + + +| 400 +| Invalid ID supplied +| <<>> + + +| 404 +| Order not found +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Store/getOrderById/GET/http-request.adoc[] + + +// markup not included, not found: include::Store/getOrderById/GET/http-response.adoc[] + + + +[.placeOrder] +==== placeOrder + +`POST /store/order` + +Place an order for a pet + + +===== Parameters + + +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| body +| order placed for purchasing the pet <> +| X +| +| + + +|=== + + + + +===== Return Type + +<> + + +===== Content Type + +* application/xml +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| <> + + +| 400 +| Invalid Order +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::Store/placeOrder/POST/http-request.adoc[] + + +// markup not included, not found: include::Store/placeOrder/POST/http-response.adoc[] + + + +[.User] +=== User + + +[.createUser] +==== createUser + +`POST /user` + +Create user + + + +// markup not included, not found: include::User/createUser/operation-spec.adoc[] + + +===== Description + +This can only be done by the logged in user. + +===== Parameters + + +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| body +| Created user object <> +| X +| +| + + +|=== + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 0 +| successful operation +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/createUser/POST/http-request.adoc[] + + +// markup not included, not found: include::User/createUser/POST/http-response.adoc[] + + + +[.createUsersWithArrayInput] +==== createUsersWithArrayInput + +`POST /user/createWithArray` + +Creates list of users with given input array + + +===== Parameters + + +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| body +| List of user object <> +| X +| +| + + +|=== + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 0 +| successful operation +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/createUsersWithArrayInput/POST/http-request.adoc[] + + +// markup not included, not found: include::User/createUsersWithArrayInput/POST/http-response.adoc[] + + + +[.createUsersWithListInput] +==== createUsersWithListInput + +`POST /user/createWithList` + +Creates list of users with given input array + + +===== Parameters + + +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| body +| List of user object <> +| X +| +| + + +|=== + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 0 +| successful operation +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/createUsersWithListInput/POST/http-request.adoc[] + + +// markup not included, not found: include::User/createUsersWithListInput/POST/http-response.adoc[] + + + +[.deleteUser] +==== deleteUser + +`DELETE /user/{username}` + +Delete user + + + +// markup not included, not found: include::User/deleteUser/operation-spec.adoc[] + + +===== Description + +This can only be done by the logged in user. + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| username +| The name that needs to be deleted +| X +| null +| + + +|=== + + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 400 +| Invalid username supplied +| <<>> + + +| 404 +| User not found +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/deleteUser/DELETE/http-request.adoc[] + + +// markup not included, not found: include::User/deleteUser/DELETE/http-response.adoc[] + + + +[.getUserByName] +==== getUserByName + +`GET /user/{username}` + +Get user by user name + + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| username +| The name that needs to be fetched. Use user1 for testing. +| X +| null +| + + +|=== + + + + + +===== Return Type + +<> + + +===== Content Type + +* application/xml +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| <> + + +| 400 +| Invalid username supplied +| <<>> + + +| 404 +| User not found +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/getUserByName/GET/http-request.adoc[] + + +// markup not included, not found: include::User/getUserByName/GET/http-response.adoc[] + + + +[.loginUser] +==== loginUser + +`GET /user/login` + +Logs user into the system + + +===== Parameters + + + + +====== Query Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| username +| The user name for login +| X +| null +| + + +| password +| The password for login in clear text +| X +| null +| + + +|=== + + +===== Return Type + + +<> + + +===== Content Type + +* application/xml +* application/json + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 200 +| successful operation +| <> + + +| 400 +| Invalid username/password supplied +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/loginUser/GET/http-request.adoc[] + + +// markup not included, not found: include::User/loginUser/GET/http-response.adoc[] + + + +[.logoutUser] +==== logoutUser + +`GET /user/logout` + +Logs out current logged in user session + + +===== Parameters + + + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 0 +| successful operation +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/logoutUser/GET/http-request.adoc[] + + +// markup not included, not found: include::User/logoutUser/GET/http-response.adoc[] + + + +[.updateUser] +==== updateUser + +`PUT /user/{username}` + +Updated user + + + +// markup not included, not found: include::User/updateUser/operation-spec.adoc[] + + +===== Description + +This can only be done by the logged in user. + +===== Parameters + +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| username +| name that need to be deleted +| X +| null +| + + +|=== + +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +| body +| Updated user object <> +| X +| +| + + +|=== + + + + +===== Return Type + + + +- + + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + + +| 400 +| Invalid user supplied +| <<>> + + +| 404 +| User not found +| <<>> + +|=== + +===== Samples + + +// markup not included, not found: include::User/updateUser/PUT/http-request.adoc[] + + +// markup not included, not found: include::User/updateUser/PUT/http-response.adoc[] + + + +[#models] +== Models + + +[#ApiResponse] +==== _ApiResponse_ An uploaded response + +Describes the result of uploading an image resource + +[.fields-ApiResponse] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +| code +| +| Integer +| +| int32 _ + +| type +| +| String +| +| _ + +| message +| +| String +| +| _ + +|=== + + +[#Category] +==== _Category_ Pet category + +A category for a pet + +[.fields-Category] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +| id +| +| Long +| +| int64 _ + +| name +| +| String +| +| _ + +|=== + + +[#Order] +==== _Order_ Pet Order + +An order for a pets from the pet store + +[.fields-Order] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +| id +| +| Long +| +| int64 _ + +| petId +| +| Long +| +| int64 _ + +| quantity +| +| Integer +| +| int32 _ + +| shipDate +| +| Date +| +| date-time _ + +| status +| +| String +| Order Status +| Enum: _ placed, approved, delivered, _ + +| complete +| +| Boolean +| +| _ + +|=== + + +[#Pet] +==== _Pet_ a Pet + +A pet for sale in the pet store + +[.fields-Pet] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +| id +| +| Long +| +| int64 _ + +| category +| +| Category +| +| _ + +| name +| X +| String +| +| _ + +| photoUrls +| X +| List of <> +| +| _ + +| tags +| +| List of <> +| +| _ + +| status +| +| String +| pet status in the store +| Enum: _ available, pending, sold, _ + +|=== + + +[#Tag] +==== _Tag_ Pet Tag + +A tag for a pet + +[.fields-Tag] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +| id +| +| Long +| +| int64 _ + +| name +| +| String +| +| _ + +|=== + + +[#User] +==== _User_ a User + +A User who is purchasing from the pet store + +[.fields-User] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +| id +| +| Long +| +| int64 _ + +| username +| +| String +| +| _ + +| firstName +| +| String +| +| _ + +| lastName +| +| String +| +| _ + +| email +| +| String +| +| _ + +| password +| +| String +| +| _ + +| phone +| +| String +| +| _ + +| userStatus +| +| Integer +| User Status +| int32 _ + +|=== + + From 438ed43ad9c608e8651f786e504f79bd6b0e1ba2 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Fri, 30 Aug 2019 00:45:01 +0200 Subject: [PATCH 05/14] add asciidoc generator to readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2bbd07321ea3..b9dc59fcdcb9 100644 --- a/README.md +++ b/README.md @@ -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** From f032332df38614953b73de52460c56c92e9f3046 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Fri, 30 Aug 2019 22:33:24 +0200 Subject: [PATCH 06/14] test asciidoc generator for all include files with own json spec. --- .../AsciidocDocumentationCodegen.java | 2 +- .../asciidoc-documentation/index.mustache | 23 ++++-- .../asciidoc/AsciidocGeneratorTest.java | 12 +-- .../asciidoc/AsciidocSampleGeneratorTest.java | 76 +++++++++++++++++++ .../asciidoc/IncludeMarkupFilterTest.java | 2 +- .../test/resources/3_0/asciidoc/api-docs.json | 1 + .../rest/project/GET/curl-request.adoc | 4 + .../rest/project/GET/http-request.adoc | 6 ++ .../rest/project/GET/http-response.adoc | 11 +++ .../rest/project/GET/httpie-request.adoc | 4 + .../rest/project/GET/request-body.adoc | 4 + .../rest/project/GET/response-body.adoc | 4 + .../rest/project/GET/implementation.adoc | 2 + .../asciidoc/specs/rest/project/GET/spec.adoc | 7 ++ 14 files changed, 142 insertions(+), 16 deletions(-) create mode 100644 modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/api-docs.json create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/curl-request.adoc create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-request.adoc create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-response.adoc create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/httpie-request.adoc create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/request-body.adoc create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/response-body.adoc create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/implementation.adoc create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/spec.adoc diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index f605962c95dc..f39282132182 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -62,7 +62,7 @@ public void execute(final Template.Fragment frag, final Writer out) throws IOExc out.write("\ninclude::" + relativeFileName + "[]\n"); } else { LOGGER.debug(++notFoundCount + ". file not found, skip include for: " + relativeFileName); - out.write("\n// markup not included, not found: include::" + relativeFileName + "[]\n"); + out.write("\n// markup not found, no include ::" + relativeFileName + "[]\n"); } } } diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache index adbd13e711c7..7c7332d94d52 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -8,12 +8,15 @@ :keywords: openapi, rest, {{appName}} :specDir: {{specDir}} :snippetDir: {{snippetDir}} +:generator-template: v1 2018-08-30 +:info-url: {{infoUrl}} +:app-name: {{appName}} [abstract] .Abstract {{{appDescription}}} -{{#specinclude}}stubs/empty.adoc{{/specinclude}} +{{#specinclude}}intro.adoc{{/specinclude}} == Endpoints @@ -33,14 +36,12 @@ {{{summary}}} -{{#notes}} - -{{#specinclude}}{{baseName}}/{{nickname}}/operation-spec.adoc{{/specinclude}} - ===== Description {{{notes}}} -{{/notes}} + +{{#specinclude}}{{path}}/{{httpMethod}}/spec.adoc{{/specinclude}} + {{> params}} @@ -81,8 +82,14 @@ ===== Samples -{{#snippetinclude}}{{baseName}}/{{nickname}}/{{httpMethod}}/http-request.adoc{{/snippetinclude}} -{{#snippetinclude}}{{baseName}}/{{nickname}}/{{httpMethod}}/http-response.adoc{{/snippetinclude}} +{{#snippetinclude}}{{path}}/{{httpMethod}}/http-request.adoc{{/snippetinclude}} +{{#snippetinclude}}{{path}}/{{httpMethod}}/http-response.adoc{{/snippetinclude}} + +ifdef::internal-generation[] +===== Implementation +{{#specinclude}}{{path}}/{{httpMethod}}/implementation.adoc{{/specinclude}} + +endif::internal-generation[] {{/operation}} {{/operations}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java index e7bbb8cf2694..0961e4f76fd9 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java @@ -20,8 +20,8 @@ import io.swagger.v3.oas.models.OpenAPI; -public class AsciidocGeneratorTest { - +/** check against ping.yaml spec. */ +public class AsciidocGeneratorTest { @Test public void testSpecSchema() throws Exception { @@ -42,8 +42,8 @@ public void testGenerateMarkupFileWithAsciidocGenerator() throws Exception { .setGeneratorName("asciidoc") .setInputSpec("src/test/resources/3_0/ping.yaml") .setOutputDir(output.getAbsolutePath()) - .addAdditionalProperty("snippetDir", "MY-SNIPPET-DIR") - .addAdditionalProperty("specDir", "MY-SPEC-DIR"); + .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY-SNIPPET-DIR") + .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, "MY-SPEC-DIR"); final ClientOptInput clientOptInput = configurator.toClientOptInput(); MockDefaultGenerator generator = new MockDefaultGenerator(); @@ -91,8 +91,8 @@ public void testAdditionalDirectoriesGeneratoreHeaderAttributes() throws Excepti .setGeneratorName("asciidoc") .setInputSpec("src/test/resources/3_0/ping.yaml") .setOutputDir(output.getAbsolutePath()) - .addAdditionalProperty("specDir", "SPEC-DIR") - .addAdditionalProperty("snippetDir", "MY/SNIPPET/DIR"); + .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, "SPEC-DIR") + .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY/SNIPPET/DIR"); DefaultGenerator generator = new DefaultGenerator(); List files = generator.opts(configurator.toClientOptInput()).generate(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java new file mode 100644 index 000000000000..350a89851516 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java @@ -0,0 +1,76 @@ +package org.openapitools.codegen.asciidoc; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.List; + +import org.apache.commons.io.FileUtils; + +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.languages.AsciidocDocumentationCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class AsciidocSampleGeneratorTest { + + /** ensure api-docs.json includes sample and spec files into markup. */ + @Test + public void testSampleMarkupGenerationFromJsonWithSpecsAndSamples() throws Exception { + + File output = Files.createTempDirectory("test-openapi-asciidoc-markup").toFile(); + + File specDir = new File("src/test/resources/3_0/asciidoc/specs"); + File snippetDir = new File("src/test/resources/3_0/asciidoc/generated-snippets"); + + Assert.assertTrue(specDir.exists(), "test cancel, not specdDir found to use." + specDir.getPath()); + Assert.assertTrue(snippetDir.exists(), "test cancel, not snippedDir found to use." + snippetDir.getPath()); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("asciidoc") + .setInputSpec("src/test/resources/3_0/asciidoc/api-docs.json") + .setOutputDir(output.getAbsolutePath()) + .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, specDir.toString()) + .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, snippetDir.toString()); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator + .opts(configurator.toClientOptInput()) + .generate(); + + boolean markupFileGenerated = false; + + for (File file : files) { + if (file.getName().equals("index.adoc")) { + markupFileGenerated = true; + String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); + + // include correct values from cli. + Assert.assertTrue(markupContent.contains(":specDir: " + specDir.toString()), + "expected :specDir: in: " + markupContent.substring(0, 350)); + Assert.assertTrue(markupContent.contains(":snippetDir: " + snippetDir.toString()), + "expected :snippetDir: in: " + markupContent.substring(0, 350)); + + // include correct markup from separate directories + Assert.assertTrue(markupContent.contains("include::/rest/project/GET/spec.adoc[]"), + "expected project spec.adoc to be included in " + file.getAbsolutePath()); + + Assert.assertTrue(markupContent.contains("include::/rest/project/GET/implementation.adoc[]"), + "expected project implementation.adoc to be included in " + file.getAbsolutePath()); + + Assert.assertTrue(markupContent.contains("include::/rest/project/GET/http-request.adoc[]"), + "expected project http-request.adoc to be included in " + file.getAbsolutePath()); + + Assert.assertTrue(markupContent.contains("include::/rest/project/GET/http-response.adoc[]"), + "expected project http-response.adoc to be included in " + file.getAbsolutePath()); + + // extract correct value from json + Assert.assertTrue(markupContent.contains("= time@work rest api"), "missing main header for api spec from json: " + markupContent.substring(0, 100)); + } + } + Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!"); + + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java index 035e113efeaf..fb5470c75bfd 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java @@ -26,7 +26,7 @@ public void testMarkupFilterDoesNotIncludeMissingFile() { final Map ctx = context("specinclude", generator.new IncludeMarkupLambda("DOES_NOT_EXIST")); final String result = execute("{{#specinclude}}not.an.existing.file.adoc{{/specinclude}}", ctx); - Assert.assertTrue(result.contains("// markup not included, not found"), "unexpected filtered " + result); + Assert.assertTrue(result.contains("// markup not found, no include ::not.an.existing.file.adoc[]"), "unexpected filtered " + result); } @Test diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/api-docs.json b/modules/openapi-generator/src/test/resources/3_0/asciidoc/api-docs.json new file mode 100644 index 000000000000..9a19658cc2ce --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/api-docs.json @@ -0,0 +1 @@ +{"openapi":"3.0.1","info":{"title":"time@work rest api","description":"internal rest api, used by time@work angular client","contact":{"name":"man@home","url":"https://gitlab.com/spare-time-demos/timeatwork","email":"man.at.home@do-not-use-this-mail.com"},"license":{"name":"Apache 2.0","url":"http://foo.bar"},"version":"0.1"},"externalDocs":{"description":"specs","url":"https://gitlab.com/spare-time-demos/timeatwork/tree/master/docs/src/main/docs/features"},"servers":[{"url":"http://localhost:8080","description":"Generated server url"}],"tags":[{"name":"ui-admin","description":"ui: admin and team lead api calls"},{"name":"ui-user","description":"ui: user api calls"},{"name":"admin","description":"admin api, internal use"},{"name":"graphql","description":"external graphql api (spike only)"}],"paths":{"/rest/admin/job/usersync":{"get":{"tags":["admin"],"summary":"start background job: usersync","operationId":"startuserSync","responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"string"}}}}}}},"/rest/project":{"get":{"tags":["ui-admin"],"summary":"retrieving all visible projects for current user.","operationId":"getProjects","responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Project"}}}}}}},"post":{"tags":["ui-admin"],"summary":"create a new project.","operationId":"createProject","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Project"}}}},"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Project"}}}}}}},"/rest/project/{projectId}":{"get":{"tags":["ui-admin"],"summary":"retrieving a specific visible projects for current user.","operationId":"getProject","parameters":[{"name":"projectId","in":"path","description":"unique project id to find","required":true,"schema":{"type":"integer","format":"int64"},"example":"0185"}],"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Project"}}}}}},"put":{"tags":["ui-admin"],"summary":"change an existing project.","operationId":"changeProject","parameters":[{"name":"projectId","in":"path","description":"unique project id to change","required":true,"schema":{"type":"integer","format":"int64"},"example":"0815"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Project"}}}},"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Project"}}}}}}},"/rest/project/{projectId}/task":{"get":{"tags":["ui-admin"],"summary":"retrieving tasks for a specific project.","operationId":"getProjectTasks","parameters":[{"name":"projectId","in":"path","description":"project id to find tasks for","required":true,"schema":{"type":"integer","format":"int64"},"example":"0815"}],"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Task"}}}}}}},"post":{"tags":["ui-admin"],"summary":"create a new task for an existing project","operationId":"createTaskForProject","parameters":[{"name":"projectId","in":"path","description":"project id for task to change","required":true,"schema":{"type":"integer","format":"int64"},"example":"0815"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Task"}}}},"responses":{"200":{"description":"task created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Task"}}}},"404":{"description":"project not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResponseStatusException"}}}}}}},"/rest/task/{taskId}":{"get":{"tags":["ui-admin"],"summary":"retrieving a specific task.","operationId":"getTask","parameters":[{"name":"taskId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"$ref":"#/components/schemas/Task"}}}}}},"put":{"tags":["ui-admin"],"summary":"change an existing task.","operationId":"changeTask","parameters":[{"name":"taskId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Task"}}}},"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Task"}}}}}},"delete":{"tags":["ui-admin"],"summary":"delete an existing task.","operationId":"deleteTask","parameters":[{"name":"taskId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"integer","format":"int64"}}}}}}},"/rest/task/{taskId}/assignment":{"get":{"tags":["ui-admin"],"summary":"retrieving team member assignments for a specific task.","operationId":"getTaskAssignments","parameters":[{"name":"taskId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/TaskAssignment"}}}}}}},"post":{"tags":["ui-admin"],"summary":"add a new assignment to an existing task.","operationId":"createAssignment","parameters":[{"name":"taskId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskAssignment"}}}},"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskAssignment"}}}}}}},"/rest/task/{taskId}/assignment/{id}":{"put":{"tags":["ui-admin"],"summary":"change from/until of given assignment","operationId":"changeAssignment","parameters":[{"name":"taskId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"id","in":"path","required":true,"schema":{"type":"integer","format":"int64"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskAssignment"}}}},"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskAssignment"}}}}}}},"/rest/task/{taskId}/assignment/{assignmentId}":{"delete":{"tags":["ui-admin"],"summary":"delete an existing assignment from task.","operationId":"deleteAssignment","parameters":[{"name":"taskId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"assignmentId","in":"path","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"integer","format":"int64"}}}}}}},"/rest/teammember":{"get":{"tags":["ui-admin","ui-user"],"summary":"retrieving all known users.","operationId":"getTeamMembers","responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/TeamMember"}}}}}}}},"/rest/workweek/{fromIsoDateString}":{"get":{"tags":["ui-user"],"summary":"retrieving work week for given week, date format: /rest/workweek/YYYY-MM-DD.","operationId":"getWorkWeek","parameters":[{"name":"fromIsoDateString","in":"path","description":"date, start of week, format YYYY-MM-DD","required":true,"schema":{"type":"string"},"example":"2019-03-11"}],"responses":{"200":{"description":"default response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkWeek"}}}}}},"put":{"tags":["ui-user"],"summary":"update work done for given week","operationId":"updateWorkWeek","parameters":[{"name":"fromIsoDateString","in":"path","description":"date, start of week, format YYYY-MM-DD","required":true,"schema":{"type":"string"},"example":"2019-03-11"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkWeek"}}}},"responses":{"200":{"description":"default response"}}}},"/graphql":{"get":{"operationId":"graphqlGET","parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string"}},{"name":"operationName","in":"query","required":false,"schema":{"type":"string"}},{"name":"variables","in":"query","required":false,"schema":{"type":"string"}}],"responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"object"}}}}}},"post":{"operationId":"graphqlPOST","requestBody":{"content":{"*/*":{"schema":{"$ref":"#/components/schemas/GraphQLRequestBody"}}}},"responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"object"}}}}}}}},"components":{"schemas":{"Project":{"required":["active","name"],"type":"object","properties":{"id":{"type":"integer","description":"unique project id.","format":"int64","example":815},"name":{"maxLength":100,"minLength":1,"type":"string","description":"unique descriptive name","example":"my unique project name"},"active":{"type":"boolean","description":"is project active for administration by project lead.","example":true},"projectLeads":{"type":"array","description":"project leads (administrator)","items":{"$ref":"#/components/schemas/TeamMember"}}},"description":"tracked project."},"TeamMember":{"required":["name","userId"],"type":"object","properties":{"id":{"type":"integer","description":"unique internal member id","format":"int64","example":4712},"name":{"maxLength":100,"type":"string","description":"unique descriptive name","example":"Tom Teammember"},"userId":{"maxLength":100,"type":"string","description":"unique descriptive name","example":"tlead1"}},"description":"a team member, could be project lead or an member with assigned tasks."},"Task":{"required":["name","project","state"],"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"maxLength":100,"minLength":1,"type":"string","description":"unique descriptive name","example":"first task: do something"},"state":{"type":"string","enum":["planned","active","done"]},"project":{"$ref":"#/components/schemas/Project"}},"description":"a project task to be worked on."},"ResponseStatusException":{"type":"object","properties":{"mostSpecificCause":{"type":"object","properties":{"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"message":{"type":"string"},"suppressed":{"type":"array","items":{"type":"object","properties":{"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"message":{"type":"string"},"localizedMessage":{"type":"string"}}}},"localizedMessage":{"type":"string"}}},"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"status":{"type":"string","enum":["100 CONTINUE","101 SWITCHING_PROTOCOLS","102 PROCESSING","103 CHECKPOINT","200 OK","201 CREATED","202 ACCEPTED","203 NON_AUTHORITATIVE_INFORMATION","204 NO_CONTENT","205 RESET_CONTENT","206 PARTIAL_CONTENT","207 MULTI_STATUS","208 ALREADY_REPORTED","226 IM_USED","300 MULTIPLE_CHOICES","301 MOVED_PERMANENTLY","302 FOUND","302 MOVED_TEMPORARILY","303 SEE_OTHER","304 NOT_MODIFIED","305 USE_PROXY","307 TEMPORARY_REDIRECT","308 PERMANENT_REDIRECT","400 BAD_REQUEST","401 UNAUTHORIZED","402 PAYMENT_REQUIRED","403 FORBIDDEN","404 NOT_FOUND","405 METHOD_NOT_ALLOWED","406 NOT_ACCEPTABLE","407 PROXY_AUTHENTICATION_REQUIRED","408 REQUEST_TIMEOUT","409 CONFLICT","410 GONE","411 LENGTH_REQUIRED","412 PRECONDITION_FAILED","413 PAYLOAD_TOO_LARGE","413 REQUEST_ENTITY_TOO_LARGE","414 URI_TOO_LONG","414 REQUEST_URI_TOO_LONG","415 UNSUPPORTED_MEDIA_TYPE","416 REQUESTED_RANGE_NOT_SATISFIABLE","417 EXPECTATION_FAILED","418 I_AM_A_TEAPOT","419 INSUFFICIENT_SPACE_ON_RESOURCE","420 METHOD_FAILURE","421 DESTINATION_LOCKED","422 UNPROCESSABLE_ENTITY","423 LOCKED","424 FAILED_DEPENDENCY","426 UPGRADE_REQUIRED","428 PRECONDITION_REQUIRED","429 TOO_MANY_REQUESTS","431 REQUEST_HEADER_FIELDS_TOO_LARGE","451 UNAVAILABLE_FOR_LEGAL_REASONS","500 INTERNAL_SERVER_ERROR","501 NOT_IMPLEMENTED","502 BAD_GATEWAY","503 SERVICE_UNAVAILABLE","504 GATEWAY_TIMEOUT","505 HTTP_VERSION_NOT_SUPPORTED","506 VARIANT_ALSO_NEGOTIATES","507 INSUFFICIENT_STORAGE","508 LOOP_DETECTED","509 BANDWIDTH_LIMIT_EXCEEDED","510 NOT_EXTENDED","511 NETWORK_AUTHENTICATION_REQUIRED"]},"reason":{"type":"string"},"message":{"type":"string"},"rootCause":{"type":"object","properties":{"cause":{"type":"object","properties":{"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"message":{"type":"string"},"suppressed":{"type":"array","items":{"type":"object","properties":{"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"message":{"type":"string"},"localizedMessage":{"type":"string"}}}},"localizedMessage":{"type":"string"}}},"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"message":{"type":"string"},"suppressed":{"type":"array","items":{"type":"object","properties":{"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"message":{"type":"string"},"localizedMessage":{"type":"string"}}}},"localizedMessage":{"type":"string"}}},"suppressed":{"type":"array","items":{"type":"object","properties":{"stackTrace":{"type":"array","items":{"type":"object","properties":{"classLoaderName":{"type":"string"},"moduleName":{"type":"string"},"moduleVersion":{"type":"string"},"methodName":{"type":"string"},"fileName":{"type":"string"},"lineNumber":{"type":"integer","format":"int32"},"className":{"type":"string"},"nativeMethod":{"type":"boolean"}}}},"message":{"type":"string"},"localizedMessage":{"type":"string"}}}},"localizedMessage":{"type":"string"}}},"TaskAssignment":{"required":["from","teamMember"],"type":"object","properties":{"id":{"type":"integer","description":"internal unique assignment id","format":"int64","example":-1},"teamMember":{"$ref":"#/components/schemas/TeamMember"},"from":{"type":"string","description":"assignment start date","format":"date"},"until":{"type":"string","description":"optional assignment end date","format":"date"}},"description":"planned assignment of a team member to a given project task."},"TaskWeek":{"type":"object","properties":{"taskId":{"type":"integer","format":"int64"},"taskName":{"type":"string"},"workHours":{"type":"array","items":{"$ref":"#/components/schemas/WorkHoursAssigned"}}},"description":"one week of working hours for a given task."},"WorkHoursAssigned":{"type":"object","properties":{"workHours":{"type":"integer","format":"int64"},"readOnly":{"type":"boolean"}}},"WorkWeek":{"type":"object","properties":{"from":{"type":"string","format":"date"},"until":{"type":"string","format":"date"},"taskWeeks":{"type":"array","items":{"$ref":"#/components/schemas/TaskWeek"}}},"description":"week, holds all work and working assignments."},"GraphQLRequestBody":{"type":"object","properties":{"query":{"type":"string"},"operationName":{"type":"string"},"variables":{"type":"object","additionalProperties":{"type":"object"}}}}},"securitySchemes":{"APIKEY_IN_HEADER":{"type":"apiKey","description":"authentication with APIKEY http header not yet implemented","name":"APIKEY","in":"header"}}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/curl-request.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/curl-request.adoc new file mode 100644 index 000000000000..340a97532bc8 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/curl-request.adoc @@ -0,0 +1,4 @@ +[source,bash] +---- +$ curl 'http://samplehost.timeatwork.manathome.org:8080/rest/project/' -i -X GET +---- \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-request.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-request.adoc new file mode 100644 index 000000000000..aeffcec0116b --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-request.adoc @@ -0,0 +1,6 @@ +[source,http,options="nowrap"] +---- +GET /rest/project/ HTTP/1.1 +Host: samplehost.timeatwork.manathome.org:8080 + +---- \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-response.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-response.adoc new file mode 100644 index 000000000000..15f6735316dd --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/http-response.adoc @@ -0,0 +1,11 @@ +[source,http,options="nowrap"] +---- +HTTP/1.1 200 OK +Vary: Origin +Vary: Access-Control-Request-Method +Vary: Access-Control-Request-Headers +Content-Type: application/json;charset=UTF-8 +Content-Length: 530 + +[{"id":-3,"name":"a third inactive project","active":false,"projectLeads":[{"id":-1,"name":"a first test lead and user","userId":"tlead1"},{"id":-2,"name":"another second lead","userId":"tlead2"}]},{"id":-2,"name":"a second active project","active":true,"projectLeads":[{"id":-1,"name":"a first test lead and user","userId":"tlead1"}]},{"id":-1,"name":"a first active project","active":true,"projectLeads":[{"id":-1,"name":"a first test lead and user","userId":"tlead1"},{"id":-2,"name":"another second lead","userId":"tlead2"}]}] +---- \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/httpie-request.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/httpie-request.adoc new file mode 100644 index 000000000000..55a176514cb5 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/httpie-request.adoc @@ -0,0 +1,4 @@ +[source,bash] +---- +$ http GET 'http://samplehost.timeatwork.manathome.org:8080/rest/project/' +---- \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/request-body.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/request-body.adoc new file mode 100644 index 000000000000..dab5f81d2fba --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/request-body.adoc @@ -0,0 +1,4 @@ +[source,options="nowrap"] +---- + +---- \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/response-body.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/response-body.adoc new file mode 100644 index 000000000000..5383ea167bf8 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/response-body.adoc @@ -0,0 +1,4 @@ +[source,options="nowrap"] +---- +[{"id":-3,"name":"a third inactive project","active":false,"projectLeads":[{"id":-1,"name":"a first test lead and user","userId":"tlead1"},{"id":-2,"name":"another second lead","userId":"tlead2"}]},{"id":-2,"name":"a second active project","active":true,"projectLeads":[{"id":-1,"name":"a first test lead and user","userId":"tlead1"}]},{"id":-1,"name":"a first active project","active":true,"projectLeads":[{"id":-1,"name":"a first test lead and user","userId":"tlead1"},{"id":-2,"name":"another second lead","userId":"tlead2"}]}] +---- \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/implementation.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/implementation.adoc new file mode 100644 index 000000000000..2713f95e67a9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/implementation.adoc @@ -0,0 +1,2 @@ + +// optional, conditionally included implementation notes. \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/spec.adoc b/modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/spec.adoc new file mode 100644 index 000000000000..b916c8d6bc6d --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/specs/rest/project/GET/spec.adoc @@ -0,0 +1,7 @@ +// spec to include + +* all _projects_ visible for the _current user_ are returned +* _projects_ may be active or closed + +USER: project lead, admin + From e9bda85a84abee80ed72d7e08fb1b1399b7829c7 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Tue, 3 Sep 2019 23:43:57 +0200 Subject: [PATCH 07/14] link fillter to link generated test data into asciidoc markup --- .../AsciidocDocumentationCodegen.java | 70 +++++++++++++++++-- .../asciidoc-documentation/index.mustache | 4 +- .../asciidoc/AsciidocGeneratorTest.java | 8 ++- .../asciidoc/AsciidocSampleGeneratorTest.java | 30 +++++--- .../asciidoc/LinkMarkupFilterTest.java | 46 ++++++++++++ .../rest/project/GET/GET.json | 16 +++++ 6 files changed, 155 insertions(+), 19 deletions(-) create mode 100644 modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java create mode 100644 modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/GET.json diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index f39282132182..25a7664e6054 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -32,7 +32,7 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code /** * Lambda emitting an asciidoc "include::filename.adoc[]" if file is found in path. * Use: - *
{{#includeMarkup}}{{name}}/description.adoc{{/includeMarkup}}
+ *
{{#includemarkup}}{{name}}/description.adoc{{/includemarkup}}
*/ public class IncludeMarkupLambda implements Mustache.Lambda { @@ -45,7 +45,7 @@ public IncludeMarkupLambda(final String basePath) { } public String resetCounter( ) { - String msg = "included:" + includeCount + " notFound: " + notFoundCount + " from " + basePath; + String msg = "included: " + includeCount + " notFound: " + notFoundCount + " from " + basePath; includeCount = 0; notFoundCount = 0; return msg; @@ -54,19 +54,63 @@ public String resetCounter( ) { @Override public void execute(final Template.Fragment frag, final Writer out) throws IOException { - final String relativeFileName = frag.execute(); - final Path filePathToInclude = Paths.get(basePath, relativeFileName); + 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.toAbsolutePath().toString()); + 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: " + relativeFileName); + 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: + *
{{#snippetLink}}markup until koma, /{{name}}.json{{/snippetLink}}
+ */ + 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"; @@ -74,12 +118,21 @@ public void execute(final Template.Fragment frag, final Writer out) throws IOExc private IncludeMarkupLambda includeSpecMarkupLambda; private IncludeMarkupLambda includeSnippetMarkupLambda; + private LinkMarkupLambda linkSnippetMarkupLambda; public CodegenType getTag() { return CodegenType.DOCUMENTATION; } - public String getName() { + /** extracted filter value should be relative to be of use as link or include file. */ + public 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"; } @@ -173,6 +226,9 @@ public void processOpts() { this.includeSnippetMarkupLambda = new IncludeMarkupLambda(snippetDir); additionalProperties.put("snippetinclude", this.includeSnippetMarkupLambda ); + + this.linkSnippetMarkupLambda = new LinkMarkupLambda(snippetDir); + additionalProperties.put("snippetlink", this.linkSnippetMarkupLambda ); } @Override diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache index 7c7332d94d52..166938da2a4b 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -8,7 +8,7 @@ :keywords: openapi, rest, {{appName}} :specDir: {{specDir}} :snippetDir: {{snippetDir}} -:generator-template: v1 2018-08-30 +:generator-template: v1 2019-09-03 :info-url: {{infoUrl}} :app-name: {{appName}} @@ -85,6 +85,8 @@ {{#snippetinclude}}{{path}}/{{httpMethod}}/http-request.adoc{{/snippetinclude}} {{#snippetinclude}}{{path}}/{{httpMethod}}/http-response.adoc{{/snippetinclude}} +{{#snippetlink}}* wiremock data, {{path}}/{{httpMethod}}/{{httpMethod}}.json{{/snippetlink}} + ifdef::internal-generation[] ===== Implementation {{#specinclude}}{{path}}/{{httpMethod}}/implementation.adoc{{/specinclude}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java index 0961e4f76fd9..13d6cf0c8782 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java @@ -15,6 +15,8 @@ import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.AsciidocDocumentationCodegen; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; @@ -22,6 +24,8 @@ /** check against ping.yaml spec. */ public class AsciidocGeneratorTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocGeneratorTest.class); @Test public void testSpecSchema() throws Exception { @@ -37,7 +41,7 @@ public void testSpecSchema() throws Exception { public void testGenerateMarkupFileWithAsciidocGenerator() throws Exception { File output = Files.createTempDirectory("test").toFile(); - + final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("asciidoc") .setInputSpec("src/test/resources/3_0/ping.yaml") @@ -84,6 +88,8 @@ public void testGenerateAsciidocMarkupContent() throws Exception { public void testAdditionalDirectoriesGeneratoreHeaderAttributes() throws Exception { File output = Files.createTempDirectory("test").toFile(); + LOGGER.info("test: generating sample markup " + output.getAbsolutePath()); + Map props = new TreeMap(); props.put("specDir", "spec"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java index 350a89851516..4f0449184f7c 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java @@ -3,6 +3,7 @@ import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Paths; import java.util.List; import org.apache.commons.io.FileUtils; @@ -19,10 +20,10 @@ public class AsciidocSampleGeneratorTest { @Test public void testSampleMarkupGenerationFromJsonWithSpecsAndSamples() throws Exception { - File output = Files.createTempDirectory("test-openapi-asciidoc-markup").toFile(); + File outputTempDirectory = Files.createTempDirectory("test-asciidoc-sample-generator.").toFile(); - File specDir = new File("src/test/resources/3_0/asciidoc/specs"); - File snippetDir = new File("src/test/resources/3_0/asciidoc/generated-snippets"); + File specDir = new File("src/test/resources/3_0/asciidoc/specs/"); + File snippetDir = new File("src/test/resources/3_0/asciidoc/generated-snippets/"); Assert.assertTrue(specDir.exists(), "test cancel, not specdDir found to use." + specDir.getPath()); Assert.assertTrue(snippetDir.exists(), "test cancel, not snippedDir found to use." + snippetDir.getPath()); @@ -30,7 +31,7 @@ public void testSampleMarkupGenerationFromJsonWithSpecsAndSamples() throws Excep final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("asciidoc") .setInputSpec("src/test/resources/3_0/asciidoc/api-docs.json") - .setOutputDir(output.getAbsolutePath()) + .setOutputDir(outputTempDirectory.getAbsolutePath()) .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, specDir.toString()) .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, snippetDir.toString()); @@ -52,25 +53,34 @@ public void testSampleMarkupGenerationFromJsonWithSpecsAndSamples() throws Excep Assert.assertTrue(markupContent.contains(":snippetDir: " + snippetDir.toString()), "expected :snippetDir: in: " + markupContent.substring(0, 350)); - // include correct markup from separate directories - Assert.assertTrue(markupContent.contains("include::/rest/project/GET/spec.adoc[]"), + // include correct markup from separate directories, relative links + Assert.assertTrue(markupContent.contains("include::rest/project/GET/spec.adoc[]"), "expected project spec.adoc to be included in " + file.getAbsolutePath()); - Assert.assertTrue(markupContent.contains("include::/rest/project/GET/implementation.adoc[]"), + Assert.assertTrue(markupContent.contains("include::rest/project/GET/implementation.adoc[]"), "expected project implementation.adoc to be included in " + file.getAbsolutePath()); - Assert.assertTrue(markupContent.contains("include::/rest/project/GET/http-request.adoc[]"), + Assert.assertTrue(markupContent.contains("include::rest/project/GET/http-request.adoc[]"), "expected project http-request.adoc to be included in " + file.getAbsolutePath()); - Assert.assertTrue(markupContent.contains("include::/rest/project/GET/http-response.adoc[]"), + Assert.assertTrue(markupContent.contains("include::rest/project/GET/http-response.adoc[]"), "expected project http-response.adoc to be included in " + file.getAbsolutePath()); + + + Assert.assertTrue(markupContent.contains("link:rest/project/GET/GET.json["), + "expected link: not found in file: " + file.getAbsoluteFile()); + // extract correct value from json Assert.assertTrue(markupContent.contains("= time@work rest api"), "missing main header for api spec from json: " + markupContent.substring(0, 100)); } + Files.deleteIfExists(Paths.get(file.getAbsolutePath())); } + Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!"); - + + Files.deleteIfExists(Paths.get(outputTempDirectory.getAbsolutePath(), ".openapi-generator")); + Files.deleteIfExists(Paths.get(outputTempDirectory.getAbsolutePath())); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java new file mode 100644 index 000000000000..7be543ff0a90 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java @@ -0,0 +1,46 @@ +package org.openapitools.codegen.asciidoc; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +import org.mockito.MockitoAnnotations; +import org.openapitools.codegen.languages.AsciidocDocumentationCodegen; +import org.openapitools.codegen.templating.mustache.LambdaTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import org.testng.Assert; + +public class LinkMarkupFilterTest extends LambdaTest { + + @BeforeMethod + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testMarkupFilterDoesNotLinkMissingFile() { + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + final Map ctx = context("link", generator.new LinkMarkupLambda("DOES_NOT_EXIST")); + + final String result = execute("{{#link}}not.an.existing.file.adoc{{/link}}", ctx); + Assert.assertTrue(result.contains("// markup not found, not linked"), "unexpected filtered: " + result); + } + + @Test + public void testMarkupLinkFoundFileOk() throws IOException { + + File tempFile = File.createTempFile("LinkMarkupFilterTestDummyfile", ".adoc"); + tempFile.deleteOnExit(); + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + final Map ctx = context("linkIntoMarkup", generator.new LinkMarkupLambda(tempFile.getParent())); + + final String result = execute("{{#linkIntoMarkup}}my link text, " + tempFile.getName() + "{{/linkIntoMarkup}}", ctx); + Assert.assertTrue(result.contains("link:"), "unexpected filtered: " + result); + Assert.assertTrue(result.contains(tempFile.getName() + "[my link text]"), "unexpected filtered: " + result); + } + +} diff --git a/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/GET.json b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/GET.json new file mode 100644 index 000000000000..0538e0fb212c --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/asciidoc/generated-snippets/rest/project/GET/GET.json @@ -0,0 +1,16 @@ +{ + "id" : "238a47e3-2533-41a4-ac62-f6654c936ada", + "request" : { + "url" : "/rest/project/", + "method" : "GET" + }, + "response" : { + "status" : 200, + "body" : "[{\"id\":-3,\"name\":\"a third inactive project\",\"active\":false,\"projectLeads\":[{\"id\":-2,\"name\":\"another second lead\",\"userId\":\"tlead2\"},{\"id\":-1,\"name\":\"a first test lead and user\",\"userId\":\"tlead1\"}]},{\"id\":-2,\"name\":\"a second active project\",\"active\":true,\"projectLeads\":[{\"id\":-1,\"name\":\"a first test lead and user\",\"userId\":\"tlead1\"}]},{\"id\":-1,\"name\":\"a first active project\",\"active\":true,\"projectLeads\":[{\"id\":-2,\"name\":\"another second lead\",\"userId\":\"tlead2\"},{\"id\":-1,\"name\":\"a first test lead and user\",\"userId\":\"tlead1\"}]}]", + "headers" : { + "Vary" : [ "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers" ], + "Content-Type" : "application/json" + } + }, + "uuid" : "238a47e3-2533-41a4-ac62-f6654c936ada" +} \ No newline at end of file From 6cb7ee9042d7949a42a087bbc2d02509139d8f9d Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Wed, 4 Sep 2019 02:28:20 +0200 Subject: [PATCH 08/14] fix and cleanup names asciidoc tests. --- .../codegen/asciidoc/AsciidocGeneratorTest.java | 8 ++++---- .../codegen/asciidoc/AsciidocSampleGeneratorTest.java | 2 +- .../codegen/asciidoc/IncludeMarkupFilterTest.java | 4 ++-- .../codegen/asciidoc/LinkMarkupFilterTest.java | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java index 13d6cf0c8782..4ebd3d6d45fd 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java @@ -28,7 +28,7 @@ public class AsciidocGeneratorTest { private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocGeneratorTest.class); @Test - public void testSpecSchema() throws Exception { + public void testPingSpecTitle() throws Exception { final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/ping.yaml"); AsciidocDocumentationCodegen codeGen = new AsciidocDocumentationCodegen(); @@ -38,7 +38,7 @@ public void testSpecSchema() throws Exception { } @Test - public void testGenerateMarkupFileWithAsciidocGenerator() throws Exception { + public void testGenerateIndexAsciidocMarkupFileWithAsciidocGenerator() throws Exception { File output = Files.createTempDirectory("test").toFile(); @@ -58,7 +58,7 @@ public void testGenerateMarkupFileWithAsciidocGenerator() throws Exception { } @Test - public void testGenerateAsciidocMarkupContent() throws Exception { + public void testGenerateIndexAsciidocMarkupContent() throws Exception { final File output = Files.createTempDirectory("test").toFile(); output.mkdirs(); output.deleteOnExit(); @@ -85,7 +85,7 @@ public void testGenerateAsciidocMarkupContent() throws Exception { @Test - public void testAdditionalDirectoriesGeneratoreHeaderAttributes() throws Exception { + public void testAdditionalDirectoriesGeneratedIntoHeaderAttributes() throws Exception { File output = Files.createTempDirectory("test").toFile(); LOGGER.info("test: generating sample markup " + output.getAbsolutePath()); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java index 4f0449184f7c..73276fbd430a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java @@ -18,7 +18,7 @@ public class AsciidocSampleGeneratorTest { /** ensure api-docs.json includes sample and spec files into markup. */ @Test - public void testSampleMarkupGenerationFromJsonWithSpecsAndSamples() throws Exception { + public void testSampleAsciidocMarkupGenerationFromJsonWithSpecsAndSamples() throws Exception { File outputTempDirectory = Files.createTempDirectory("test-asciidoc-sample-generator.").toFile(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java index fb5470c75bfd..44f3356b311a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java @@ -20,7 +20,7 @@ public void setup() { } @Test - public void testMarkupFilterDoesNotIncludeMissingFile() { + public void testIncludeMarkupFilterDoesNotIncludeMissingFile() { final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); final Map ctx = context("specinclude", generator.new IncludeMarkupLambda("DOES_NOT_EXIST")); @@ -30,7 +30,7 @@ public void testMarkupFilterDoesNotIncludeMissingFile() { } @Test - public void testMarkupIncludesFoundFileOk() throws IOException { + public void testIncludeMarkupFilterFoundFileOk() throws IOException { File tempFile = File.createTempFile("IncludeMarkupFilterTestDummyfile", "-adoc"); tempFile.deleteOnExit(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java index 7be543ff0a90..e5edb8709162 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java @@ -20,17 +20,17 @@ public void setup() { } @Test - public void testMarkupFilterDoesNotLinkMissingFile() { + public void testLinkMarkupFilterDoesNotLinkMissingFile() { final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); final Map ctx = context("link", generator.new LinkMarkupLambda("DOES_NOT_EXIST")); final String result = execute("{{#link}}not.an.existing.file.adoc{{/link}}", ctx); - Assert.assertTrue(result.contains("// markup not found, not linked"), "unexpected filtered: " + result); + Assert.assertTrue(result.contains("// file not found, no"), "unexpected filtered: " + result); } @Test - public void testMarkupLinkFoundFileOk() throws IOException { + public void testLinkMarkupFilterLinksFoundFileOk() throws IOException { File tempFile = File.createTempFile("LinkMarkupFilterTestDummyfile", ".adoc"); tempFile.deleteOnExit(); @@ -40,7 +40,7 @@ public void testMarkupLinkFoundFileOk() throws IOException { final String result = execute("{{#linkIntoMarkup}}my link text, " + tempFile.getName() + "{{/linkIntoMarkup}}", ctx); Assert.assertTrue(result.contains("link:"), "unexpected filtered: " + result); - Assert.assertTrue(result.contains(tempFile.getName() + "[my link text]"), "unexpected filtered: " + result); + Assert.assertTrue(result.contains(tempFile.getName() + "[]"), "unexpected filtered: " + result); } } From 24046cf9b3ff30d362208d9fa16f7444fa8527f5 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Thu, 5 Sep 2019 23:11:13 +0200 Subject: [PATCH 09/14] fix travis build error, removed windows line endings from mustache asciiidoc templates. --- .../asciidoc-documentation/index.mustache | 202 +++++++++--------- .../asciidoc-documentation/model.mustache | 56 ++--- .../asciidoc-documentation/param.mustache | 1 - .../asciidoc-documentation/params.mustache | 106 ++++----- 4 files changed, 182 insertions(+), 183 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache index 166938da2a4b..425cb563715f 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -1,101 +1,101 @@ -= {{{appName}}} -{{infoEmail}} -{{#version}}{{{version}}}{{/version}} -:toc: left -:numbered: -:toclevels: 3 -:source-highlighter: highlightjs -:keywords: openapi, rest, {{appName}} -:specDir: {{specDir}} -:snippetDir: {{snippetDir}} -:generator-template: v1 2019-09-03 -:info-url: {{infoUrl}} -:app-name: {{appName}} - -[abstract] -.Abstract -{{{appDescription}}} - -{{#specinclude}}intro.adoc{{/specinclude}} - -== Endpoints - -{{#apiInfo}} -{{#apis}} -{{#operations}} - -[.{{baseName}}] -=== {{baseName}} - -{{#operation}} - -[.{{nickname}}] -==== {{nickname}} - -`{{httpMethod}} {{path}}` - -{{{summary}}} - -===== Description - -{{{notes}}} - -{{#specinclude}}{{path}}/{{httpMethod}}/spec.adoc{{/specinclude}} - - -{{> params}} - -===== Return Type - -{{#hasReference}} -{{^returnSimpleType}}{{returnContainer}}[{{/returnSimpleType}}<<{{returnBaseType}}>>{{^returnSimpleType}}]{{/returnSimpleType}} -{{/hasReference}} - -{{^hasReference}} -{{#returnType}}<<{{returnType}}>>{{/returnType}} -{{^returnType}}-{{/returnType}} -{{/hasReference}} - -{{#hasProduces}} -===== Content Type - -{{#produces}} -* {{{mediaType}}} -{{/produces}} -{{/hasProduces}} - -===== Responses - -.http response codes -[cols="2,3,1"] -|=== -| Code | Message | Datatype - -{{#responses}} - -| {{code}} -| {{message}} -| {{^simpleType}}{{dataType}}[<<{{baseType}}>>]{{/simpleType}} {{#simpleType}}<<{{dataType}}>>{{/simpleType}} - -{{/responses}} -|=== - -===== Samples - -{{#snippetinclude}}{{path}}/{{httpMethod}}/http-request.adoc{{/snippetinclude}} -{{#snippetinclude}}{{path}}/{{httpMethod}}/http-response.adoc{{/snippetinclude}} - -{{#snippetlink}}* wiremock data, {{path}}/{{httpMethod}}/{{httpMethod}}.json{{/snippetlink}} - -ifdef::internal-generation[] -===== Implementation -{{#specinclude}}{{path}}/{{httpMethod}}/implementation.adoc{{/specinclude}} - -endif::internal-generation[] - -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} - -{{> model}} += {{{appName}}} +{{infoEmail}} +{{#version}}{{{version}}}{{/version}} +:toc: left +:numbered: +:toclevels: 3 +:source-highlighter: highlightjs +:keywords: openapi, rest, {{appName}} +:specDir: {{specDir}} +:snippetDir: {{snippetDir}} +:generator-template: v1 2019-09-03 +:info-url: {{infoUrl}} +:app-name: {{appName}} + +[abstract] +.Abstract +{{{appDescription}}} + +{{#specinclude}}intro.adoc{{/specinclude}} + +== Endpoints + +{{#apiInfo}} +{{#apis}} +{{#operations}} + +[.{{baseName}}] +=== {{baseName}} + +{{#operation}} + +[.{{nickname}}] +==== {{nickname}} + +`{{httpMethod}} {{path}}` + +{{{summary}}} + +===== Description + +{{{notes}}} + +{{#specinclude}}{{path}}/{{httpMethod}}/spec.adoc{{/specinclude}} + + +{{> params}} + +===== Return Type + +{{#hasReference}} +{{^returnSimpleType}}{{returnContainer}}[{{/returnSimpleType}}<<{{returnBaseType}}>>{{^returnSimpleType}}]{{/returnSimpleType}} +{{/hasReference}} + +{{^hasReference}} +{{#returnType}}<<{{returnType}}>>{{/returnType}} +{{^returnType}}-{{/returnType}} +{{/hasReference}} + +{{#hasProduces}} +===== Content Type + +{{#produces}} +* {{{mediaType}}} +{{/produces}} +{{/hasProduces}} + +===== Responses + +.http response codes +[cols="2,3,1"] +|=== +| Code | Message | Datatype + +{{#responses}} + +| {{code}} +| {{message}} +| {{^simpleType}}{{dataType}}[<<{{baseType}}>>]{{/simpleType}} {{#simpleType}}<<{{dataType}}>>{{/simpleType}} + +{{/responses}} +|=== + +===== Samples + +{{#snippetinclude}}{{path}}/{{httpMethod}}/http-request.adoc{{/snippetinclude}} +{{#snippetinclude}}{{path}}/{{httpMethod}}/http-response.adoc{{/snippetinclude}} + +{{#snippetlink}}* wiremock data, {{path}}/{{httpMethod}}/{{httpMethod}}.json{{/snippetlink}} + +ifdef::internal-generation[] +===== Implementation +{{#specinclude}}{{path}}/{{httpMethod}}/implementation.adoc{{/specinclude}} + +endif::internal-generation[] + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +{{> model}} diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache index d1b13074c392..b36b7227c190 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/model.mustache @@ -1,28 +1,28 @@ -[#models] -== Models - -{{#models}} - {{#model}} - -[#{{classname}}] -==== _{{classname}}_ {{title}} - -{{unescapedDescription}} - -[.fields-{{classname}}] -[cols="2,1,2,4,1"] -|=== -| Field Name| Required| Type| Description| Format - -{{#vars}} -| {{name}} -| {{#required}}X{{/required}} -| {{dataType}} {{#isContainer}} of <<{{complexType}}>>{{/isContainer}} -| {{description}} -| {{{dataFormat}}} {{#isEnum}}Enum: _ {{#_enum}}{{this}}, {{/_enum}}{{/isEnum}} _ - -{{/vars}} -|=== - - {{/model}} -{{/models}} +[#models] +== Models + +{{#models}} + {{#model}} + +[#{{classname}}] +==== _{{classname}}_ {{title}} + +{{unescapedDescription}} + +[.fields-{{classname}}] +[cols="2,1,2,4,1"] +|=== +| Field Name| Required| Type| Description| Format + +{{#vars}} +| {{name}} +| {{#required}}X{{/required}} +| {{dataType}} {{#isContainer}} of <<{{complexType}}>>{{/isContainer}} +| {{description}} +| {{{dataFormat}}} {{#isEnum}}Enum: _ {{#_enum}}{{this}}, {{/_enum}}{{/isEnum}} _ + +{{/vars}} +|=== + + {{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache index 51c4447d8033..863c72948915 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/param.mustache @@ -3,4 +3,3 @@ | {{^required}}-{{/required}}{{#required}}X{{/required}} | {{defaultValue}} | {{{pattern}}} - diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache index bc895ee93f1d..9be5b8377f04 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/params.mustache @@ -1,53 +1,53 @@ -===== Parameters - -{{#hasPathParams}} -====== Path Parameters - -[cols="2,3,1,1,1"] -|=== -|Name| Description| Required| Default| Pattern - -{{#pathParams}} -{{>param}} -{{/pathParams}} -|=== -{{/hasPathParams}} - -{{#hasBodyParam}} -===== Body Parameter - -[cols="2,3,1,1,1"] -|=== -|Name| Description| Required| Default| Pattern - -{{#bodyParams}} -{{>param}} -{{/bodyParams}} -|=== -{{/hasBodyParam}} - -{{#hasHeaderParams}} -====== Header Parameters - -[cols="2,3,1,1,1"] -|=== -|Name| Description| Required| Default| Pattern - -{{#headerParams}} -{{>param}} -{{/headerParams}} -|=== -{{/hasHeaderParams}} - -{{#hasQueryParams}} -====== Query Parameters - -[cols="2,3,1,1,1"] -|=== -|Name| Description| Required| Default| Pattern - -{{#queryParams}} -{{>param}} -{{/queryParams}} -|=== -{{/hasQueryParams}} +===== Parameters + +{{#hasPathParams}} +====== Path Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#pathParams}} +{{>param}} +{{/pathParams}} +|=== +{{/hasPathParams}} + +{{#hasBodyParam}} +===== Body Parameter + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#bodyParams}} +{{>param}} +{{/bodyParams}} +|=== +{{/hasBodyParam}} + +{{#hasHeaderParams}} +====== Header Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#headerParams}} +{{>param}} +{{/headerParams}} +|=== +{{/hasHeaderParams}} + +{{#hasQueryParams}} +====== Query Parameters + +[cols="2,3,1,1,1"] +|=== +|Name| Description| Required| Default| Pattern + +{{#queryParams}} +{{>param}} +{{/queryParams}} +|=== +{{/hasQueryParams}} From 12086f7688ce45b36bd284ef8c6a896d240c3570 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Thu, 5 Sep 2019 23:22:33 +0200 Subject: [PATCH 10/14] asciidoc generator: comment and reduce visibility of helper method (fix dron build) --- .../languages/AsciidocDocumentationCodegen.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index 25a7664e6054..b2b127c6df9b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -54,7 +54,7 @@ public String resetCounter( ) { @Override public void execute(final Template.Fragment frag, final Writer out) throws IOException { - final String relativeFileName = AsciidocDocumentationCodegen.Sanitize(frag.execute()); + final String relativeFileName = AsciidocDocumentationCodegen.sanitize(frag.execute()); final Path filePathToInclude = Paths.get(basePath, relativeFileName).toAbsolutePath(); if(Files.isRegularFile(filePathToInclude)) { @@ -97,7 +97,7 @@ public void execute(final Template.Fragment frag, final Writer out) throws IOExc final String linkName = tokens.length > 0 ? tokens[0] : ""; - final String relativeFileName = AsciidocDocumentationCodegen.Sanitize(tokens.length > 1 ? tokens[1] : linkName); + final String relativeFileName = AsciidocDocumentationCodegen.sanitize(tokens.length > 1 ? tokens[1] : linkName); final Path filePathToLinkTo = Paths.get(basePath, relativeFileName).toAbsolutePath(); @@ -124,8 +124,10 @@ public CodegenType getTag() { return CodegenType.DOCUMENTATION; } - /** extracted filter value should be relative to be of use as link or include file. */ - public static String Sanitize(final String name) { + /** 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) From 9bf9b7f1e068274aa33c2722e8437bc853b8c380 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Thu, 5 Sep 2019 23:33:54 +0200 Subject: [PATCH 11/14] asciidoc: windows linefeed again (fix travis ci) --- .../src/main/resources/asciidoc-documentation/stubs/empty.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc b/modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc index 5d3959a037b8..c6d8ea163e71 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/stubs/empty.adoc @@ -1 +1 @@ -// openapi generator built documentation, see https://github.com/OpenAPITools/openapi-generator +// openapi generator built documentation, see https://github.com/OpenAPITools/openapi-generator From 9697f9ed1c370e645a404524f5c0d20cf3e99932 Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Fri, 6 Sep 2019 00:22:48 +0200 Subject: [PATCH 12/14] asciidoc generator: remove \t and format again. --- .../AsciidocDocumentationCodegen.java | 286 +++++++++--------- .../asciidoc/AsciidocGeneratorTest.java | 47 ++- .../asciidoc/IncludeMarkupFilterTest.java | 24 +- .../asciidoc/LinkMarkupFilterTest.java | 21 +- 4 files changed, 194 insertions(+), 184 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index b2b127c6df9b..0f4dad2818b3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -19,103 +19,112 @@ import io.swagger.v3.oas.models.OpenAPI; -/** basic asciidoc markup generator. - * @see asciidoctor - */ +/** + * basic asciidoc markup generator. + * + * @see asciidoctor + */ public class AsciidocDocumentationCodegen extends DefaultCodegen implements CodegenConfig { - private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocDocumentationCodegen.class); + 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: - *
{{#includemarkup}}{{name}}/description.adoc{{/includemarkup}}
- */ - 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: - *
{{#snippetLink}}markup until koma, /{{name}}.json{{/snippetLink}}
- */ - 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"); - } - } - } - + /** + * Lambda emitting an asciidoc "include::filename.adoc[]" if file is found in + * path. Use: + * + *
+     * {{#includemarkup}}{{name}}/description.adoc{{/includemarkup}}
+     * 
+ */ + 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: + * + *
+     * {{#snippetLink}}markup until koma, /{{name}}.json{{/snippetLink}}
+     * 
+ */ + 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; @@ -124,40 +133,42 @@ public CodegenType getTag() { return CodegenType.DOCUMENTATION; } - /** extracted filter value should be relative to be of use as link or include file. + /** + * 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. */ + * @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; - } + String sanitized = name == null ? "" : name.trim(); + return sanitized.startsWith(File.separator) || sanitized.startsWith("/") ? sanitized.substring(1) : sanitized; + } - public String getName() { + public String getName() { return "asciidoc"; } public String getHelp() { return "Generates asciidoc markup based documentation."; } - + public String getSpecDir() { - return additionalProperties.get("specDir").toString(); + return additionalProperties.get("specDir").toString(); } - + public String getSnippetDir() { - return additionalProperties.get("snippetDir").toString(); + 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(); cliOptions.add(new CliOption("appName", "short name of the application")); @@ -170,15 +181,13 @@ public AsciidocDocumentationCodegen() { 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("..")); + + 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"); @@ -190,15 +199,15 @@ public AsciidocDocumentationCodegen() { 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(); languageSpecificPrimitives = new HashSet(); importMapping = new HashMap(); - + } - + @Override public String escapeQuotationMark(String input) { return input; // just return the original string @@ -208,45 +217,44 @@ public String escapeQuotationMark(String input) { 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()); - }; - + 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 ); + 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()); - }; - + 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 ); + additionalProperties.put("snippetinclude", this.includeSnippetMarkupLambda); this.linkSnippetMarkupLambda = new LinkMarkupLambda(snippetDir); - additionalProperties.put("snippetlink", this.linkSnippetMarkupLambda ); + 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); - } + if (this.includeSpecMarkupLambda != null) { + LOGGER.info("specs: " + ": " + this.includeSpecMarkupLambda.resetCounter()); + } + if (this.includeSnippetMarkupLambda != null) { + LOGGER.info("snippets: " + ": " + this.includeSnippetMarkupLambda.resetCounter()); + } + super.processOpenAPI(openAPI); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java index 4ebd3d6d45fd..746a5bd87afa 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java @@ -23,11 +23,11 @@ import io.swagger.v3.oas.models.OpenAPI; /** check against ping.yaml spec. */ -public class AsciidocGeneratorTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocGeneratorTest.class); - - @Test +public class AsciidocGeneratorTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocGeneratorTest.class); + + @Test public void testPingSpecTitle() throws Exception { final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/ping.yaml"); @@ -36,16 +36,14 @@ public void testPingSpecTitle() throws Exception { Assert.assertEquals(openAPI.getInfo().getTitle(), "ping test"); } - + @Test public void testGenerateIndexAsciidocMarkupFileWithAsciidocGenerator() throws Exception { File output = Files.createTempDirectory("test").toFile(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("asciidoc") - .setInputSpec("src/test/resources/3_0/ping.yaml") - .setOutputDir(output.getAbsolutePath()) + + final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("asciidoc") + .setInputSpec("src/test/resources/3_0/ping.yaml").setOutputDir(output.getAbsolutePath()) .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY-SNIPPET-DIR") .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, "MY-SPEC-DIR"); @@ -56,7 +54,7 @@ public void testGenerateIndexAsciidocMarkupFileWithAsciidocGenerator() throws Ex Map generatedFiles = generator.getFiles(); TestUtils.ensureContainsFile(generatedFiles, output, "index.adoc"); } - + @Test public void testGenerateIndexAsciidocMarkupContent() throws Exception { final File output = Files.createTempDirectory("test").toFile(); @@ -73,17 +71,18 @@ public void testGenerateIndexAsciidocMarkupContent() throws Exception { boolean markupFileGenerated = false; for (File file : files) { if (file.getName().equals("index.adoc")) { - markupFileGenerated = true; + markupFileGenerated = true; String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); // check on some basic asciidoc markup content - Assert.assertTrue(markupContent.contains("= ping test"), "expected = header in: " + markupContent.substring(0, 50)); - Assert.assertTrue(markupContent.contains(":toc: "), "expected = :toc: " + markupContent.substring(0, 50)); + Assert.assertTrue(markupContent.contains("= ping test"), + "expected = header in: " + markupContent.substring(0, 50)); + Assert.assertTrue(markupContent.contains(":toc: "), + "expected = :toc: " + markupContent.substring(0, 50)); } } Assert.assertTrue(markupFileGenerated, "Default api file is not generated!"); } - @Test public void testAdditionalDirectoriesGeneratedIntoHeaderAttributes() throws Exception { File output = Files.createTempDirectory("test").toFile(); @@ -93,22 +92,22 @@ public void testAdditionalDirectoriesGeneratedIntoHeaderAttributes() throws Exce Map props = new TreeMap(); props.put("specDir", "spec"); - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("asciidoc") - .setInputSpec("src/test/resources/3_0/ping.yaml") - .setOutputDir(output.getAbsolutePath()) + final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("asciidoc") + .setInputSpec("src/test/resources/3_0/ping.yaml").setOutputDir(output.getAbsolutePath()) .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, "SPEC-DIR") - .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY/SNIPPET/DIR"); + .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY/SNIPPET/DIR"); DefaultGenerator generator = new DefaultGenerator(); List files = generator.opts(configurator.toClientOptInput()).generate(); boolean markupFileGenerated = false; for (File file : files) { if (file.getName().equals("index.adoc")) { - markupFileGenerated = true; + markupFileGenerated = true; String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); - Assert.assertTrue(markupContent.contains(":specDir: SPEC-DIR"), "expected :specDir: in: " + markupContent.substring(0, 250)); - Assert.assertTrue(markupContent.contains(":snippetDir: MY/SNIPPET/DIR"), "expected :snippetDir: in: " + markupContent.substring(0, 250)); + Assert.assertTrue(markupContent.contains(":specDir: SPEC-DIR"), + "expected :specDir: in: " + markupContent.substring(0, 250)); + Assert.assertTrue(markupContent.contains(":snippetDir: MY/SNIPPET/DIR"), + "expected :snippetDir: in: " + markupContent.substring(0, 250)); } } Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java index 44f3356b311a..7c178b495500 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/IncludeMarkupFilterTest.java @@ -13,7 +13,7 @@ import org.testng.Assert; public class IncludeMarkupFilterTest extends LambdaTest { - + @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); @@ -21,26 +21,28 @@ public void setup() { @Test public void testIncludeMarkupFilterDoesNotIncludeMissingFile() { - - final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); final Map ctx = context("specinclude", generator.new IncludeMarkupLambda("DOES_NOT_EXIST")); - + final String result = execute("{{#specinclude}}not.an.existing.file.adoc{{/specinclude}}", ctx); - Assert.assertTrue(result.contains("// markup not found, no include ::not.an.existing.file.adoc[]"), "unexpected filtered " + result); + Assert.assertTrue(result.contains("// markup not found, no include ::not.an.existing.file.adoc[]"), + "unexpected filtered " + result); } @Test public void testIncludeMarkupFilterFoundFileOk() throws IOException { - - File tempFile = File.createTempFile("IncludeMarkupFilterTestDummyfile", "-adoc"); + + File tempFile = File.createTempFile("IncludeMarkupFilterTestDummyfile", "-adoc"); tempFile.deleteOnExit(); - - final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); - final Map ctx = context("snippetinclude", generator.new IncludeMarkupLambda(tempFile.getParent())); + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + final Map ctx = context("snippetinclude", + generator.new IncludeMarkupLambda(tempFile.getParent())); final String result = execute("{{#snippetinclude}}" + tempFile.getName() + "{{/snippetinclude}}", ctx); Assert.assertTrue(result.contains("include::"), "unexpected filtered: " + result); - Assert.assertTrue(result.contains(tempFile.getName()), "unexpected filtered: " + result); + Assert.assertTrue(result.contains(tempFile.getName()), "unexpected filtered: " + result); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java index e5edb8709162..3d04eec31108 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/LinkMarkupFilterTest.java @@ -13,7 +13,7 @@ import org.testng.Assert; public class LinkMarkupFilterTest extends LambdaTest { - + @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); @@ -21,26 +21,27 @@ public void setup() { @Test public void testLinkMarkupFilterDoesNotLinkMissingFile() { - - final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); final Map ctx = context("link", generator.new LinkMarkupLambda("DOES_NOT_EXIST")); - + final String result = execute("{{#link}}not.an.existing.file.adoc{{/link}}", ctx); Assert.assertTrue(result.contains("// file not found, no"), "unexpected filtered: " + result); } @Test public void testLinkMarkupFilterLinksFoundFileOk() throws IOException { - - File tempFile = File.createTempFile("LinkMarkupFilterTestDummyfile", ".adoc"); + + File tempFile = File.createTempFile("LinkMarkupFilterTestDummyfile", ".adoc"); tempFile.deleteOnExit(); - - final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); + + final AsciidocDocumentationCodegen generator = new AsciidocDocumentationCodegen(); final Map ctx = context("linkIntoMarkup", generator.new LinkMarkupLambda(tempFile.getParent())); - final String result = execute("{{#linkIntoMarkup}}my link text, " + tempFile.getName() + "{{/linkIntoMarkup}}", ctx); + final String result = execute("{{#linkIntoMarkup}}my link text, " + tempFile.getName() + "{{/linkIntoMarkup}}", + ctx); Assert.assertTrue(result.contains("link:"), "unexpected filtered: " + result); - Assert.assertTrue(result.contains(tempFile.getName() + "[]"), "unexpected filtered: " + result); + Assert.assertTrue(result.contains(tempFile.getName() + "[]"), "unexpected filtered: " + result); } } From cb3e9dbad5d6108e4bcbdb8c6493936acf85f28f Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Fri, 6 Sep 2019 01:29:30 +0200 Subject: [PATCH 13/14] fix ascidoc generator ci builds ... ongoing.. --- docs/generators/asciidoc.md | 25 ++++ .../asciidoc/AsciidocSampleGeneratorTest.java | 128 +++++++++--------- 2 files changed, 87 insertions(+), 66 deletions(-) create mode 100644 docs/generators/asciidoc.md diff --git a/docs/generators/asciidoc.md b/docs/generators/asciidoc.md new file mode 100644 index 000000000000..8e2a1c0f4b72 --- /dev/null +++ b/docs/generators/asciidoc.md @@ -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: .| |..| diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java index 73276fbd430a..31535e69bc66 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocSampleGeneratorTest.java @@ -16,71 +16,67 @@ public class AsciidocSampleGeneratorTest { - /** ensure api-docs.json includes sample and spec files into markup. */ - @Test - public void testSampleAsciidocMarkupGenerationFromJsonWithSpecsAndSamples() throws Exception { - - File outputTempDirectory = Files.createTempDirectory("test-asciidoc-sample-generator.").toFile(); - - File specDir = new File("src/test/resources/3_0/asciidoc/specs/"); - File snippetDir = new File("src/test/resources/3_0/asciidoc/generated-snippets/"); - - Assert.assertTrue(specDir.exists(), "test cancel, not specdDir found to use." + specDir.getPath()); - Assert.assertTrue(snippetDir.exists(), "test cancel, not snippedDir found to use." + snippetDir.getPath()); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("asciidoc") - .setInputSpec("src/test/resources/3_0/asciidoc/api-docs.json") - .setOutputDir(outputTempDirectory.getAbsolutePath()) - .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, specDir.toString()) - .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, snippetDir.toString()); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator - .opts(configurator.toClientOptInput()) - .generate(); - - boolean markupFileGenerated = false; - - for (File file : files) { - if (file.getName().equals("index.adoc")) { - markupFileGenerated = true; - String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); - - // include correct values from cli. - Assert.assertTrue(markupContent.contains(":specDir: " + specDir.toString()), - "expected :specDir: in: " + markupContent.substring(0, 350)); - Assert.assertTrue(markupContent.contains(":snippetDir: " + snippetDir.toString()), - "expected :snippetDir: in: " + markupContent.substring(0, 350)); - - // include correct markup from separate directories, relative links - Assert.assertTrue(markupContent.contains("include::rest/project/GET/spec.adoc[]"), - "expected project spec.adoc to be included in " + file.getAbsolutePath()); - - Assert.assertTrue(markupContent.contains("include::rest/project/GET/implementation.adoc[]"), - "expected project implementation.adoc to be included in " + file.getAbsolutePath()); - - Assert.assertTrue(markupContent.contains("include::rest/project/GET/http-request.adoc[]"), - "expected project http-request.adoc to be included in " + file.getAbsolutePath()); - - Assert.assertTrue(markupContent.contains("include::rest/project/GET/http-response.adoc[]"), - "expected project http-response.adoc to be included in " + file.getAbsolutePath()); - - - Assert.assertTrue(markupContent.contains("link:rest/project/GET/GET.json["), - "expected link: not found in file: " + file.getAbsoluteFile()); - - - // extract correct value from json - Assert.assertTrue(markupContent.contains("= time@work rest api"), "missing main header for api spec from json: " + markupContent.substring(0, 100)); - } - Files.deleteIfExists(Paths.get(file.getAbsolutePath())); - } - - Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!"); - - Files.deleteIfExists(Paths.get(outputTempDirectory.getAbsolutePath(), ".openapi-generator")); - Files.deleteIfExists(Paths.get(outputTempDirectory.getAbsolutePath())); - } + /** ensure api-docs.json includes sample and spec files into markup. */ + @Test + public void testSampleAsciidocMarkupGenerationFromJsonWithSpecsAndSamples() throws Exception { + + File outputTempDirectory = Files.createTempDirectory("test-asciidoc-sample-generator.").toFile(); + + File specDir = new File("src/test/resources/3_0/asciidoc/specs/"); + File snippetDir = new File("src/test/resources/3_0/asciidoc/generated-snippets/"); + + Assert.assertTrue(specDir.exists(), "test cancel, not specdDir found to use." + specDir.getPath()); + Assert.assertTrue(snippetDir.exists(), "test cancel, not snippedDir found to use." + snippetDir.getPath()); + + final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("asciidoc") + .setInputSpec("src/test/resources/3_0/asciidoc/api-docs.json") + .setOutputDir(outputTempDirectory.getAbsolutePath()) + .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, specDir.toString()) + .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, snippetDir.toString()); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + + boolean markupFileGenerated = false; + + for (File file : files) { + if (file.getName().equals("index.adoc")) { + markupFileGenerated = true; + String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); + + // include correct values from cli. + Assert.assertTrue(markupContent.contains(":specDir: " + specDir.toString()), + "expected :specDir: in: " + markupContent.substring(0, 350)); + Assert.assertTrue(markupContent.contains(":snippetDir: " + snippetDir.toString()), + "expected :snippetDir: in: " + markupContent.substring(0, 350)); + + // include correct markup from separate directories, relative links + Assert.assertTrue(markupContent.contains("include::rest/project/GET/spec.adoc[]"), + "expected project spec.adoc to be included in " + file.getAbsolutePath()); + + Assert.assertTrue(markupContent.contains("include::rest/project/GET/implementation.adoc[]"), + "expected project implementation.adoc to be included in " + file.getAbsolutePath()); + + Assert.assertTrue(markupContent.contains("include::rest/project/GET/http-request.adoc[]"), + "expected project http-request.adoc to be included in " + file.getAbsolutePath()); + + Assert.assertTrue(markupContent.contains("include::rest/project/GET/http-response.adoc[]"), + "expected project http-response.adoc to be included in " + file.getAbsolutePath()); + + Assert.assertTrue(markupContent.contains("link:rest/project/GET/GET.json["), + "expected link: not found in file: " + file.getAbsoluteFile()); + + // extract correct value from json + Assert.assertTrue(markupContent.contains("= time@work rest api"), + "missing main header for api spec from json: " + markupContent.substring(0, 100)); + } + Files.deleteIfExists(Paths.get(file.getAbsolutePath())); + } + + Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!"); + + Files.deleteIfExists(Paths.get(outputTempDirectory.getAbsolutePath(), ".openapi-generator")); + Files.deleteIfExists(Paths.get(outputTempDirectory.getAbsolutePath())); + } } From 138b88c85f039b6aab6862060d68488bb33873ad Mon Sep 17 00:00:00 2001 From: "man.from.home" Date: Fri, 6 Sep 2019 21:31:46 +0200 Subject: [PATCH 14/14] asciidoc: add generator .md files, unix line ending. --- docs/generators.md | 1 + docs/generators/asciidoc.md | 50 ++++++++++++++++++------------------- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/docs/generators.md b/docs/generators.md index 81653653bb26..19c75327570b 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -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) diff --git a/docs/generators/asciidoc.md b/docs/generators/asciidoc.md index 8e2a1c0f4b72..d33cab1f7eb2 100644 --- a/docs/generators/asciidoc.md +++ b/docs/generators/asciidoc.md @@ -1,25 +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: .| |..| + +--- +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: .| |..|