You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by jd...@apache.org on 2026/10/07 17:26:15 UTC
(grails-core) 02/07: Move the Forge build conventions into build-logic
This is an automated email from the ASF dual-hosted git repository.
jdaugherty pushed a commit to branch feat/forge-grails-composite
in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit e1131ca72e7d4f9a0c8c2444a7772e507f67df9a
Author: James Daugherty <jd...@jdresources.net>
AuthorDate: Wed Oct 7 10:14:14 2026 -0400
Move the Forge build conventions into build-logic
The Forge buildSrc becomes convention plugins and task types of build-logic, as the rest of the
repository's build logic is: the Rocker template compilation plugin, which hands the generated
sources to the Groovy source set for joint compilation where the groovy plugin is applied, the
shadow jar transformers for the Groovy extension modules and the license and notice files, and the
picocli completion, manpage and version-info task types. The Rocker, ANTLR and shadow versions
they need are pinned with the repository's other build tooling versions.
Co-authored-by: James Fredley <ja...@users.noreply.github.com>
---
build-logic/plugins/build.gradle | 9 +
.../buildsrc/WriteGrailsVersionInfoTask.groovy | 106 +++++++++
.../GrailsGroovyExtensionTransformer.groovy | 141 +++++++++++
.../shadowjar/GrailsShadowLicenseTransform.groovy | 265 +++++++++++++++++++++
.../shadowjar/GrailsShadowNoticeTransform.groovy | 45 ++++
.../internal/tasks/GenerateManpageAsciidoc.java | 68 ++++++
.../internal/tasks/PicocliBuildCompletionTask.java | 63 +++++
.../forge/rocker/plugin/JavaGeneratorRunnable.java | 166 +++++++++++++
.../forge/rocker/plugin/RockerConfiguration.java | 99 ++++++++
.../forge/rocker/plugin/RockerGradleException.java | 34 +++
.../grails/forge/rocker/plugin/RockerPlugin.java | 100 ++++++++
.../rocker/plugin/RockerSourceSetProperty.java | 80 +++++++
.../org/grails/forge/rocker/plugin/RockerTask.java | 186 +++++++++++++++
.../forge/rocker/plugin/TemplateDirectorySet.java | 124 ++++++++++
.../forge/rocker/plugin/WhitespaceProcessor.java | 52 ++++
.../buildsrc/WriteGrailsVersionInfoTaskSpec.groovy | 52 ++++
gradle.properties | 5 +
17 files changed, 1595 insertions(+)
diff --git a/build-logic/plugins/build.gradle b/build-logic/plugins/build.gradle
index b440fce8ee..bc257cb2a3 100644
--- a/build-logic/plugins/build.gradle
+++ b/build-logic/plugins/build.gradle
@@ -45,6 +45,11 @@ dependencies {
implementation gradleBomDependencies['asm']
// validateBomProperties reads BOM POMs with Maven's own model, as ExtractDependenciesTask in docs-core does
implementation "org.apache.maven:maven-model:${gradleBomDependencyVersions['maven-model.version']}"
+ // Forge build conventions: the Rocker template compiler behind org.grails.forge.rocker and the
+ // shadow transformers that assemble the grails CLI distribution
+ implementation "com.fizzed:rocker-compiler:${gradleProperties.rockerVersion}"
+ implementation "org.antlr:antlr4-runtime:${gradleProperties.antlr4Version}"
+ implementation "com.gradleup.shadow:shadow-gradle-plugin:${gradleProperties.shadowVersion}"
testImplementation "org.spockframework:spock-core:${gradleBomDependencyVersions['gradle-spock.version']}"
testImplementation gradleTestKit()
@@ -143,5 +148,9 @@ gradlePlugin {
id = 'org.apache.grails.buildsrc.agent-skills'
implementationClass = 'org.apache.grails.buildsrc.AgentSkillsPlugin'
}
+ register('forgeRockerPlugin') {
+ id = 'org.grails.forge.rocker'
+ implementationClass = 'org.grails.forge.rocker.plugin.RockerPlugin'
+ }
}
}
diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/WriteGrailsVersionInfoTask.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/WriteGrailsVersionInfoTask.groovy
new file mode 100644
index 0000000000..5e8a1d16db
--- /dev/null
+++ b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/WriteGrailsVersionInfoTask.groovy
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.buildsrc
+
+import groovy.transform.CompileStatic
+import groovy.xml.XmlSlurper
+import groovy.xml.slurpersupport.GPathResult
+import groovy.xml.slurpersupport.NodeChild
+import org.gradle.api.DefaultTask
+import org.gradle.api.GradleException
+import org.gradle.api.Project
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.model.ObjectFactory
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.CacheableTask
+import org.gradle.api.tasks.Input
+import org.gradle.api.tasks.InputFile
+import org.gradle.api.tasks.OutputDirectories
+import org.gradle.api.tasks.OutputDirectory
+import org.gradle.api.tasks.OutputFile
+import org.gradle.api.tasks.PathSensitive
+import org.gradle.api.tasks.PathSensitivity
+import org.gradle.api.tasks.TaskAction
+import org.xml.sax.SAXException
+
+import javax.inject.Inject
+import javax.xml.parsers.ParserConfigurationException
+import java.nio.charset.StandardCharsets
+import java.nio.file.Files
+
+@CompileStatic
+@CacheableTask
+abstract class WriteGrailsVersionInfoTask extends DefaultTask {
+
+ @Input
+ final Property<String> projectVersion
+
+ @InputFile
+ @PathSensitive(PathSensitivity.RELATIVE)
+ final RegularFileProperty bomPublicationFile
+
+ @OutputDirectory
+ final DirectoryProperty versionsDirectory
+
+ @Inject
+ WriteGrailsVersionInfoTask(ObjectFactory objects, Project project) {
+ projectVersion = objects.property(String).convention(project.provider {
+ project.version as String
+ })
+ bomPublicationFile = objects.fileProperty()
+ versionsDirectory = objects.directoryProperty()
+ }
+
+ @TaskAction
+ void writeVersionInfo() {
+ File versionsDirectory = versionsDirectory.get().asFile
+ if (versionsDirectory.exists()) {
+ versionsDirectory.deleteDir()
+ }
+ versionsDirectory.mkdirs()
+
+ File versions = new File(versionsDirectory, 'grails-versions.properties')
+
+ File pomFile = bomPublicationFile.get().asFile
+
+ GPathResult pom = null
+ try {
+ pom = new XmlSlurper().parse(pomFile)
+ } catch (IOException | SAXException | ParserConfigurationException e) {
+ throw new GradleException("Unable to parse BOM publication file: ${pomFile.absolutePath}", e)
+ }
+
+ TreeMap<String, String> props = []
+ props.put("grails.version", getProjectVersion().get())
+ ((GPathResult) pom.getProperty("properties")).children().forEach(child -> {
+ NodeChild node = (NodeChild) child
+ props.put(node.name(), node.text())
+ })
+
+ try (OutputStream out = Files.newOutputStream(versions.toPath())) {
+ for (Map.Entry<String, String> entry : props.entrySet()) {
+ getLogger().info("Writing version property: {} => {}", entry.getKey(), entry.getValue())
+ String line = "${entry.getKey()}=${entry.getValue()}\n" as String
+ out.write(line.getBytes(StandardCharsets.ISO_8859_1))
+ }
+ }
+ }
+}
diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsGroovyExtensionTransformer.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsGroovyExtensionTransformer.groovy
new file mode 100644
index 0000000000..7833ff584a
--- /dev/null
+++ b/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsGroovyExtensionTransformer.groovy
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.grails.forge.buildlogic.shadowjar
+
+import java.nio.charset.StandardCharsets
+import java.time.LocalDate
+import java.time.ZoneOffset
+import java.util.regex.Pattern
+
+import com.github.jengelman.gradle.plugins.shadow.transformers.Transformer
+import com.github.jengelman.gradle.plugins.shadow.transformers.TransformerContext
+import groovy.transform.CompileStatic
+import org.apache.tools.zip.ZipEntry
+import org.apache.tools.zip.ZipOutputStream
+import org.gradle.api.file.FileTreeElement
+
+/**
+ * Based on com.github.jengelman.gradle.plugins.shadow.transformers.GroovyExtensionModuleTransformer but with
+ * reproducible property file support
+ */
+@CompileStatic
+class GrailsGroovyExtensionTransformer implements Transformer {
+
+ private static final String GROOVY_EXTENSION_MODULE_DESCRIPTOR_PATH = 'META-INF/groovy/org.codehaus.groovy.runtime.ExtensionModule'
+
+ private static final String MODULE_NAME_KEY = 'moduleName'
+ private static final String MODULE_VERSION_KEY = 'moduleVersion'
+ private static final String EXTENSION_CLASSES_KEY = 'extensionClasses'
+ private static final String STATIC_EXTENSION_CLASSES_KEY = 'staticExtensionClasses'
+
+ private static final String MERGED_MODULE_NAME = 'MergedByGrailsShadowJar'
+ private static final String MERGED_MODULE_VERSION = '1.0.0'
+
+ private final Properties module = new Properties()
+
+ @Override
+ boolean canTransformResource(FileTreeElement element) {
+ def path = element.relativePath.pathString
+ path == GROOVY_EXTENSION_MODULE_DESCRIPTOR_PATH
+ }
+
+ @Override
+ void transform(TransformerContext context) {
+ def props = new Properties()
+ props.load(context.is)
+ props.entrySet().each { Map.Entry<Object, Object> entry ->
+ String key = entry.key as String
+ String value = entry.value as String
+ switch (key) {
+ case MODULE_NAME_KEY:
+ handle(key, value) {
+ module.setProperty(key, MERGED_MODULE_NAME)
+ }
+ break
+ case MODULE_VERSION_KEY:
+ handle(key, value) {
+ module.setProperty(key, MERGED_MODULE_VERSION)
+ }
+ break
+ case [EXTENSION_CLASSES_KEY, STATIC_EXTENSION_CLASSES_KEY]:
+ handle(key, value) { String existingValue ->
+ def newValue = "${existingValue},${value}"
+ module.setProperty(key, newValue)
+ }
+ break
+ }
+ }
+ }
+
+ private handle(String key, String value, Closure mergeValue) {
+ def existingValue = module.getProperty(key)
+ if (existingValue) {
+ mergeValue(existingValue)
+ } else {
+ module.setProperty(key, value)
+ }
+ }
+
+ @Override
+ boolean hasTransformedResource() {
+ return module.size() > 0
+ }
+
+ @Override
+ void modifyOutputStream(ZipOutputStream os, boolean preserveFileTimestamps) {
+ ZipEntry entry = new ZipEntry(GROOVY_EXTENSION_MODULE_DESCRIPTOR_PATH)
+ entry.time = TransformerContext.getEntryTimestamp(preserveFileTimestamps, entry.time)
+ os.putNextEntry(entry)
+
+ os.write()
+ try (InputStream inputStream = toInputStream(module)) {
+ inputStream.transferTo(os)
+ }
+ os.closeEntry()
+ }
+
+ private static InputStream toInputStream(Properties props) {
+ def baos = new ByteArrayOutputStream()
+ props.store(baos, null)
+ return makePropertiesOutputReproducible(baos)
+ }
+
+ // Inlined from grails-gradle-common PropertyFileUtils so build-logic does not
+ // depend on grails-gradle (that included build already uses these plugins).
+ private static final Pattern TIME_REGEX = ~'^#(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)(?:,|\\s).*$'
+
+ private static InputStream makePropertiesOutputReproducible(ByteArrayOutputStream propertyOutputStream) {
+ List<String> lines = propertyOutputStream.toString(StandardCharsets.ISO_8859_1.name()).readLines()
+ ByteArrayOutputStream toWrite = new ByteArrayOutputStream()
+ toWrite.withWriter(StandardCharsets.ISO_8859_1.name()) { Writer writer ->
+ BufferedWriter bufferedWriter = new BufferedWriter(writer)
+ String sourceDateEpoch = System.getenv('SOURCE_DATE_EPOCH') ?:
+ LocalDate.now(ZoneOffset.UTC).atStartOfDay(ZoneOffset.UTC).toEpochSecond().toString()
+ boolean dateReplaced = false
+ lines.each { String line ->
+ if (!dateReplaced && TIME_REGEX.matcher(line).matches()) {
+ dateReplaced = true
+ bufferedWriter.writeLine("# SOURCE_DATE_EPOCH = $sourceDateEpoch")
+ return
+ }
+ bufferedWriter.writeLine(line)
+ }
+ bufferedWriter.flush()
+ }
+ new ByteArrayInputStream(toWrite.toByteArray())
+ }
+}
diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsShadowLicenseTransform.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsShadowLicenseTransform.groovy
new file mode 100644
index 0000000000..90898120ba
--- /dev/null
+++ b/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsShadowLicenseTransform.groovy
@@ -0,0 +1,265 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.grails.forge.buildlogic.shadowjar
+
+import com.github.jengelman.gradle.plugins.shadow.transformers.Transformer
+import com.github.jengelman.gradle.plugins.shadow.transformers.TransformerContext
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+import org.apache.tools.zip.ZipEntry
+import org.apache.tools.zip.ZipOutputStream
+import org.gradle.api.file.FileTreeElement
+import org.gradle.api.tasks.Input
+
+import java.util.regex.Pattern
+
+/**
+ * This transformer assists in combining all known licenses into a single META-INF/LICENSE file. Please note that the
+ * shadow plugin will initially copy all dependencies that are in the local project and then it will copy all other external
+ * dependencies. Transformers only apply to the copied jar file dependencies, and not to the local project dependencies.
+ */
+@CompileStatic
+class GrailsShadowLicenseTransform implements Transformer {
+
+ private static final List<Pattern> LICENSE_PATTERNS = [
+ ~'(?i)META-INF/[^/]*LICENSE[^/]*',
+ ~'(?i)META-INF/LICENSES/.*',
+ ~'(?i)[^/]*LICENSE[^/]*',
+ ~'(?i)LICENSES/.*'
+ ]
+
+ private static final String LICENSE_PATH = 'META-INF/LICENSE'
+
+ private LinkedHashMap<String, LicenseHolder> licenses = [:]
+
+ @Input
+ String licenseAppendixEnding = 'LIMITATIONS UNDER THE LICENSE.'
+
+ @Input
+ String licenseTermsEnding = 'END OF TERMS AND CONDITIONS'
+
+ @Input
+ String licenseTermsStart = 'APACHE LICENSE VERSION 2.0'
+
+ @Input
+ String licenseText // to be loaded by file
+
+ @Input
+ Boolean separators = false
+
+ /**
+ * Whether this transformer can process the given resource. If set to true, it's expected the transformer will
+ * write the resource.
+ */
+ @Override
+ boolean canTransformResource(FileTreeElement element) {
+ def path = element.relativePath.pathString
+ LICENSE_PATTERNS.any { pattern -> pattern.matcher(path).matches() }
+ }
+
+ /**
+ * Parses any file that matches the license patterns and extracts the license text, deduplicating & combining where
+ * possible.
+ *
+ * @param context contains the input stream of the resource to transform
+ */
+ @Override
+ // Multiple assignments without list expressions on the right hand side are unsupported in static type checking mode
+ @CompileDynamic
+ void transform(TransformerContext context) {
+ if (!licenses) {
+ // Add our license as previously seen so we can dedupe - this transformer only applies to the copy of other jars
+ def (grailsLicense, grailsIndexMappings) = normalize(licenseText)
+ licenses[grailsLicense] = new LicenseHolder(license: licenseText, indexMappings: grailsIndexMappings)
+ }
+
+ context.is.withReader {
+ BufferedReader reader = new BufferedReader(it)
+
+ def license = stripJavaBlockComment(reader.text)
+ def (String normalized, List<Integer> indexMappings) = normalize(license)
+
+ // resect Apache License
+ String resected = resectLicense(license, normalized, indexMappings)
+ if (!resected.trim()) {
+ return // only contained duplicated license terms with the ASF license
+ }
+
+ def (String resectedNormalized, List<Integer> resectedIndexMappings) = normalize(resected)
+ def previouslySeen = getVariations(resectedNormalized).any { licenses.containsKey(it) }
+ if (!previouslySeen) {
+ licenses[resectedNormalized] = new LicenseHolder(license: resected, indexMappings: resectedIndexMappings)
+ }
+ }
+ }
+
+ /**
+ * Some libraries ship with a license.header file that contains a Java block comment. This method strips the
+ * Java block comment syntax and returns the text without the comment.
+ */
+ private static String stripJavaBlockComment(String text) {
+ if (!text.startsWith('/*')) {
+ return text
+ }
+
+ return text
+ .replaceAll('^/\\*+|\\*+/\\s*$', '') // opening & closing comment
+ .readLines()
+ .collect {
+ it.replaceFirst(/^(\s*\*)?/, '').trim()
+ } // leading whitespace & *
+ .join('\n')
+ }
+
+ /**
+ * Normalizes the license text by collapsing whitespace and uppercasing all characters. It also returns a mapping
+ * of the normalized text to the original license text, where each character in the normalized text maps to its
+ * original index in the license text. This allows us to index into the normalized text from sections of the license text
+ * for deduplication purposes.
+ *
+ * @param license the original license text
+ * @return a tuple containing the normalized license text and a list of index mappings
+ */
+ private static Tuple2<String, List<Integer>> normalize(String license) {
+ def sb = new StringBuilder()
+ List<Integer> indexMappings = [] // each char in sb maps to original index
+
+ boolean previousWhitespace = false
+ for (int i = 0; i < license.length(); i++) {
+ char c = license.charAt(i)
+ if (c.isWhitespace()) {
+ if (!previousWhitespace) {
+ sb.append(' ')
+ indexMappings << i
+ previousWhitespace = true
+ }
+ } else {
+ sb.append(Character.toUpperCase(c))
+ indexMappings << i
+ previousWhitespace = false
+ }
+ }
+
+ String normalized = sb.toString().trim()
+ int startTrim = sb.indexOf(normalized)
+ int endTrim = startTrim + normalized.length()
+ new Tuple2<String, List<Integer>>(normalized, indexMappings[startTrim..<endTrim])
+ }
+
+ /**
+ * For a given license, this method will extract the duplicate license text and return the remaining text
+ * @param license the original license text
+ * @param normalized a normalized version of the license text, with all whitespace collapsed and all characters uppercased
+ * @param indexMappings a mapping of the normalized text to the original license text, where each character in the normalized text maps to its original index in the license text
+ * @return either null if no additional license text was found or the additional license text
+ */
+ private String resectLicense(String license, String normalized, List<Integer> indexMappings) {
+ if (!normalized.startsWith(licenseTermsStart.toUpperCase())) {
+ return license // not ASF license, return as is
+ }
+
+ // try to search on the appendix first
+ String endOfLicenseMarker = normalize(licenseAppendixEnding).v1
+ int end1Index = normalized.indexOf(endOfLicenseMarker)
+ if (end1Index >= 0) {
+ // license included the appendix
+ def originalEnding = indexMappings[end1Index + endOfLicenseMarker.size() - 1] + 1
+ if (originalEnding > license.length()) {
+ // only the license is present
+ return null
+ }
+
+ return license.substring(originalEnding)
+ }
+
+ // try to search on the terms ending
+ String endMarker = normalize(licenseTermsEnding).v1
+ int end2Index = normalized.indexOf(endMarker)
+ if (end2Index >= 0) {
+ // bare license
+ def originalEnding = indexMappings[end2Index + endMarker.size() - 1] + 1
+ if (originalEnding > license.length()) {
+ // only the license is present
+ return null
+ }
+
+ return license.substring(originalEnding)
+ }
+
+ license
+ }
+
+ /**
+ * Some licenses mix http & https links, handles simple variations of the license to ensure the license can be
+ * deduplicated.
+ *
+ * @param license the license text
+ * @return a list of variations of the license text
+ */
+ private static List<String> getVariations(String license) {
+ [license.trim()].collectMany {
+ [it, it.replace('http://', 'https://'), it.replace('https://', 'http://')]
+ }
+ }
+
+ /**
+ * Whether this transformer will modify the output stream.
+ */
+ @Override
+ boolean hasTransformedResource() {
+ // Must always be true since we want to write the LICENSE file and all license files originate from jar files
+ // after our project restructure
+ true
+ }
+
+ /**
+ * Writes the combined license file to the output stream. The file will be written to
+ * META-INF/LICENSE and will contain all licenses found in the project
+ *
+ * @param os the jar file output stream
+ * @param preserveFileTimestamps whether to preserve file timestamps in the output jar
+ */
+ @Override
+ void modifyOutputStream(ZipOutputStream os, boolean preserveFileTimestamps) {
+ ZipEntry zipEntry = new ZipEntry(LICENSE_PATH)
+ zipEntry.time = TransformerContext.getEntryTimestamp(preserveFileTimestamps, zipEntry.time)
+ os.putNextEntry(zipEntry)
+
+ os.withPrintWriter { writer ->
+ licenses.entrySet().withIndex().each { license ->
+ if (license.v1.value == null) {
+ return // skip the license that will be copied by shadow from our existing jars
+ }
+
+ writer.println(license.v1.value.license)
+ if (separators && license.v2 < licenses.size() - 1) {
+ writer.println("-------------------------${license.v2}---------------------------")
+ }
+ }
+
+ writer.flush()
+ }
+
+ licenses = [:]
+ }
+
+ private static class LicenseHolder {
+
+ String license
+ List<Integer> indexMappings
+ }
+}
\ No newline at end of file
diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsShadowNoticeTransform.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsShadowNoticeTransform.groovy
new file mode 100644
index 0000000000..a4b7dded9c
--- /dev/null
+++ b/build-logic/plugins/src/main/groovy/org/apache/grails/forge/buildlogic/shadowjar/GrailsShadowNoticeTransform.groovy
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.grails.forge.buildlogic.shadowjar
+
+import com.github.jengelman.gradle.plugins.shadow.transformers.ApacheNoticeResourceTransformer
+import groovy.transform.CompileStatic
+import org.gradle.api.file.FileTreeElement
+
+import java.util.regex.Pattern
+
+/**
+ * jakarta is eclipse licensed, so we need to include the NOTICE.md file
+ */
+@CompileStatic
+class GrailsShadowNoticeTransform extends ApacheNoticeResourceTransformer {
+
+ private static final List<Pattern> NOTICE_PATTERNS = [
+ ~'(?i)META-INF/[^/]*NOTICE[^/]*',
+ ~'(?i)[^/]*NOTICE[^/]*'
+ ]
+
+ @Override
+ boolean canTransformResource(FileTreeElement element) {
+ if (super.canTransformResource(element)) {
+ return true
+ }
+
+ def path = element.relativePath.pathString
+ NOTICE_PATTERNS.any { pattern -> pattern.matcher(path).matches() }
+ }
+}
diff --git a/build-logic/plugins/src/main/groovy/org/grails/forge/internal/tasks/GenerateManpageAsciidoc.java b/build-logic/plugins/src/main/groovy/org/grails/forge/internal/tasks/GenerateManpageAsciidoc.java
new file mode 100644
index 0000000000..9516d7763e
--- /dev/null
+++ b/build-logic/plugins/src/main/groovy/org/grails/forge/internal/tasks/GenerateManpageAsciidoc.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.forge.internal.tasks;
+
+import org.gradle.api.DefaultTask;
+import org.gradle.api.file.ConfigurableFileCollection;
+import org.gradle.api.file.DirectoryProperty;
+import org.gradle.api.provider.Property;
+import org.gradle.api.tasks.CacheableTask;
+import org.gradle.api.tasks.Classpath;
+import org.gradle.api.tasks.Input;
+import org.gradle.api.tasks.OutputDirectory;
+import org.gradle.api.tasks.TaskAction;
+import org.gradle.process.ExecOperations;
+
+import javax.inject.Inject;
+
+@CacheableTask
+public abstract class GenerateManpageAsciidoc extends DefaultTask {
+
+ @Input
+ public abstract Property<String> getMainClass();
+
+ @Classpath
+ public abstract ConfigurableFileCollection getClasspath();
+
+ @OutputDirectory
+ public abstract DirectoryProperty getOutputDirectory();
+
+ @Inject
+ protected abstract ExecOperations getExecOperations();
+
+ public GenerateManpageAsciidoc() {
+ setGroup("Documentation");
+ setDescription("Generate AsciiDoc manpage");
+ }
+
+ @TaskAction
+ void generate() {
+ getExecOperations().javaexec(spec -> {
+ spec.getMainClass().set("picocli.codegen.docgen.manpage.ManPageGenerator");
+ spec.setClasspath(getClasspath());
+ spec.args(
+ "--outdir=" + getOutputDirectory().getAsFile().get(),
+ "-v",
+ "--factory=org.grails.forge.cli.GrailsPicocliFactory",
+ //, "--template-dir=src/docs/mantemplates"
+ getMainClass().get()
+ );
+ });
+ }
+}
diff --git a/build-logic/plugins/src/main/groovy/org/grails/forge/internal/tasks/PicocliBuildCompletionTask.java b/build-logic/plugins/src/main/groovy/org/grails/forge/internal/tasks/PicocliBuildCompletionTask.java
new file mode 100644
index 0000000000..5125d6fa16
--- /dev/null
+++ b/build-logic/plugins/src/main/groovy/org/grails/forge/internal/tasks/PicocliBuildCompletionTask.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.forge.internal.tasks;
+
+import org.gradle.api.DefaultTask;
+import org.gradle.api.file.ConfigurableFileCollection;
+import org.gradle.api.file.DirectoryProperty;
+import org.gradle.api.provider.Property;
+import org.gradle.api.tasks.CacheableTask;
+import org.gradle.api.tasks.Classpath;
+import org.gradle.api.tasks.Input;
+import org.gradle.api.tasks.OutputDirectory;
+import org.gradle.api.tasks.TaskAction;
+import org.gradle.process.ExecOperations;
+
+import javax.inject.Inject;
+
+@CacheableTask
+public abstract class PicocliBuildCompletionTask extends DefaultTask {
+ @Input
+ public abstract Property<String> getMainClass();
+
+ @Classpath
+ public abstract ConfigurableFileCollection getClasspath();
+
+ @OutputDirectory
+ public abstract DirectoryProperty getOutputDirectory();
+
+ @Inject
+ protected abstract ExecOperations getExecOperations();
+
+ @TaskAction
+ public void execute() {
+ getExecOperations().javaexec(spec -> {
+ spec.setClasspath(getClasspath());
+ spec.getMainClass().set("picocli.AutoComplete");
+ spec.jvmArgs("-Dpicocli.autocomplete.systemExitOnError");
+ spec.args(
+ getMainClass().get(),
+ "--completionScript=" + getOutputDirectory().file("grails_forge_cli_completion").get().getAsFile().getAbsolutePath(),
+ "--force",
+ "--factory=org.grails.forge.cli.GrailsPicocliFactory"
+ );
+ });
+ }
+
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/JavaGeneratorRunnable.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/JavaGeneratorRunnable.java
new file mode 100644
index 0000000000..4b6e889c98
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/JavaGeneratorRunnable.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+import com.fizzed.rocker.compiler.GeneratorException;
+import com.fizzed.rocker.compiler.JavaGenerator;
+import com.fizzed.rocker.compiler.JavaGeneratorMain;
+import com.fizzed.rocker.compiler.PlainTextStrategy;
+import com.fizzed.rocker.compiler.RockerConfiguration;
+import com.fizzed.rocker.compiler.RockerUtil;
+import com.fizzed.rocker.compiler.TemplateParser;
+import com.fizzed.rocker.model.TemplateModel;
+import com.fizzed.rocker.runtime.ParserException;
+import com.fizzed.rocker.runtime.RockerRuntime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+public class JavaGeneratorRunnable implements Runnable {
+
+ private static final Logger log = LoggerFactory.getLogger(JavaGeneratorMain.class);
+
+ private final com.fizzed.rocker.compiler.RockerConfiguration configuration;
+ private final TemplateParser parser;
+ private final JavaGenerator generator;
+ private final List<File> templateFiles;
+ private String suffixRegex;
+ private boolean failOnError;
+
+ public JavaGeneratorRunnable() {
+ this.configuration = new RockerConfiguration();
+ this.parser = new TemplateParser(this.configuration);
+ this.generator = new JavaGenerator(this.configuration);
+ this.generator.setPlainTextStrategy(PlainTextStrategy.STATIC_STRINGS);
+ this.templateFiles = new ArrayList<>();
+ this.suffixRegex = ".*\\.rocker\\.(raw|html)$";
+ this.failOnError = true;
+ }
+
+ public String getSuffixRegex() {
+ return suffixRegex;
+ }
+
+ public void setSuffixRegex(String suffixRegex) {
+ this.suffixRegex = suffixRegex;
+ }
+
+ public boolean isFailOnError() {
+ return failOnError;
+ }
+
+ public void setFailOnError(boolean failOnError) {
+ this.failOnError = failOnError;
+ }
+
+ public TemplateParser getParser() {
+ return parser;
+ }
+
+ public JavaGenerator getGenerator() {
+ return generator;
+ }
+
+ public void run() throws RuntimeException{
+ if (this.configuration.getTemplateDirectory() == null) {
+ throw new RuntimeException("Template directory was null");
+ }
+
+ if (!this.configuration.getTemplateDirectory().exists() || !this.configuration.getTemplateDirectory().isDirectory()) {
+ throw new RuntimeException("Template directory does not exist: " + this.configuration.getTemplateDirectory());
+ }
+
+ // loop thru template directory and match templates
+ Collection<File> allFiles = RockerUtil.listFileTree(this.configuration.getTemplateDirectory());
+ for (File f : allFiles) {
+ if (f.getName().matches(suffixRegex)) {
+ templateFiles.add(f);
+ }
+ }
+
+ log.info("Parsing " + templateFiles.size() + " rocker template files");
+
+ int errors = 0;
+ int generated = 0;
+
+ for (File f : templateFiles) {
+ TemplateModel model = null;
+
+ try {
+ // parse model
+ model = parser.parse(f);
+ } catch (IOException | ParserException e) {
+ if (e instanceof ParserException) {
+ ParserException pe = (ParserException) e;
+ log.error("Parsing failed for " + f + ":[" + pe.getLineNumber() + "," + pe.getColumnNumber() + "] " + pe.getMessage());
+ } else {
+ log.error("Unable to parse template", e);
+ }
+ errors++;
+ }
+
+ try {
+ File outputFile = generator.generate(model);
+ generated++;
+
+ log.debug("Generated java source: " + outputFile);
+ } catch (GeneratorException | IOException e) {
+ throw new RuntimeException("Generating java source failed for " + f + ": " + e.getMessage(), e);
+ }
+
+ }
+
+ log.info("Generated " + generated + " rocker java source files");
+
+ if (errors > 0 && failOnError) {
+ throw new RuntimeException("Caught " + errors + " errors.");
+ }
+
+ if (!configuration.getOptions().getOptimize()) {
+ // save configuration
+ this.configuration.getClassDirectory().mkdirs();
+
+ // use resource name, but strip leading slash
+ // place it into the classes directory (not the compile directory)
+ try{
+ File configFile = new File(this.configuration.getClassDirectory(), RockerRuntime.CONF_RESOURCE_NAME.substring(1));
+ this.configuration.write(configFile);
+ log.info("Generated rocker configuration " + configFile);
+ }catch(IOException iox){
+ throw new RuntimeException(iox);
+ }
+ } else {
+ log.info("Optimize flag on. Did not generate rocker configuration file");
+ }
+ }
+
+ public void setTemplateDirectory(File templateDirectory) {
+ this.parser.getConfiguration().setTemplateDirectory(templateDirectory);
+ }
+
+ public void setOutputDirectory(File outputDirectory) {
+ this.generator.getConfiguration().setOutputDirectory(outputDirectory);
+ }
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerConfiguration.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerConfiguration.java
new file mode 100644
index 0000000000..09583504b8
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerConfiguration.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+import com.fizzed.rocker.model.JavaVersion;
+import org.gradle.api.file.DirectoryProperty;
+import org.gradle.api.provider.ListProperty;
+import org.gradle.api.provider.Property;
+import org.gradle.api.tasks.Input;
+import org.gradle.api.tasks.Internal;
+import org.gradle.api.tasks.Optional;
+
+/**
+ * Bean for the configuration options of Rocker Compiler
+ */
+public abstract class RockerConfiguration {
+ private String[] postProcessing;
+ private Boolean markAsGenerated;
+
+ public RockerConfiguration() {
+ getSkip().convention(false);
+ getFailOnError().convention(true);
+ getSkipTouch().convention(true);
+ getJavaVersion().convention(JavaVersion.current());
+ getOptimize().convention(true);
+ getDiscardLogicWhitespace().convention(true);
+ }
+
+ @Internal
+ public abstract Property<Boolean> getSkip();
+
+ @Internal
+ public abstract Property<Boolean> getFailOnError();
+
+ @Internal
+ public abstract Property<Boolean> getSkipTouch();
+
+ @Optional
+ @Input
+ public abstract Property<String> getTouchFile();
+
+ @Input
+ public abstract Property<String> getJavaVersion();
+
+ @Optional
+ @Input
+ public abstract Property<String> getExtendsClass();
+
+ @Optional
+ @Input
+ public abstract Property<String> getExtendsModelClass();
+
+ @Optional
+ @Input
+ public abstract Property<Boolean> getOptimize();
+
+ @Optional
+ @Input
+ public abstract Property<Boolean> getDiscardLogicWhitespace();
+
+ @Optional
+ @Input
+ public abstract Property<String> getTargetCharset();
+
+ @Optional
+ @Input
+ public abstract Property<String> getSuffixRegex();
+
+ @Internal
+ public abstract DirectoryProperty getOutputBaseDirectory();
+
+ @Internal
+ public abstract DirectoryProperty getClassBaseDirectory();
+
+ @Optional
+ @Input
+ public abstract ListProperty<String> getPostProcessing();
+
+ @Optional
+ @Input
+ public abstract Property<Boolean> getMarkAsGenerated();
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerGradleException.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerGradleException.java
new file mode 100644
index 0000000000..85b879ff51
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerGradleException.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+/**
+ * Named RuntimeException
+ */
+@SuppressWarnings("serial")
+public class RockerGradleException extends RuntimeException {
+ public RockerGradleException(String msg) {
+ super(msg);
+ }
+
+ public RockerGradleException(String msg, Exception e) {
+ super(msg, e);
+ }
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerPlugin.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerPlugin.java
new file mode 100644
index 0000000000..0c861313a7
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerPlugin.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+import org.gradle.api.Plugin;
+import org.gradle.api.Project;
+import org.gradle.api.plugins.ExtensionAware;
+import org.gradle.api.plugins.JavaLibraryPlugin;
+import org.gradle.api.plugins.JavaPluginExtension;
+import org.gradle.api.tasks.SourceSet;
+import org.gradle.api.tasks.GroovySourceDirectorySet;
+import org.gradle.api.tasks.SourceSetContainer;
+import org.gradle.api.tasks.TaskProvider;
+
+/**
+ * A plugin that for gradle that provides the `generateRockerTemplateSource`
+ * tasks.
+ */
+public class RockerPlugin implements Plugin<Project> {
+ /**
+ * Create `rockerCompile` task in group build and describe the task
+ *
+ * @param project - gradle project
+ */
+ @Override
+ public void apply(Project project) {
+ // Make sure that we have the objects from the java task available
+ project.getPluginManager().apply(JavaLibraryPlugin.class);
+
+ // Create own project extension (configuration)
+ RockerConfiguration rockerConfig = project.getExtensions().create("rocker", RockerConfiguration.class);
+ rockerConfig.getOutputBaseDirectory().convention(
+ project.getLayout().getBuildDirectory().dir("generated-src/rocker")
+ );
+ rockerConfig.getClassBaseDirectory().convention(
+ project.getLayout().getBuildDirectory().dir("classes")
+ );
+
+ // Create own source set extension using the modern JavaPluginExtension API
+ SourceSetContainer sourceSets = project.getExtensions()
+ .getByType(JavaPluginExtension.class).getSourceSets();
+ sourceSets.all(sourceSet -> processSourceSet(project, sourceSet, rockerConfig));
+
+ }
+
+ private static void processSourceSet(Project project, SourceSet sourceSet,
+ RockerConfiguration rockerConfig) {
+ // for each source set we will:
+ // 1) Add a new 'rocker' extension to the source set
+ RockerSourceSetProperty rockerProperty
+ = new RockerSourceSetProperty(project);
+ ((ExtensionAware) sourceSet).getExtensions().add(
+ "rocker", rockerProperty);
+
+ // 2) Create a rocker task for this sourceSet following the gradle
+ // naming conventions
+ String taskName = sourceSet.getTaskName(
+ "generate", "RockerTemplateSource");
+ TaskProvider<RockerTask> rockerTaskProvider = project.getTasks().register(taskName, RockerTask.class, rockerTask -> {
+ rockerTask.setGroup("build");
+ rockerTask.setDescription("Generate Sources from "
+ + sourceSet.getName() + " Rocker Templates");
+ rockerTask.getRockerProjectConfig().set(rockerConfig);
+ rockerTask.getOutputDir().convention(
+ rockerConfig.getOutputBaseDirectory().dir(sourceSet.getName())
+ );
+ rockerTask.getClassDir().convention(
+ rockerConfig.getClassBaseDirectory().dir(sourceSet.getName())
+ );
+ rockerTask.getTemplateDirs().from(rockerProperty.getRocker().getSrcDirs());
+ });
+
+ // The generated Java references the template models, which are Groovy classes in the Forge
+ // modules, and the Groovy code references the generated templates, so the generated sources are
+ // joint-compiled with the Groovy sources when the Groovy plugin is applied
+ if (project.getPluginManager().hasPlugin("groovy")) {
+ sourceSet.getExtensions().getByType(GroovySourceDirectorySet.class).srcDir(rockerTaskProvider);
+ } else {
+ sourceSet.getJava().srcDir(rockerTaskProvider);
+ }
+ }
+
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerSourceSetProperty.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerSourceSetProperty.java
new file mode 100644
index 0000000000..5aef586e2b
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerSourceSetProperty.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+import groovy.lang.Closure;
+import org.gradle.api.Action;
+import org.gradle.api.Project;
+import org.gradle.api.tasks.SourceSet;
+import org.gradle.util.internal.ClosureBackedAction;
+
+import java.io.File;
+import java.util.Set;
+
+/**
+ * The rocker property added to the {@link SourceSet}.
+ */
+public class RockerSourceSetProperty {
+
+ private final TemplateDirectorySet templateDirs;
+
+ /**
+ * @param project - main gradle project
+ */
+ public RockerSourceSetProperty(Project project) {
+ super();
+ templateDirs = new TemplateDirectorySet(project);
+ }
+
+ public TemplateDirectorySet getRocker() {
+ return templateDirs;
+ }
+
+ public RockerSourceSetProperty rocker(Closure<?> configureClosure) {
+ new ClosureBackedAction<>(configureClosure).execute(getRocker());
+ return this;
+ }
+
+ public RockerSourceSetProperty rocker(
+ Action<? super TemplateDirectorySet> configureAction) {
+ configureAction.execute(getRocker());
+ return this;
+ }
+
+ // Delegate methods to TemplateDirectorySet for DSL compatibility
+ public RockerSourceSetProperty srcDir(Object srcDir) {
+ templateDirs.srcDir(srcDir);
+ return this;
+ }
+
+ public RockerSourceSetProperty srcDirs(Object... srcDirs) {
+ templateDirs.srcDirs(srcDirs);
+ return this;
+ }
+
+ public RockerSourceSetProperty setSrcDirs(Iterable<?> srcPaths) {
+ templateDirs.setSrcDirs(srcPaths);
+ return this;
+ }
+
+ public Set<File> getSrcDirs() {
+ return templateDirs.getSrcDirs();
+ }
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerTask.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerTask.java
new file mode 100644
index 0000000000..218b1d1a59
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/RockerTask.java
@@ -0,0 +1,186 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+import com.fizzed.rocker.compiler.RockerOptions;
+import org.gradle.api.DefaultTask;
+import org.gradle.api.file.ConfigurableFileCollection;
+import org.gradle.api.file.DirectoryProperty;
+import org.gradle.api.file.FileSystemOperations;
+import org.gradle.api.logging.Logger;
+import org.gradle.api.provider.Property;
+import org.gradle.api.tasks.CacheableTask;
+import org.gradle.api.tasks.Classpath;
+import org.gradle.api.tasks.InputFiles;
+import org.gradle.api.tasks.Nested;
+import org.gradle.api.tasks.OutputDirectory;
+import org.gradle.api.tasks.PathSensitive;
+import org.gradle.api.tasks.PathSensitivity;
+import org.gradle.api.tasks.TaskAction;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+import javax.inject.Inject;
+
+@CacheableTask
+public abstract class RockerTask extends DefaultTask {
+
+
+ /**
+ * @return the config
+ */
+ @Nested
+ public abstract Property<RockerConfiguration> getRockerProjectConfig();
+
+ /**
+ * @return the templateDirs
+ */
+ @InputFiles
+ @PathSensitive(PathSensitivity.RELATIVE)
+ public abstract ConfigurableFileCollection getTemplateDirs();
+
+ /**
+ * @return the outputDir
+ */
+ @OutputDirectory
+ public abstract DirectoryProperty getOutputDir();
+
+ @Classpath
+ public abstract DirectoryProperty getClassDir();
+
+ @Inject
+ protected abstract FileSystemOperations getFileSystemOperations();
+
+ /**
+ * Sets up the logger and runs the rocker compiler
+ */
+ @TaskAction
+ public void compileRocker() {
+ RockerConfiguration ext = (RockerConfiguration)
+ getProject().getExtensions().findByName("rocker");
+ File outputDir = getOutputDir().get().getAsFile();
+ // Rocker only writes files, so remove sources generated from templates that no longer exist
+ getFileSystemOperations().delete(spec -> spec.delete(outputDir));
+ Set<File> templateDirs = getTemplateDirs().getFiles();
+ for (File templateDir : templateDirs) {
+ doCompileRocker(ext, getLogger(), templateDir, outputDir, getClassDir().get().getAsFile());
+ }
+ }
+
+ /**
+ * Uses the project to get GradleExtension and runs the generator
+ */
+ public static void doCompileRocker(RockerConfiguration ext,
+ Logger logger,
+ File templateDir, File outputDir, File classDir) {
+
+ runJavaGeneratorMain(ext, logger, templateDir, outputDir, classDir);
+ }
+
+ /**
+ * Run the Rocker compiler with the RockerGradleExtension as configuration
+ * options.
+ *
+ * @param ext the extension from the project object
+ */
+ private static void runJavaGeneratorMain(RockerConfiguration ext,
+ Logger logger,
+ File templateDir, File outputDir, File classDir) {
+ if (ext.getSkip().get()) {
+ logger.info("Skip flag is on, will skip goal.");
+ return;
+ }
+
+ logger.info("Targeting java version " + ext.getJavaVersion().get());
+
+ try {
+ JavaGeneratorRunnable jgm = new JavaGeneratorRunnable();
+
+ jgm.getParser().getConfiguration().setTemplateDirectory(templateDir);
+ jgm.getGenerator().getConfiguration().setOutputDirectory(outputDir);
+ jgm.getGenerator().getConfiguration().setClassDirectory(classDir);
+ jgm.setFailOnError(ext.getFailOnError().get());
+
+ // passthru other config
+ if (ext.getSuffixRegex().isPresent()) {
+ jgm.setSuffixRegex(ext.getSuffixRegex().get());
+ }
+ RockerOptions rockerOptions = jgm.getParser().getConfiguration().getOptions();
+ rockerOptions.setJavaVersion(ext.getJavaVersion().get());
+ if (ext.getExtendsClass().isPresent()) {
+ rockerOptions.setExtendsClass(ext.getExtendsClass().get());
+ }
+ if (ext.getExtendsModelClass().isPresent()) {
+ rockerOptions.setExtendsModelClass(ext.getExtendsModelClass().get());
+ }
+ if (ext.getDiscardLogicWhitespace().isPresent()) {
+ rockerOptions.setDiscardLogicWhitespace(ext.getDiscardLogicWhitespace().get());
+ }
+ if (ext.getTargetCharset().isPresent()) {
+ rockerOptions.setTargetCharset(ext.getTargetCharset().get());
+ }
+ if (ext.getOptimize().isPresent()) {
+ rockerOptions.setOptimize(ext.getOptimize().get());
+ }
+ if (ext.getPostProcessing().isPresent()) {
+ List<String> postProcessing = ext.getPostProcessing().get();
+ if (!postProcessing.isEmpty()) {
+ rockerOptions.setPostProcessing(postProcessing.toArray(new String[0]));
+ }
+ }
+ if (ext.getMarkAsGenerated().isPresent()) {
+ rockerOptions.setMarkAsGenerated(ext.getMarkAsGenerated().get());
+ }
+
+ jgm.run();
+
+ } catch (Exception e) {
+ throw new RockerGradleException(e.getMessage(), e);
+ }
+
+ if (!ext.getSkipTouch().get()) {
+ String touchFile = ext.getTouchFile().orElse("").get();
+ if (touchFile.length() == 0) {
+ throw new RockerGradleException(
+ "If skipTouch is equal to false, then "
+ + "touchFile must not be empty");
+ }
+ if (ext.getTouchFile().isPresent()) {
+ File f = new File(touchFile);
+ logger.info("Touching file " + f);
+ try {
+ if (!f.exists()) {
+ new FileOutputStream(f).close();
+ }
+ if (!f.setLastModified(System.currentTimeMillis())) {
+ throw new IOException("Could not set Last Modified");
+ }
+ } catch (IOException e) {
+ logger.debug("Unable to touch file: " + f.getAbsolutePath(), e);
+ }
+ }
+ }
+ }
+
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/TemplateDirectorySet.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/TemplateDirectorySet.java
new file mode 100644
index 0000000000..2ce6084ed1
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/TemplateDirectorySet.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+import org.gradle.api.PathValidation;
+import org.gradle.api.Project;
+import org.gradle.api.tasks.SourceSet;
+import org.gradle.api.tasks.util.PatternFilterable;
+
+import java.io.File;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A simplified version of {@link SourceSet}. Gradle's {@link SourceSet}
+ * inherits from {@link PatternFilterable}, but rocker works on complete
+ * directories. So instead of using {@link SourceSet} and allowing
+ * the user to specify filters without any effect, this simplified
+ * source set implementation is used.
+ * <P>
+ * It would be tempting to provide e.g. {@code templateDir} instead of
+ * {@code srcDir}, but this would break established use and templates are
+ * the source in this context.
+ */
+public class TemplateDirectorySet {
+ private Project project;
+ private final Set<File> templateDirs = new HashSet<>();
+
+ /**
+ * Create a new instance. The project is used to immediately check
+ * (with {@code project.file()} the validity of added directories.
+ *
+ * @param project the project
+ */
+ public TemplateDirectorySet(Project project) {
+ super();
+ this.project = project;
+ }
+
+ /**
+ * Adds the given source directory to this set.
+ *
+ * @param srcDir the directory
+ * @return the template set for easy chaining
+ */
+ public TemplateDirectorySet srcDir(Object srcDir) {
+ templateDirs.add(project.file(srcDir, PathValidation.DIRECTORY));
+ return this;
+ }
+
+ /**
+ * Adds the given source directories to this set.
+ *
+ * @param srcDirs the directories
+ * @return the template set for easy chaining
+ */
+ public TemplateDirectorySet srcDirs(Object... srcDirs) {
+ for (Object srcDir : srcDirs) {
+ srcDir(srcDir);
+ }
+ return this;
+ }
+
+ /**
+ * Sets the source directories for this set.
+ *
+ * @param srcPaths the source directories
+ * @return the template set for easy chaining
+ */
+ public TemplateDirectorySet setSrcDirs(Iterable<?> srcPaths) {
+ templateDirs.clear();
+ srcPaths.forEach(this::srcDir);
+ return this;
+ }
+
+ /**
+ * Adds the given source to this set.
+ *
+ * @param source the source
+ * @return the template set for easy chaining
+ */
+ public TemplateDirectorySet source(TemplateDirectorySet source) {
+ source.getSrcDirs().forEach(this::srcDir);
+ return this;
+ }
+
+ /**
+ * Returns the source directories that make up this set.
+ *
+ * @return the directories
+ */
+ public Set<File> getSrcDirs() {
+ return templateDirs;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("TemplateDirectorySet [");
+ if (!templateDirs.isEmpty()) {
+ builder.append("templateDirs=");
+ builder.append(templateDirs);
+ }
+ builder.append("]");
+ return builder.toString();
+ }
+}
diff --git a/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/WhitespaceProcessor.java b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/WhitespaceProcessor.java
new file mode 100644
index 0000000000..a24f929dfc
--- /dev/null
+++ b/build-logic/plugins/src/main/java/org/grails/forge/rocker/plugin/WhitespaceProcessor.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.forge.rocker.plugin;
+
+import com.fizzed.rocker.model.PlainText;
+import com.fizzed.rocker.model.PostProcessorException;
+import com.fizzed.rocker.model.TemplateModel;
+import com.fizzed.rocker.model.TemplateModelPostProcessor;
+import com.fizzed.rocker.model.TemplateUnit;
+
+import java.util.List;
+
+public class WhitespaceProcessor implements TemplateModelPostProcessor {
+
+ @Override
+ public TemplateModel process(TemplateModel templateModel, int ppIndex) throws PostProcessorException {
+ List<TemplateUnit> units = templateModel.getUnits();
+ int length = units.size();
+ PlainText lastPlainText = null;
+ for (int i = 0; i < length; i ++) {
+ TemplateUnit tu = units.get(i);
+ if (tu instanceof PlainText) {
+ PlainText pt = (PlainText)tu;
+ if ((lastPlainText == null || lastPlainText.getText().endsWith("\n")) && pt.getText().startsWith("\n")) {
+ PlainText replacementPt = new PlainText(pt.getSourceRef(), pt.getText().substring(1));
+ // replace the unit
+ units.add(i, replacementPt);
+ units.remove(i + 1);
+ }
+ lastPlainText = pt;
+ }
+ }
+ return templateModel;
+ }
+}
diff --git a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/WriteGrailsVersionInfoTaskSpec.groovy b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/WriteGrailsVersionInfoTaskSpec.groovy
new file mode 100644
index 0000000000..daa72975c1
--- /dev/null
+++ b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/WriteGrailsVersionInfoTaskSpec.groovy
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.buildsrc
+
+import org.gradle.api.GradleException
+import org.gradle.api.Project
+import org.gradle.testfixtures.ProjectBuilder
+import spock.lang.Specification
+import spock.lang.TempDir
+
+class WriteGrailsVersionInfoTaskSpec extends Specification {
+
+ @TempDir
+ File tmp
+
+ void 'parse failure throws GradleException instead of falling through to NPE'() {
+ given:
+ Project project = ProjectBuilder.builder().withProjectDir(tmp).build()
+ WriteGrailsVersionInfoTask task = project.tasks.register('writeGrailsVersionInfo', WriteGrailsVersionInfoTask).get()
+ File pom = new File(tmp, 'pom-default.xml')
+ pom.text = '<not-xml'
+ File outDir = new File(tmp, 'versions')
+ task.projectVersion.set('8.1.0-SNAPSHOT')
+ task.bomPublicationFile.set(pom)
+ task.versionsDirectory.set(outDir)
+
+ when:
+ task.writeVersionInfo()
+
+ then:
+ GradleException e = thrown()
+ e.message.contains('Unable to parse BOM publication file')
+ !(e instanceof NullPointerException)
+ e.cause != null
+ }
+}
diff --git a/gradle.properties b/gradle.properties
index a0c8fed3e3..14ed4d492a 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -56,6 +56,11 @@ picocliVersion=4.7.7
spyMemcachedVersion=2.12.3
# Build dependency versions not managed by BOMs
+# Forge pins read by build-logic (the Rocker compiler plugin and the shadow transformers);
+# rockerVersion is also the Rocker runtime the Forge modules compile against
+antlr4Version=4.8-1!!
+rockerVersion=2.2.1
+shadowVersion=8.3.11
apacheRatVersion=0.8.1
gradleChecksumPluginVersion=1.4.0
gradleCycloneDxPluginVersion=3.0.0