Search in sources :

Example 1 with Template

use of com.devonfw.cobigen.impl.config.entity.Template in project cobigen by devonfw.

the class TemplatesConfigurationReader method createTemplate.

/**
 * @param templateFile the {@link TemplateFile}.
 * @param templateName the {@link Template#getName() template name} (ID).
 * @param unresolvedTemplatePath the {@link Template#getUnresolvedTemplatePath() unresolved template path}.
 * @param mergeStratgey the {@link Template#getMergeStrategy() merge strategy}.
 * @param outputCharset the {@link Template#getTargetCharset() target charset}.
 * @param scanSourcePath {@link TemplateScan#getTemplatePath() root path} of the {@link TemplateScan}
 * @return the new template instance.
 */
private Template createTemplate(TemplateFile templateFile, String templateName, String unresolvedTemplatePath, String mergeStratgey, String outputCharset, String scanSourcePath) {
    String unresolvedDestinationPath = unresolvedTemplatePath;
    TemplateFolder templateFolder = templateFile.getParent();
    String relocate = templateFolder.getVariables().get(PROPERTY_RELOCATE);
    if (relocate != null) {
        if (scanSourcePath != null) {
            // The relative template path has to be specifically parsed to string and back to a path so
            // the templateFile and scanSourcePath are using the same file system. More info can be found
            // at https://github.com/devonfw/cobigen/issues/715
            String templateFilePath = templateFile.getRootRelativePath().toString();
            Path destinationPath = Paths.get(scanSourcePath).relativize(Paths.get(templateFilePath));
            unresolvedDestinationPath = relocate.replace(VARIABLE_CWD, destinationPath.toString().replace("\\", "/"));
        }
    }
    return new Template(templateFile, templateName, stripTemplateFileending(unresolvedDestinationPath), unresolvedTemplatePath, mergeStratgey, outputCharset);
}
Also used : Path(java.nio.file.Path) TemplatePath(com.devonfw.cobigen.impl.config.entity.TemplatePath) TemplateFolder(com.devonfw.cobigen.impl.config.entity.TemplateFolder) Template(com.devonfw.cobigen.impl.config.entity.Template)

Example 2 with Template

use of com.devonfw.cobigen.impl.config.entity.Template in project cobigen by devonfw.

the class TemplatesConfigurationReader method loadTemplates.

/**
 * Loads all templates of the static configuration into the local representation
 *
 * @param trigger {@link Trigger} for which the templates should be loaded
 * @return the mapping of template names to the corresponding {@link Template}
 * @throws UnknownContextVariableException if the destination path contains an undefined context variable
 * @throws UnknownExpressionException if there is an unknown variable modifier
 * @throws InvalidConfigurationException if there are multiple templates with the same name
 */
