Skip to content

Commit 70294ac

Browse files
authored
Merge pull request #7881 from jmini/issue7845
[3.0.0] Modify 'meta' generator
2 parents 82e7192 + a4fbd6d commit 70294ac

File tree

18 files changed

+857
-54
lines changed

18 files changed

+857
-54
lines changed

bin/meta-codegen.sh

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/bin/sh
2+
3+
SCRIPT="$0"
4+
5+
while [ -h "$SCRIPT" ] ; do
6+
ls=`ls -ld "$SCRIPT"`
7+
link=`expr "$ls" : '.*-> \(.*\)$'`
8+
if expr "$link" : '/.*' > /dev/null; then
9+
SCRIPT="$link"
10+
else
11+
SCRIPT=`dirname "$SCRIPT"`/"$link"
12+
fi
13+
done
14+
15+
if [ ! -d "${APP_DIR}" ]; then
16+
APP_DIR=`dirname "$SCRIPT"`/..
17+
APP_DIR=`cd "${APP_DIR}"; pwd`
18+
fi
19+
20+
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
21+
22+
if [ ! -f "$executable" ]
23+
then
24+
mvn clean package
25+
fi
26+
27+
# if you've executed sbt assembly previously it will use that instead.
28+
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
29+
ags="$@ meta -n myClientCodegen -p com.my.company.codegen -o samples/meta-codegen"
30+
31+
java $JAVA_OPTS -jar $executable $ags

modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java

Lines changed: 36 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package io.swagger.codegen.cmd;
22

3-
import ch.lambdaj.function.convert.Converter;
43
import com.google.common.base.CaseFormat;
54
import com.google.common.collect.ImmutableList;
65
import com.google.common.collect.ImmutableMap;
@@ -17,17 +16,14 @@
1716
import java.util.List;
1817
import java.util.Map;
1918

20-
import static ch.lambdaj.collection.LambdaCollections.with;
21-
import static com.google.common.base.Joiner.on;
22-
2319
/**
2420
* User: lanwen Date: 24.03.15 Time: 20:22
2521
*/
2622
public class Meta implements Runnable {
2723

2824
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
2925

30-
private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
26+
private static final String TEMPLATE_DIR_CLASSPATH = "v2/codegen";
3127
private static final String MUSTACHE_EXTENSION = ".mustache";
3228

3329
private String outputFolder = "";
@@ -56,27 +52,28 @@ public void run() {
5652
List<SupportingFile> supportingFiles =
5753
ImmutableList
5854
.of(new SupportingFile("pom.mustache", "", "pom.xml"),
59-
new SupportingFile("generatorClass.mustache", on(File.separator)
60-
.join("src/main/java", asPath(targetPackage)), mainClass
61-
.concat(".java")), new SupportingFile("README.mustache",
62-
"", "README.md"), new SupportingFile("api.template",
63-
"src/main/resources" + File.separator + name,
64-
"api.mustache"), new SupportingFile("model.template",
65-
"src/main/resources" + File.separator + name,
66-
"model.mustache"), new SupportingFile("services.mustache",
67-
"src/main/resources/META-INF/services",
68-
"io.swagger.codegen.CodegenConfig"));
69-
70-
String swaggerVersion = Version.readVersionFromResources();
55+
new SupportingFile("generatorClass.mustache",
56+
String.join(File.separator, "src", "main", "java", asPath(targetPackage)),
57+
mainClass.concat(".java")),
58+
new SupportingFile("README.mustache", "", "README.md"),
59+
new SupportingFile("api.template", String.join(File.separator, "src", "main", "resources", name), "api.mustache"),
60+
new SupportingFile("model.template", String.join(File.separator, "src", "main", "resources", name), "model.mustache"),
61+
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
62+
new SupportingFile("services.mustache", String.join(File.separator, "src", "main", "resources", "META-INF", "services"), "io.swagger.codegen.CodegenConfig"));
63+
64+
String swaggerCodegenVersion = Version.readVersionFromResources(Version.SWAGGER_CODEGEN_VERSION);
65+
String swaggerCodegenGeneratorsVersion = Version.readVersionFromResources(Version.SWAGGER_CODEGEN_GENERATORS_VERSION);
7166

7267
Map<String, Object> data =
7368
new ImmutableMap.Builder<String, Object>().put("generatorPackage", targetPackage)
7469
.put("generatorClass", mainClass).put("name", name)
7570
.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass)
76-
.put("swaggerCodegenVersion", swaggerVersion).build();
77-
71+
.put("swaggerCodegenVersion", swaggerCodegenVersion)
72+
.put("swaggerCodegenGeneratorsVersion", swaggerCodegenGeneratorsVersion)
73+
.build();
7874

