Skip to content

Commit 029728d

Browse files
authored
[maven-plugin] allow for ignore file override (#4597)
* [maven-plugin] allow for ignore file override The .swagger-codegen-ignore file is beneficial for existing source directories to provide pattern-based exclusion rules for existing source to be ignored by swagger codegen. Until now, there's been no utility other than skipOverwrite to modify the initial generation of code (either via CLI or maven plugin). This commit adds support for an ignoreFileOverride option to both the CLI and the maven plugin. Example CLI usage: ``` java -jar swagger-codegen.jar generate \ -i swagger.json -l csharp \ -o target --ignore-file-override /path/to/ignore-file ``` Example Maven Plugin configuration: ``` <build> <plugins> <plugin> <groupId>io.swagger</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>2.2.2-SNAPSHOT</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/swagger.yaml</inputSpec> <language>csharp</language> <invokerPackage>io.swagger</invokerPackage> <modelPackage>io.swagger.models</modelPackage> <apiPackage>io.swagger.apis</apiPackage> <ignoreFileOverride>/Users/jim/projects/swagger-codegen/.sample-ignore</ignoreFileOverride> <configOptions> </configOptions> </configuration> </execution> </executions> </plugin> </plugins> </build> ``` * [maven-plugin] update new javadocs * fix bad merge due to missing }
1 parent 59c189e commit 029728d

File tree

13 files changed

+157
-24
lines changed

13 files changed

+157
-24
lines changed

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,9 @@ public class Generate implements Runnable {
121121
@Option(name = {"--reserved-words-mappings"}, title = "import mappings",
122122
description = "specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used. For example id=identifier")
123123
private String reservedWordsMappings;
124+
125+
@Option(name = {"--ignore-file-override"}, title = "ignore file override location", description = CodegenConstants.IGNORE_FILE_OVERRIDE_DESC)
126+
private String ignoreFileOverride;
124127

125128
@Override
126129
public void run() {
@@ -215,6 +218,10 @@ public void run() {
215218
configurator.setHttpUserAgent(httpUserAgent);
216219
}
217220

221+
if (isNotEmpty(ignoreFileOverride)) {
222+
configurator.setIgnoreFileOverride(ignoreFileOverride);
223+
}
224+
218225
applySystemPropertiesKvp(systemProperties, configurator);
219226
applyInstantiationTypesKvp(instantiationTypes, configurator);
220227
applyImportMappingsKvp(importMappings, configurator);

modules/swagger-codegen-maven-plugin/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ mvn clean compile
4949
- `useJaxbAnnotations` - enable Jaxb annotations inside the generated models
5050
- `configOptions` - a map of language-specific parameters (see below)
5151
- `configHelp` - dumps the configuration help for the specified library (generates no sources)
52+
- `ignoreFileOverride` - specifies the full path to a `.swagger-codegen-ignore` used for pattern based overrides of generated outputs
5253

5354
### Custom Generator
5455

modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,12 @@ public class CodeGenMojo extends AbstractMojo {
162162
@Parameter(name = "modelNameSuffix", required = false)
163163
private String modelNameSuffix;
164164

165+
/**
166+
* Sets an optional ignoreFileOverride path
167+
*/
168+
@Parameter(name = "ignoreFileOverride", required = false)
169+
private String ignoreFileOverride;
170+
165171
/**
166172
* A map of language-specific parameters as passed with the -c option to the command line
167173
*/
@@ -216,6 +222,10 @@ public void execute() throws MojoExecutionException {
216222
configurator.setGitRepoId(gitRepoId);
217223
}
218224

225+
if(isNotEmpty(ignoreFileOverride)) {
226+
configurator.setIgnoreFileOverride(ignoreFileOverride);
227+
}
228+
219229
configurator.setLang(language);
220230

221231
configurator.setOutputDir(output.getAbsolutePath());

modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,5 +199,8 @@ public interface CodegenConfig {
199199
String getHttpUserAgent();
200200

201201
String getCommonTemplateDir();
202-
202+
203+
void setIgnoreFilePathOverride(String ignoreFileOverride);
204+
205+
String getIgnoreFilePathOverride();
203206
}

modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,7 @@ public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case
153153

154154
public static final String NON_PUBLIC_API = "nonPublicApi";
155155
public static final String NON_PUBLIC_API_DESC = "Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.";
156+
157+
public static final String IGNORE_FILE_OVERRIDE = "ignoreFileOverride";
158+
public static final String IGNORE_FILE_OVERRIDE_DESC = "Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation.";
156159
}

modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ public class DefaultCodegen {
115115
// Then translated back during JSON encoding and decoding
116116
protected Map<String, String> specialCharReplacements = new HashMap<String, String>();
117117

118+
protected String ignoreFilePathOverride;
119+
118120
public List<CliOption> cliOptions() {
119121
return cliOptions;
120122
}
@@ -3454,7 +3456,26 @@ public boolean convertPropertyToBooleanAndWriteBack(String propertyKey) {
34543456

34553457
return booleanValue;
34563458
}
3457-
3459+
3460+
/**
3461+
* Provides an override location, if any is specified, for the .swagger-codegen-ignore.
3462+
*
3463+
* This is originally intended for the first generation only.
3464+
*
3465+
* @return a string of the full path to an override ignore file.
3466+
*/
3467+
public String getIgnoreFilePathOverride() {
3468+
return ignoreFilePathOverride;
3469+
}
3470+
3471+
/**
3472+
* Sets an override location for the .swagger-codegen.ignore location for the first code generation.
3473+
*
3474+
* @param ignoreFileOverride The full path to an ignore file
3475+
*/
3476+
public void setIgnoreFilePathOverride(final String ignoreFileOverride) {
3477+
this.ignoreFilePathOverride = ignoreFileOverride;
3478+
}
34583479

34593480
public boolean convertPropertyToBoolean(String propertyKey) {
34603481
boolean booleanValue = false;

modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,21 @@ public Generator opts(ClientOptInput opts) {
4242
this.swagger = opts.getSwagger();
4343
this.config = opts.getConfig();
4444
this.config.additionalProperties().putAll(opts.getOpts().getProperties());
45-
ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
45+
46+
String ignoreFileLocation = this.config.getIgnoreFilePathOverride();
47+
if(ignoreFileLocation != null) {
48+
final File ignoreFile = new File(ignoreFileLocation);
49+
if(ignoreFile.exists() && ignoreFile.canRead()) {
50+
this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile);
51+
} else {
52+
LOGGER.warn("Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", ignoreFileLocation);
53+
}
54+
}
55+
56+
if(this.ignoreProcessor == null) {
57+
this.ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
58+
}
59+
4660
return this;
4761
}
4862

modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ public class CodegenConfigurator {
5454
private String artifactId;
5555
private String artifactVersion;
5656
private String library;
57+
private String ignoreFileOverride;
5758
private Map<String, String> systemProperties = new HashMap<String, String>();
5859
private Map<String, String> instantiationTypes = new HashMap<String, String>();
5960
private Map<String, String> typeMappings = new HashMap<String, String>();
@@ -356,7 +357,16 @@ public CodegenConfigurator setReservedWordsMappings(Map<String, String> reserved
356357
public CodegenConfigurator addAdditionalReservedWordMapping(String key, String value) {
357358
this.reservedWordMappings.put(key, value);
358359
return this;
359-
}
360+
}
361+
362+
public String getIgnoreFileOverride() {
363+
return ignoreFileOverride;
364+
}
365+
366+
public CodegenConfigurator setIgnoreFileOverride(final String ignoreFileOverride) {
367+
this.ignoreFileOverride = ignoreFileOverride;
368+
return this;
369+
}
360370

361371
public ClientOptInput toClientOptInput() {
362372

@@ -371,6 +381,7 @@ public ClientOptInput toClientOptInput() {
371381
config.setInputSpec(inputSpec);
372382
config.setOutputDir(outputDir);
373383
config.setSkipOverwrite(skipOverwrite);
384+
config.setIgnoreFilePathOverride(ignoreFileOverride);
374385

375386
config.instantiationTypes().putAll(instantiationTypes);
376387
config.typeMapping().putAll(typeMappings);

modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java

Lines changed: 77 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,34 +8,71 @@
88

99
import java.io.*;
1010
import java.util.ArrayList;
11+
import java.util.Collection;
1112
import java.util.List;
1213

14+
/**
15+
* Presents a processing utility for parsing and evaluating files containing common ignore patterns. (.swagger-codegen-ignore)
16+
*/
1317
public class CodegenIgnoreProcessor {
1418

1519
private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class);
16-
private final String outputPath;
20+
21+
private File ignoreFile = null;
22+
1723
private List<Rule> exclusionRules = new ArrayList<>();
1824
private List<Rule> inclusionRules = new ArrayList<>();
1925

20-
public CodegenIgnoreProcessor(String outputPath) {
21-
this.outputPath = outputPath;
22-
final File directory = new File(outputPath);
23-
if(directory.exists() && directory.isDirectory()){
24-
final File codegenIgnore = new File(directory, ".swagger-codegen-ignore");
25-
if(codegenIgnore.exists() && codegenIgnore.isFile()){
26-
try {
27-
loadCodegenRules(codegenIgnore);
28-
} catch (IOException e) {
29-
LOGGER.error("Could not process .swagger-codegen-ignore.", e.getMessage());
30-
}
31-
} else {
32-
// log info message
33-
LOGGER.info("No .swagger-codegen-ignore file found.");
26+
/**
27+
* Loads the default ignore file (.swagger-codegen-ignore) from the specified path.
28+
*
29+
* @param baseDirectory The base directory of the files to be processed. This contains the ignore file.
30+
*/
31+
public CodegenIgnoreProcessor(final String baseDirectory) {
32+
this(baseDirectory, ".swagger-codegen-ignore");
33+
}
34+
35+
/**
36+
* Loads the specified ignore file by name ([ignoreFile]) from the specified path.
37+
*
38+
* @param baseDirectory The base directory of the files to be processed. This contains the ignore file.
39+
* @param ignoreFile The file containing ignore patterns.
40+
*/
41+
@SuppressWarnings("WeakerAccess")
42+
public CodegenIgnoreProcessor(final String baseDirectory, final String ignoreFile) {
43+
final File directory = new File(baseDirectory);
44+
final File targetIgnoreFile = new File(directory, ignoreFile);
45+
if (directory.exists() && directory.isDirectory()) {
46+
loadFromFile(targetIgnoreFile);
47+
} else {
48+
LOGGER.warn("Directory does not exist, or is inaccessible. No file will be evaluated.");
49+
}
50+
}
51+
52+
/**
53+
* Constructs an instance of {@link CodegenIgnoreProcessor} from an ignore file defined by {@code targetIgnoreFile}.
54+
*
55+
* @param targetIgnoreFile The ignore file location.
56+
*/
57+
public CodegenIgnoreProcessor(final File targetIgnoreFile) {
58+
loadFromFile(targetIgnoreFile);
59+
}
60+
61+
private void loadFromFile(File targetIgnoreFile) {
62+
if (targetIgnoreFile.exists() && targetIgnoreFile.isFile()) {
63+
try {
64+
loadCodegenRules(targetIgnoreFile);
65+
this.ignoreFile = targetIgnoreFile;
66+
} catch (IOException e) {
67+
LOGGER.error(String.format("Could not process %s.", targetIgnoreFile.getName()), e.getMessage());
3468
}
69+
} else {
70+
// log info message
71+
LOGGER.info(String.format("No %s file found.", targetIgnoreFile.getName()));
3572
}
3673
}
3774

38-
void loadCodegenRules(File codegenIgnore) throws IOException {
75+
void loadCodegenRules(final File codegenIgnore) throws IOException {
3976
try (BufferedReader reader = new BufferedReader(new FileReader(codegenIgnore))) {
4077
String line;
4178

@@ -61,8 +98,17 @@ void loadCodegenRules(File codegenIgnore) throws IOException {
6198
}
6299
}
63100

64-
public boolean allowsFile(File targetFile) {
65-
File file = new File(new File(this.outputPath).toURI().relativize(targetFile.toURI()).getPath());
101+
/**
102+
* Determines whether or not a file defined by {@code toEvaluate} is allowed,
103+
* under the exclusion rules from the ignore file being processed.
104+
*
105+
* @param targetFile The file to check against exclusion rules from the ignore file.
106+
* @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed).
107+
*/
108+
public boolean allowsFile(final File targetFile) {
109+
if(this.ignoreFile == null) return true;
110+
111+
File file = new File(this.ignoreFile.getParentFile().toURI().relativize(targetFile.toURI()).getPath());
66112
Boolean directoryExcluded = false;
67113
Boolean exclude = false;
68114
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
@@ -124,10 +170,23 @@ public boolean allowsFile(File targetFile) {
124170
return Boolean.FALSE.equals(exclude);
125171
}
126172

173+
/**
174+
* Allows a consumer to manually inspect explicit "inclusion rules". That is, patterns in the ignore file which have been negated.
175+
*
176+
* @return A {@link ImmutableList#copyOf(Collection)} of rules which possibly negate exclusion rules in the ignore file.
177+
*/
127178
public List<Rule> getInclusionRules() {
128179
return ImmutableList.copyOf(inclusionRules);
129180
}
130181

182+
/**
183+
* Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent
184+
* files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
185+
*
186+
* NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
187+
*
188+
* @return A {@link ImmutableList#copyOf(Collection)} of rules which define exclusions by patterns in the ignore file.
189+
*/
131190
public List<Rule> getExclusionRules() {
132191
return ImmutableList.copyOf(exclusionRules);
133192
}

modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ protected String getPattern() {
5151
* Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root.
5252
* <p>
5353
* NOTE: It is not possible to re-include a file if a parent directory of that file is excluded.
54+
*
55+
* @return {@code true} if the rule is negated (inverse), otherwise {@code false} (normal).
5456
*/
5557
public Boolean getNegated() {
5658
return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE;

0 commit comments

Comments
 (0)