public Map<String, Template> loadTemplates(Trigger trigger) throws UnknownExpressionException, UnknownContextVariableException, InvalidConfigurationException {
    Map<String, Template> templates = new HashMap<>();
    Templates templatesNode = this.configNode.getTemplates();
    if (templatesNode != null) {
        for (com.devonfw.cobigen.impl.config.entity.io.Template t : templatesNode.getTemplate()) {
            if (templates.get(t.getName()) != null) {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Multiple template definitions found for ref='" + t.getName() + "'");
            }
            TemplatePath child = this.rootTemplateFolder.navigate(t.getTemplateFile());
            if ((child == null) || (child.isFolder())) {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "no template file found for '" + t.getTemplateFile() + "'");
            }
            Template template = createTemplate((TemplateFile) child, t.getName(), t.getDestinationPath(), t.getMergeStrategy(), t.getTargetCharset(), null);
            templates.put(t.getName(), template);
        }
    }
    TemplateScans templateScans = this.configNode.getTemplateScans();
    if (templateScans != null) {
        List<TemplateScan> scans = templateScans.getTemplateScan();
        if (scans != null) {
            for (TemplateScan scan : scans) {
                scanTemplates(scan, templates, trigger);
            }
        }
    }
    // override existing templates with extension definitions
    Set<String> observedExtensionNames = Sets.newHashSet();
    if (templatesNode != null && templatesNode.getTemplateExtension() != null) {
        for (TemplateExtension ext : this.configNode.getTemplates().getTemplateExtension()) {
            // detection of duplicate templateExtensions
            if (observedExtensionNames.contains(ext.getRef())) {
                throw new InvalidConfigurationException("Two templateExtensions declared for ref='" + ext.getRef() + "'. Don't know what to do.");
            }
            observedExtensionNames.add(ext.getRef());
            // overriding properties if defined
            if (templates.containsKey(ext.getRef())) {
                Template template = templates.get(ext.getRef());
                if (ext.getDestinationPath() != null) {
                    template.setUnresolvedTargetPath(ext.getDestinationPath());
                }
                if (ext.getMergeStrategy() != null) {
                    template.setMergeStrategy(ext.getMergeStrategy());
                }
                if (ext.getTargetCharset() != null) {
                    template.setTargetCharset(ext.getTargetCharset());
                }
            } else {
                throw new InvalidConfigurationException("The templateExtension with ref='" + ext.getRef() + "' does not reference any template!");
            }
        }
    }
    return templates;
}
Also used : TemplatePath(com.devonfw.cobigen.impl.config.entity.TemplatePath) HashMap(java.util.HashMap) Templates(com.devonfw.cobigen.impl.config.entity.io.Templates) TemplateScan(com.devonfw.cobigen.impl.config.entity.io.TemplateScan) Template(com.devonfw.cobigen.impl.config.entity.Template) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) TemplateScans(com.devonfw.cobigen.impl.config.entity.io.TemplateScans) TemplateExtension(com.devonfw.cobigen.impl.config.entity.io.TemplateExtension)

Example 3 with Template

use of com.devonfw.cobigen.impl.config.entity.Template in project cobigen by devonfw.

the class TemplatesConfigurationReader method addAllTemplatesRecursively.

/**
 * Adds all templates defined within the increment and sub increments recursively.
 *
 * @param rootIncrement the {@link Increment} on which the templates should be added
 * @param current the source {@link com.devonfw.cobigen.impl.config.entity.io.Increment} from which to retrieve the
 *        data
 * @param templates {@link Map} of all templates (see {@link TemplatesConfigurationReader#loadTemplates(Trigger)}
 * @param increments {@link Map} of all retrieved increments
 * @throws InvalidConfigurationException if there is an invalid ref attribute
 */