79-
with(supportingFiles).convert(processFiles(targetDir, data));
75+
DefaultGenerator generator = new DefaultGenerator();
76+
supportingFiles.stream().forEach(f -> processFiles(generator, f, targetDir, data));
8077
}
8178

8279
/**
@@ -87,40 +84,27 @@ public void run() {
8784
* @param data - map with additional params needed to process templates
8885
* @return converter object to pass to lambdaj
8986
*/
90-
private static Converter<SupportingFile, File> processFiles(final File targetDir,
91-
final Map<String, Object> data) {
92-
return new Converter<SupportingFile, File>() {
93-
private DefaultGenerator generator = new DefaultGenerator();
87+
private static void processFiles(DefaultGenerator generator, SupportingFile support, final File targetDir, final Map<String, Object> data) {
88+
try {
89+
File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder);
90+
File outputFile = new File(destinationFolder, support.destinationFilename);
9491

95-
@Override
96-
public File convert(SupportingFile support) {
97-
try {
98-
File destinationFolder =
99-
new File(new File(targetDir.getAbsolutePath()), support.folder);
100-
File outputFile = new File(destinationFolder, support.destinationFilename);
101-
102-
String template =
103-
generator.readTemplate(new File(TEMPLATE_DIR_CLASSPATH,
104-
support.templateFile).getPath());
105-
String formatted = template;
106-
107-
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
108-
LOGGER.info("writing file to {}", outputFile.getAbsolutePath());
109-
formatted =
110-
Mustache.compiler().withLoader(loader(generator)).defaultValue("")
111-
.compile(template).execute(data);
112-
} else {
113-
LOGGER.info("copying file to {}", outputFile.getAbsolutePath());
114-
}
115-
116-
FileUtils.writeStringToFile(outputFile, formatted);
117-
return outputFile;
118-
119-
} catch (IOException e) {
120-
throw new RuntimeException("Can't generate project", e);
121-
}
92+
String template = generator.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath());
93+
String formatted = template;
94+
95+
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
96+
LOGGER.info("writing file to {}", outputFile.getAbsolutePath());
97+
formatted = Mustache.compiler().withLoader(loader(generator)).defaultValue("").compile(template).execute(data);
12298
}
123-
};
99+
else {
100+
LOGGER.info("copying file to {}", outputFile.getAbsolutePath());
101+
}
102+
103+
FileUtils.writeStringToFile(outputFile, formatted);
104+
}
105+
catch (IOException e) {
106+
throw new RuntimeException("Can't generate project", e);
107+
}
124108
}
125109

