Support overriding API/model templates with library template

This commit is contained in:
xhh 2015-08-08 11:14:06 +08:00
parent a41361c959
commit b686b53259
2 changed files with 22 additions and 15 deletions

View File

@ -60,6 +60,23 @@ public abstract class AbstractGenerator {
throw new RuntimeException("can't load template " + name);
}
/**
* Get the template file path with template dir prepended, and use the
* library template if exists.
*/
public String getFullTemplateFile(CodegenConfig config, String templateFile) {
String library = config.getLibrary();
if (library != null && !"".equals(library)) {
String libTemplateFile = config.templateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (templateExists(libTemplateFile)) {
return libTemplateFile;
}
}
return config.templateDir() + File.separator + templateFile;
}
public boolean templateExists(String name) {
return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null;
}

View File

@ -139,7 +139,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (!config.shouldOverwrite(filename)) {
continue;
}
String template = readTemplate(config.templateDir() + File.separator + templateName);
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
@ -191,7 +192,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
continue;
}
String template = readTemplate(config.templateDir() + File.separator + templateName);
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
@ -262,19 +264,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
continue;
}
String templateFile = null;
String library = config.getLibrary();
if (library != null && !"".equals(library)) {
String libTemplateFile = config.templateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
support.templateFile;
if (templateExists(libTemplateFile)) {
templateFile = libTemplateFile;
}
}
if (templateFile == null) {
templateFile = config.templateDir() + File.separator + support.templateFile;
}
String templateFile = getFullTemplateFile(config, support.templateFile);
if (templateFile.endsWith("mustache")) {
String template = readTemplate(templateFile);