private void addAllTemplatesRecursively(Increment rootIncrement, com.devonfw.cobigen.impl.config.entity.io.Increment current, Map<String, Template> templates, Map<String, Increment> increments) throws InvalidConfigurationException {
    for (TemplateRef ref : current.getTemplateRefOrIncrementRefOrTemplateScanRef().stream().filter(e -> e instanceof TemplateRef).map(e -> (TemplateRef) e).collect(Collectors.toList())) {
        Template temp = templates.get(ref.getRef());
        if (temp == null) {
            if (isExternalRef(ref.getRef())) {
                rootIncrement.addTemplate(loadExternalTemplate(ref));
            } else {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "No template found for ref='" + ref.getRef() + "'!");
            }
        } else {
            rootIncrement.addTemplate(temp);
        }
    }
    for (IncrementRef ref : current.getTemplateRefOrIncrementRefOrTemplateScanRef().stream().filter(e -> e instanceof IncrementRef).map(e -> (IncrementRef) e).collect(Collectors.toList())) {
        Increment parentPkg = increments.get(current.getName());
        Increment childPkg = increments.get(ref.getRef());
        if (childPkg == null) {
            // We try to find the increment inside our templates.xml file
            Increments incrementsNode = this.configNode.getIncrements();
            com.devonfw.cobigen.impl.config.entity.io.Increment source = null;
            if (incrementsNode != null) {
                // We only add the specific increment we want
                source = getSpecificIncrement(incrementsNode.getIncrement(), ref.getRef());
                if (source != null) {
                    addAllTemplatesRecursively(rootIncrement, source, templates, increments);
                } else // incrementRef contains "::". That would mean we have to search on another folder.
                if (isExternalRef(ref.getRef())) {
                    parentPkg.addIncrementDependency(loadExternalIncrement(ref));
                } else {
                    throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "No increment found for ref='" + ref.getRef() + "'!");
                }
            }
        } else {
            parentPkg.addIncrementDependency(childPkg);
            com.devonfw.cobigen.impl.config.entity.io.Increment pkg = getIncrementDeclaration(ref);
            addAllTemplatesRecursively(rootIncrement, pkg, templates, increments);
        }
    }
    for (TemplateScanRef ref : current.getTemplateRefOrIncrementRefOrTemplateScanRef().stream().filter(e -> e instanceof TemplateScanRef).map(e -> (TemplateScanRef) e).collect(Collectors.toList())) {
        List<String> scannedTemplateNames = this.templateScanTemplates.get(ref.getRef());
        if (scannedTemplateNames == null) {
            throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "No templateScan found for ref='" + ref.getRef() + "'!");
        } else {
            for (String scannedTemplateName : scannedTemplateNames) {
                rootIncrement.addTemplate(templates.get(scannedTemplateName));
            }
        }
    }
}
Also used : TemplateScans(com.devonfw.cobigen.impl.config.entity.io.TemplateScans) Unmarshaller(jakarta.xml.bind.Unmarshaller) TemplatesConfigurationVersion(com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion) StringUtils(org.apache.commons.lang3.StringUtils) Type(com.devonfw.cobigen.impl.config.versioning.VersionValidator.Type) BigDecimal(java.math.BigDecimal) JvmUtil(com.devonfw.cobigen.api.util.JvmUtil) Map(java.util.Map) VersionValidator(com.devonfw.cobigen.impl.config.versioning.VersionValidator) Path(java.nio.file.Path) ExceptionUtil(com.devonfw.cobigen.api.util.ExceptionUtil) Increments(com.devonfw.cobigen.impl.config.entity.io.Increments) TextTemplateEngine(com.devonfw.cobigen.api.extension.TextTemplateEngine) TemplatePath(com.devonfw.cobigen.impl.config.entity.TemplatePath) Set(java.util.Set) TemplateEngineRegistry(com.devonfw.cobigen.impl.extension.TemplateEngineRegistry) Collectors(java.util.stream.Collectors) Templates(com.devonfw.cobigen.impl.config.entity.io.Templates) UnknownContextVariableException(com.devonfw.cobigen.impl.exceptions.UnknownContextVariableException) Sets(com.google.common.collect.Sets) List(java.util.List) SAXException(org.xml.sax.SAXException) JXPathContext(org.apache.commons.jxpath.JXPathContext) ConfigurationConstants(com.devonfw.cobigen.api.constants.ConfigurationConstants) TemplatesConfiguration(com.devonfw.cobigen.impl.config.entity.io.TemplatesConfiguration) StreamSource(javax.xml.transform.stream.StreamSource) HashMap(java.util.HashMap) TemplateExtension(com.devonfw.cobigen.impl.config.entity.io.TemplateExtension) Schema(javax.xml.validation.Schema) ArrayList(java.util.ArrayList) TemplateScan(com.devonfw.cobigen.impl.config.entity.io.TemplateScan) HashSet(java.util.HashSet) TemplateScanRef(com.devonfw.cobigen.impl.config.entity.io.TemplateScanRef) XMLConstants(javax.xml.XMLConstants) MavenMetadata(com.devonfw.cobigen.impl.config.constant.MavenMetadata) TemplateFolder(com.devonfw.cobigen.impl.config.entity.TemplateFolder) UnmarshalException(jakarta.xml.bind.UnmarshalException) Properties(java.util.Properties) SchemaFactory(javax.xml.validation.SchemaFactory) Iterator(java.util.Iterator) JAXBContext(jakarta.xml.bind.JAXBContext) Files(java.nio.file.Files) ConfigurationHolder(com.devonfw.cobigen.impl.config.ConfigurationHolder) IncrementRef(com.devonfw.cobigen.impl.config.entity.io.IncrementRef) TemplateRef(com.devonfw.cobigen.impl.config.entity.io.TemplateRef) UnknownExpressionException(com.devonfw.cobigen.api.exception.UnknownExpressionException) IOException(java.io.IOException) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) Template(com.devonfw.cobigen.impl.config.entity.Template) Maps(com.google.common.collect.Maps) Increment(com.devonfw.cobigen.impl.config.entity.Increment) SAXParseException(org.xml.sax.SAXParseException) JAXBException(jakarta.xml.bind.JAXBException) TemplateFile(com.devonfw.cobigen.impl.config.entity.TemplateFile) Paths(java.nio.file.Paths) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) InputStream(java.io.InputStream) IncrementRef(com.devonfw.cobigen.impl.config.entity.io.IncrementRef) Template(com.devonfw.cobigen.impl.config.entity.Template) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) TemplateScanRef(com.devonfw.cobigen.impl.config.entity.io.TemplateScanRef) Increment(com.devonfw.cobigen.impl.config.entity.Increment) Increments(com.devonfw.cobigen.impl.config.entity.io.Increments) TemplateRef(com.devonfw.cobigen.impl.config.entity.io.TemplateRef)