126110
/**

modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,20 @@ public class Version implements Runnable {
1111

1212
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
1313

14+
public static final String SWAGGER_CODEGEN_VERSION = "swagger-codegen.version";
15+
public static final String SWAGGER_CODEGEN_GENERATORS_VERSION = "swagger-codegen.generators.version";
16+
1417
private static final String VERSION_PLACEHOLDER = "${project.version}";
1518

1619
private static final String UNREADABLE_VERSION = "unreadable";
1720
private static final String UNSET_VERSION = "unset";
1821
private static final String UNKNOWN_VERSION = "unknown";
1922

2023
public static String readVersionFromResources() {
24+
return readVersionFromResources(SWAGGER_CODEGEN_VERSION);
25+
}
26+
27+
public static String readVersionFromResources(String key) {
2128
Properties versionProperties = new Properties();
2229
try (InputStream is = Version.class.getResourceAsStream("/version.properties")) {
2330
versionProperties.load(is);
@@ -26,7 +33,7 @@ public static String readVersionFromResources() {
2633
return UNREADABLE_VERSION;
2734
}
2835

29-
String version = versionProperties.getProperty("version", UNKNOWN_VERSION).trim();
36+
String version = versionProperties.getProperty(key, UNKNOWN_VERSION).trim();
3037
if (VERSION_PLACEHOLDER.equals(version)) {
3138
return UNSET_VERSION;
3239
} else {
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Swagger Codegen for the {{name}} library
2+
3+
## Overview
4+
This is a boiler-plate project to generate your own client library with Swagger. Its goal is
5+
to get you started with the basic plumbing so you can put in your own logic. It won't work without
6+
your changes applied.
7+
8+
## What's Swagger?
9+
The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service.
10+
11+
12+
Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more.
13+
14+
## How do I use this?
15+
At this point, you've likely generated a client setup. It will include something along these lines:
16+
17+
```
18+
.
19+
|- README.md // this file
20+
|- pom.xml // build script
21+
|-- src
22+
|--- main
23+
|---- java
24+
|----- {{generatorPackage}}.{{generatorClass}}.java // generator file
25+
|---- resources
26+
|----- {{name}} // template files
27+
|----- META-INF
28+
|------ services
29+
|------- io.swagger.codegen.CodegenConfig
30+
```
31+
32+
You _will_ need to make changes in at least the following:
33+
34+
`{{generatorClass}}.java`
35+
36+
Templates in this folder:
37+
38+
`src/main/resources/{{name}}`
39+
40+
Once modified, you can run this:
41+
42+
```
43+
mvn package
44+
```
45+
46+
In your generator project. A single jar file will be produced in `target`. You can now use that with codegen:
47+
48+
```
49+
java -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l {{name}} -i /path/to/swagger.yaml -o ./test
50+
```
51+
52+
Now your templates are available to the client generator and you can write output values
53+
54+
## But how do I modify this?
55+
The `{{generatorClass}}.java` has comments in it--lots of comments. There is no good substitute
56+
for reading the code more, though. See how the `{{generatorClass}}` implements `CodegenConfig`.
57+
That class has the signature of all values that can be overridden.
58+
59+
For the templates themselves, you have a number of values available to you for generation.
60+
You can execute the `java` command from above while passing different debug flags to show
61+
the object you have available during client generation:
62+
63+
```
64+
# The following additional debug options are available for all codegen targets:
65+
# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen
66+
# -DdebugModels prints models passed to the template engine
67+
# -DdebugOperations prints operations passed to the template engine
68+
# -DdebugSupportingFiles prints additional data passed to the template engine
69+
70+
java -DdebugOperations -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l {{name}} -i /path/to/swagger.yaml -o ./test
71+
```
72+
73+
Will, for example, output the debug info for operations. You can use this info
74+
in the `api.mustache` file.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
# This is a sample api mustache template. It is representing a ficticous
3+
# language and won't be usable or compile to anything without lots of changes.
4+
# Use it as an example. You can access the variables in the generator object
5+
# like such:
6+
7+
# use the package from the `apiPackage` variable
8+
package: {{package}}
9+
10+
# operations block
11+
{{#operations}}
12+
classname: {{classname}}
13+
14+
# loop over each operation in the API:
15+
{{#operation}}
16+
17+
# each operation has an `operationId`:
18+
operationId: {{operationId}}
19+
20+
# and parameters:
21+
{{#allParams}}
22+
{{paramName}}: {{dataType}}
23+
{{/allParams}}
24+
25+
{{/operation}}
26+
27+
# end of operations block
28+
{{/operations}}

0 commit comments

Comments
 (0)