Search in sources :

Example 1 with TemplatesConfiguration

use of com.devonfw.cobigen.impl.config.TemplatesConfiguration in project cobigen by devonfw.

the class TemplatesConfigurationReaderTest method testTemplateRefOutsideCurrentFile.

/**
 * Tests the correct resolution of TemplateRef from outside the current templates file.
 */
@Test
public void testTemplateRefOutsideCurrentFile() {
    // given
    Trigger trigger = new Trigger("testingTrigger", "asdf", "valid_external_templateref", Charset.forName("UTF-8"), new LinkedList<Matcher>(), new LinkedList<ContainerMatcher>());
    Path configPath = Paths.get(new File(testFileRootPath).toURI());
    ConfigurationHolder configurationHolder = new ConfigurationHolder(configPath.toUri());
    TemplatesConfiguration templatesConfiguration = configurationHolder.readTemplatesConfiguration(trigger);
    Map<String, Increment> increments = templatesConfiguration.getIncrements();
    assertThat(templatesConfiguration.getTrigger().getId()).isEqualTo("testingTrigger");
    // validation
    Increment incrementThree = increments.get("3");
    LinkedList<String> templateNamesThree = new LinkedList<>();
    for (Template tmplate : incrementThree.getTemplates()) {
        templateNamesThree.add(tmplate.getName());
    }
    assertThat(templateNamesThree).containsExactly("templateDecl");
    Increment incrementFour = increments.get("4");
    LinkedList<String> templateNamesFour = new LinkedList<>();
    for (Template tmplate : incrementFour.getTemplates()) {
        templateNamesFour.add(tmplate.getName());
    }
    assertThat(templateNamesFour).containsExactly("ExplicitlyDefined");
}
Also used : Path(java.nio.file.Path) ContainerMatcher(com.devonfw.cobigen.impl.config.entity.ContainerMatcher) Matcher(com.devonfw.cobigen.impl.config.entity.Matcher) ConfigurationHolder(com.devonfw.cobigen.impl.config.ConfigurationHolder) TemplatesConfiguration(com.devonfw.cobigen.impl.config.TemplatesConfiguration) LinkedList(java.util.LinkedList) Template(com.devonfw.cobigen.impl.config.entity.Template) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) ContainerMatcher(com.devonfw.cobigen.impl.config.entity.ContainerMatcher) Increment(com.devonfw.cobigen.impl.config.entity.Increment) File(java.io.File) AbstractUnitTest(com.devonfw.cobigen.unittest.config.common.AbstractUnitTest) Test(org.junit.Test)

Example 2 with TemplatesConfiguration

use of com.devonfw.cobigen.impl.config.TemplatesConfiguration in project cobigen by devonfw.

the class ConfigurationInterpreterImpl method getMatchingIncrements.

@Cached
@Override
public List<IncrementTo> getMatchingIncrements(Object matcherInput) throws InvalidConfigurationException {
    LOG.debug("Matching increments requested.");
    List<IncrementTo> increments = Lists.newLinkedList();
    List<String> matchingTriggerIds = getMatchingTriggerIds(matcherInput);
    for (TemplatesConfiguration templatesConfiguration : getMatchingTemplatesConfigurations(matcherInput)) {
        increments.addAll(convertIncrements(templatesConfiguration.getAllGenerationPackages(), templatesConfiguration.getTrigger(), matchingTriggerIds));
    }
    LOG.debug("{} matching increments found.", increments.size());
    return increments;
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) TemplatesConfiguration(com.devonfw.cobigen.impl.config.TemplatesConfiguration) Cached(com.devonfw.cobigen.api.annotation.Cached)

Example 3 with TemplatesConfiguration

use of com.devonfw.cobigen.impl.config.TemplatesConfiguration 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);
        }
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) Formatter(java.util.Formatter) IOException(java.io.IOException) PluginNotAvailableException(com.devonfw.cobigen.api.exception.PluginNotAvailableException) PluginProcessingException(com.devonfw.cobigen.impl.exceptions.PluginProcessingException) TemplatesConfiguration(com.devonfw.cobigen.impl.config.TemplatesConfiguration) Template(com.devonfw.cobigen.impl.config.entity.Template) InputReader(com.devonfw.cobigen.api.extension.InputReader) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) Merger(com.devonfw.cobigen.api.extension.Merger) StringWriter(java.io.StringWriter) TextTemplateEngine(com.devonfw.cobigen.api.extension.TextTemplateEngine) MergeException(com.devonfw.cobigen.api.exception.MergeException) UnknownTemplateException(com.devonfw.cobigen.impl.exceptions.UnknownTemplateException) Map(java.util.Map) File(java.io.File) PathExpressionResolver(com.devonfw.cobigen.impl.config.resolver.PathExpressionResolver) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 4 with TemplatesConfiguration

use of com.devonfw.cobigen.impl.config.TemplatesConfiguration 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;
}
Also used : Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) TemplatesConfiguration(com.devonfw.cobigen.impl.config.TemplatesConfiguration)

Example 5 with TemplatesConfiguration

use of com.devonfw.cobigen.impl.config.TemplatesConfiguration in project cobigen by devonfw.

the class ConfigurationInterpreterImpl method getMatchingTemplates.

@Cached
@Override
public List<TemplateTo> getMatchingTemplates(Object matcherInput) throws InvalidConfigurationException {
    LOG.debug("Matching templates requested.");
    List<TemplateTo> templates = Lists.newLinkedList();
    for (TemplatesConfiguration templatesConfiguration : getMatchingTemplatesConfigurations(matcherInput)) {
        for (Template template : templatesConfiguration.getAllTemplates()) {
            templates.add(new TemplateTo(template.getName(), template.getMergeStrategy(), templatesConfiguration.getTrigger().getId()));
        }
    }
    LOG.debug("{} matching templates found.", templates.size());
    return templates;
}
Also used : TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) TemplatesConfiguration(com.devonfw.cobigen.impl.config.TemplatesConfiguration) Template(com.devonfw.cobigen.impl.config.entity.Template) Cached(com.devonfw.cobigen.api.annotation.Cached)

Aggregations

TemplatesConfiguration (com.devonfw.cobigen.impl.config.TemplatesConfiguration)6 Trigger (com.devonfw.cobigen.impl.config.entity.Trigger)4 Template (com.devonfw.cobigen.impl.config.entity.Template)3 File (java.io.File)3 Cached (com.devonfw.cobigen.api.annotation.Cached)2 ConfigurationHolder (com.devonfw.cobigen.impl.config.ConfigurationHolder)2 ContainerMatcher (com.devonfw.cobigen.impl.config.entity.ContainerMatcher)2 Increment (com.devonfw.cobigen.impl.config.entity.Increment)2 Matcher (com.devonfw.cobigen.impl.config.entity.Matcher)2 AbstractUnitTest (com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)2 Path (java.nio.file.Path)2 Test (org.junit.Test)2 CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)1 MergeException (com.devonfw.cobigen.api.exception.MergeException)1 PluginNotAvailableException (com.devonfw.cobigen.api.exception.PluginNotAvailableException)1 InputReader (com.devonfw.cobigen.api.extension.InputReader)1 Merger (com.devonfw.cobigen.api.extension.Merger)1 TextTemplateEngine (com.devonfw.cobigen.api.extension.TextTemplateEngine)1 IncrementTo (com.devonfw.cobigen.api.to.IncrementTo)1 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)1