use of com.devonfw.cobigen.impl.config.entity.Trigger in project cobigen by devonfw.
the class ContextConfigurationReader method loadTriggers.
/**
* Loads all {@link Trigger}s of the static context into the local representation
*
* @return a {@link List} containing all the {@link Trigger}s
*/
public Map<String, Trigger> loadTriggers() {
Map<String, Trigger> triggers = Maps.newHashMap();
for (Path contextFile : this.contextConfigurations.keySet()) {
ContextConfiguration contextConfiguration = this.contextConfigurations.get(contextFile);
for (com.devonfw.cobigen.impl.config.entity.io.Trigger t : contextConfiguration.getTrigger()) {
// templateFolder property is optional in schema version 2.2. If not set take the path of the context.xml file
String templateFolder = t.getTemplateFolder();
if (templateFolder.isEmpty() || templateFolder.equals("/")) {
templateFolder = contextFile.getParent().getFileName().toString();
}
triggers.put(t.getId(), new Trigger(t.getId(), t.getType(), templateFolder, Charset.forName(t.getInputCharset()), loadMatchers(t), loadContainerMatchers(t)));
}
}
return triggers;
}
use of com.devonfw.cobigen.impl.config.entity.Trigger in project cobigen by devonfw.
the class CobiGenImpl method getModelBuilder.
@Override
public ModelBuilder getModelBuilder(Object input) {
List<String> matchingTriggerIds = getMatchingTriggerIds(input);
// Just take the first trigger as all trigger should have the same input reader. See javadoc.
Trigger trigger = this.configurationHolder.readContextConfiguration().getTrigger(matchingTriggerIds.get(0));
return new ModelBuilderImpl(input, trigger);
}
use of com.devonfw.cobigen.impl.config.entity.Trigger in project cobigen by devonfw.
the class GenerationProcessorImpl method generate.
/**
* Generates code for the given input with the given template and the given {@link TriggerInterpreter} to the
* destination specified by the templates configuration.
*
* @param template to be processed for generation
* @param triggerInterpreter {@link TriggerInterpreter} to be used for reading the input and creating the model
* @param origToTmpFileTrace the mapping of temporary generated files to their original target destination to
* eventually finalizing the generation process
* @param progressCallback to track progress
* @throws InvalidConfigurationException if the inputs do not fit to the configuration or there are some configuration
* failures
*/
private void generate(TemplateTo template, TriggerInterpreter triggerInterpreter, Map<File, File> origToTmpFileTrace, BiConsumer<String, Integer> progressCallback) {
Trigger trigger = this.configurationHolder.readContextConfiguration().getTrigger(template.getTriggerId());
InputReader inputReader = triggerInterpreter.getInputReader();
if (!inputReader.isValidInput(this.input)) {
throw new CobiGenRuntimeException("An invalid input of type " + this.input.getClass() + " has been passed to " + inputReader.getClass() + " (derived from trigger '" + trigger.getId() + "')");
}
List<Object> inputObjects = this.inputResolver.resolveContainerElements(this.input, trigger);
TemplatesConfiguration tConfig = this.configurationHolder.readTemplatesConfiguration(trigger);
String templateEngineName = tConfig.getTemplateEngine();
TextTemplateEngine templateEngine = TemplateEngineRegistry.getEngine(templateEngineName);
templateEngine.setTemplateFolder(this.configurationHolder.readContextConfiguration().getConfigurationPath().resolve(trigger.getTemplateFolder()));
Template templateEty = tConfig.getTemplate(template.getId());
if (templateEty == null) {
throw new UnknownTemplateException(template.getId());
}
for (Object generatorInput : inputObjects) {
progressCallback.accept("Building template model for input " + generatorInput, 1);
Map<String, Object> model = buildModel(triggerInterpreter, trigger, generatorInput, templateEty);
String targetCharset = templateEty.getTargetCharset();
// resolve temporary file paths
@SuppressWarnings("unchecked") PathExpressionResolver pathExpressionResolver = new PathExpressionResolver(Variables.fromMap((Map<String, String>) model.get(ModelBuilderImpl.NS_VARIABLES)));
String resolvedTargetDestinationPath = pathExpressionResolver.evaluateExpressions(templateEty.getUnresolvedTargetPath());
String resolvedTmpDestinationPath = pathExpressionResolver.evaluateExpressions(templateEty.getUnresolvedTemplatePath());
File originalFile = this.targetRootPath.resolve(resolvedTargetDestinationPath).toFile();
File tmpOriginalFile;
if (origToTmpFileTrace.containsKey(originalFile)) {
// use the available temporary file
tmpOriginalFile = origToTmpFileTrace.get(originalFile);
} else {
tmpOriginalFile = this.tmpTargetRootPath.resolve(resolvedTmpDestinationPath).toFile();
// remember mapping to later on copy the generated resources to its target destinations
origToTmpFileTrace.put(originalFile, tmpOriginalFile);
}
if (originalFile.exists() || tmpOriginalFile.exists()) {
if (!tmpOriginalFile.exists()) {
try {
FileUtils.copyFile(originalFile, tmpOriginalFile);
} catch (IOException e) {
throw new CobiGenRuntimeException("Could not copy file " + originalFile.getPath() + " to tmp generation directory! Generation skipped.", e);
}
}
if ((this.forceOverride || template.isForceOverride()) && templateEty.getMergeStrategy() == null || ConfigurationConstants.MERGE_STRATEGY_OVERRIDE.equals(templateEty.getMergeStrategy())) {
try (Formatter formatter = new Formatter()) {
formatter.format("Overriding %1$-40s FROM %2$-50s TO %3$s ...", originalFile.getName(), templateEty.getName(), resolvedTargetDestinationPath);
LOG.info(formatter.out().toString());
progressCallback.accept(formatter.out().toString(), 1);
}
progressCallback.accept("Generating " + template.getId() + " for " + generatorInput, 1);
generateTemplateAndWriteFile(tmpOriginalFile, templateEty, templateEngine, model, targetCharset);
} else if (templateEty.getMergeStrategy() != null) {
try (Formatter formatter = new Formatter()) {
formatter.format("Merging %1$-40s FROM %2$-50s TO %3$s ...", originalFile.getName(), templateEty.getName(), resolvedTargetDestinationPath);
LOG.info(formatter.out().toString());
progressCallback.accept(formatter.out().toString(), 1);
}
String patch = null;
try (Writer out = new StringWriter()) {
templateEngine.process(templateEty, model, out, targetCharset);
patch = out.toString();
String mergeResult = null;
Merger merger = PluginRegistry.getMerger(templateEty.getMergeStrategy());
if (merger != null) {
mergeResult = merger.merge(tmpOriginalFile, patch, targetCharset);
} else {
throw new PluginNotAvailableException("merge strategy '" + templateEty.getMergeStrategy() + "'", null);
}
if (mergeResult != null) {
LOG.debug("Merge {} with char set {}.", tmpOriginalFile.getName(), targetCharset);
FileUtils.writeStringToFile(tmpOriginalFile, mergeResult, targetCharset);
} else {
throw new PluginProcessingException("Merger " + merger.getType() + " returned null on merge(...), which is not allowed.");
}
} catch (MergeException e) {
writeBrokenPatchFile(targetCharset, tmpOriginalFile, patch);
// enrich merge exception to provide template ID
throw new MergeException(e, templateEty.getAbsoluteTemplatePath());
} catch (IOException e) {
throw new CobiGenRuntimeException("Could not write file " + tmpOriginalFile.toPath() + " after merge.", e);
}
}
} else {
try (Formatter formatter = new Formatter()) {
formatter.format("Generating %1$-40s FROM %2$-50s TO %3$s ...", originalFile.getName(), templateEty.getName(), resolvedTargetDestinationPath);
LOG.info(formatter.out().toString());
progressCallback.accept(formatter.out().toString(), 1);
}
generateTemplateAndWriteFile(tmpOriginalFile, templateEty, templateEngine, model, targetCharset);
}
}
}
use of com.devonfw.cobigen.impl.config.entity.Trigger in project cobigen by devonfw.
the class ConfigurationInterpreterImpl method getMatchingTemplatesConfigurations.
/**
* Returns the {@link List} of matching {@link TemplatesConfiguration}s for the given input object
*
* @param matcherInput input object activates a matcher and thus is target for context variable extraction. Possibly a
* combined or wrapping object for multiple input objects
* @return the {@link List} of matching {@link TemplatesConfiguration}s
* @throws InvalidConfigurationException if the configuration is not valid
*/
private List<TemplatesConfiguration> getMatchingTemplatesConfigurations(Object matcherInput) throws InvalidConfigurationException {
LOG.debug("Retrieve matching template configurations.");
List<TemplatesConfiguration> templateConfigurations = Lists.newLinkedList();
for (Trigger trigger : this.triggerMatchingEvaluator.getMatchingTriggers(matcherInput)) {
TemplatesConfiguration templatesConfiguration = this.configurationHolder.readTemplatesConfiguration(trigger);
if (templatesConfiguration != null) {
if (!templateConfigurations.contains(templatesConfiguration)) {
templateConfigurations.add(templatesConfiguration);
}
}
}
return templateConfigurations;
}
use of com.devonfw.cobigen.impl.config.entity.Trigger in project cobigen by devonfw.
the class InputInterpreterImpl method resolveContainers.
@Cached
@Override
public List<Object> resolveContainers(Object input) {
List<Trigger> matchingTriggers = this.configurationInterpreter.getMatchingTriggers(input);
List<Object> inputs = new ArrayList<>();
for (Trigger t : matchingTriggers) {
inputs.addAll(this.inputResolver.resolveContainerElements(input, t));
}
return inputs;
}
Aggregations