Example 4 with Template

use of com.devonfw.cobigen.impl.config.entity.Template 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 5 with Template

use of com.devonfw.cobigen.impl.config.entity.Template in project cobigen by devonfw.

the class TemplatesConfigurationReaderTest method testInvalidTemplateRefOutsideCurrentFile.

/**
 * Tests the correct detection of invalid external increment reference.
 *
 * @throws InvalidConfigurationException expected
 */
@Test(expected = InvalidConfigurationException.class)
public void testInvalidTemplateRefOutsideCurrentFile() {
    Path config = Paths.get(new File(testFileRootPath).toURI());
    new ContextConfigurationReader(config);
    // given
    ConfigurationHolder configurationHolder = new ConfigurationHolder(config.toUri());
    TemplatesConfigurationReader target = new TemplatesConfigurationReader(new File(testFileRootPath).toPath(), "faulty_invalid_external_templateref", configurationHolder);
    Trigger trigger = new Trigger("", "asdf", "", Charset.forName("UTF-8"), new LinkedList<Matcher>(), new LinkedList<ContainerMatcher>());
    // when
    Map<String, Template> templates = target.loadTemplates(trigger);
    target.loadIncrements(templates, trigger);
}
Also used : Path(java.nio.file.Path) ContextConfigurationReader(com.devonfw.cobigen.impl.config.reader.ContextConfigurationReader) ContainerMatcher(com.devonfw.cobigen.impl.config.entity.ContainerMatcher) Matcher(com.devonfw.cobigen.impl.config.entity.Matcher) ConfigurationHolder(com.devonfw.cobigen.impl.config.ConfigurationHolder) Template(com.devonfw.cobigen.impl.config.entity.Template) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) ContainerMatcher(com.devonfw.cobigen.impl.config.entity.ContainerMatcher) TemplatesConfigurationReader(com.devonfw.cobigen.impl.config.reader.TemplatesConfigurationReader) File(java.io.File) AbstractUnitTest(com.devonfw.cobigen.unittest.config.common.AbstractUnitTest) Test(org.junit.Test)

Aggregations

Template (com.devonfw.cobigen.impl.config.entity.Template)26 Trigger (com.devonfw.cobigen.impl.config.entity.Trigger)19 File (java.io.File)17 ContainerMatcher (com.devonfw.cobigen.impl.config.entity.ContainerMatcher)16 Matcher (com.devonfw.cobigen.impl.config.entity.Matcher)16 AbstractUnitTest (com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)16 Test (org.junit.Test)16 TemplatesConfigurationReader (com.devonfw.cobigen.impl.config.reader.TemplatesConfigurationReader)15 InvalidConfigurationException (com.devonfw.cobigen.api.exception.InvalidConfigurationException)5 Increment (com.devonfw.cobigen.impl.config.entity.Increment)5 Path (java.nio.file.Path)5 ConfigurationHolder (com.devonfw.cobigen.impl.config.ConfigurationHolder)4 TemplatePath (com.devonfw.cobigen.impl.config.entity.TemplatePath)4 TextTemplateEngine (com.devonfw.cobigen.api.extension.TextTemplateEngine)3 TemplatesConfiguration (com.devonfw.cobigen.impl.config.TemplatesConfiguration)3 HashMap (java.util.HashMap)3 CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)2 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)2 TemplateFolder (com.devonfw.cobigen.impl.config.entity.TemplateFolder)2 TemplateExtension (com.devonfw.cobigen.impl.config.entity.io.TemplateExtension)2