Copilot commented on code in PR #15686:
URL: https://github.com/apache/grails-core/pull/15686#discussion_r3319271904
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsCodeStylePlugin.groovy:
##########
@@ -90,72 +100,65 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
createOrLoad(
toCreate.resolve(CODENARC_CONFIG_FILE_NAME),
-
"${BASE_RESOURCE_PATH}/codenarc/${CODENARC_CONFIG_FILE_NAME}"
+
"${BASE_RESOURCE_PATH}/codenarc/${CODENARC_CONFIG_FILE_NAME}",
+ project
)
directory
})
}
- private static void createOrLoad(Path expectedPath, String
defaultResource) {
- if (!Files.exists(expectedPath) || expectedPath.size() == 0) {
+ private static void createOrLoad(Path expectedPath, String
defaultResource, Project project) {
+ boolean defaultPath =
expectedPath.startsWith(project.rootProject.buildDir.toPath())
+ if (!Files.exists(expectedPath) || expectedPath.size() == 0 ||
defaultPath) {
def defaultValue =
GrailsCodeStylePlugin.getResourceAsStream(defaultResource)
if (!defaultValue) {
throw new IllegalStateException("Could not locate default
configuration file: ${defaultResource}")
}
+ // TODO: This really need to use gradle caching instead
+ project.logger.info("Replacing code style configuration")
Review Comment:
`createOrLoad` always overwrites the generated config when it lives under
the root buildDir because `defaultPath` is always true for the default
locations. With many subprojects applying this plugin, this causes repeated
file writes (and repeated log noise) even when the file is already up to date,
and also prevents local edits to the generated file from surviving a single
build. Consider removing the `defaultPath` condition, or only rewriting when
the on-disk contents differ from the bundled resource (hash/byte compare), and
log at debug level to avoid noisy builds.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsViolationAggregationPlugin.groovy:
##########
@@ -0,0 +1,467 @@
+/*
+ * 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 java.time.LocalDateTime
+import java.time.format.DateTimeFormatter
+
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.GradleException
+import org.gradle.api.Plugin
+import org.gradle.api.Project
+import org.gradle.api.Task
+import org.gradle.api.file.Directory
+import org.gradle.api.file.FileCollection
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+import org.gradle.api.plugins.AppliedPlugin
+import org.gradle.api.plugins.quality.Checkstyle
+import org.gradle.api.plugins.quality.CodeNarc
+import org.gradle.api.plugins.quality.Pmd
+import org.gradle.api.provider.Provider
+import org.gradle.api.tasks.TaskProvider
+import org.gradle.testing.jacoco.tasks.JacocoReport
+
+import com.github.spotbugs.snom.SpotBugsTask
+import groovy.xml.XmlSlurper
+
+/**
+ * Root-only convention plugin that aggregates code-style violation XML
reports and JaCoCo coverage
+ * CSV reports into human-readable Markdown files under
build/reports/violations/.
+ *
+ * Apply this plugin to the root project only. Subprojects should apply
+ * grails-code-style and grails-jacoco individually.
+ *
+ * Tasks registered:
+ * aggregateStyleViolations — CodeNarc + Checkstyle only
+ * aggregateAnalysisViolations — PMD + SpotBugs only (requires opt-in
properties)
+ * aggregateViolations — depends on both of the above
+ * aggregateJacocoCoverage — JaCoCo CSV → Markdown
+ */
+@CompileStatic
+class GrailsViolationAggregationPlugin implements Plugin<Project> {
+
+ private static final Logger LOGGER =
Logging.getLogger(GrailsViolationAggregationPlugin)
+
+ @Override
+ void apply(Project project) {
+ if (project != project.rootProject) {
+ throw new GradleException(
+ 'GrailsViolationAggregationPlugin must be applied to the root
project only. ' +
+ 'Apply grails-code-style and grails-jacoco to subprojects
instead.'
+ )
+ }
+
+ Provider<Directory> violationsDir =
project.layout.buildDirectory.dir('reports/violations')
+ Provider<Directory> styleXmlDir =
project.layout.buildDirectory.dir('reports/codestyle')
+ Provider<Directory> analysisXmlDir =
project.layout.buildDirectory.dir('reports/codeanalysis')
+
+ TaskProvider<Task> styleTask = registerStyleAggregation(project,
styleXmlDir, violationsDir)
+ TaskProvider<Task> analysisTask = registerAnalysisAggregation(project,
analysisXmlDir, violationsDir)
+ registerJacocoAggregation(project, violationsDir)
+
+ project.tasks.register('aggregateViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates all violation reports (style +
analysis) into build/reports/violations/'
+ task.dependsOn(styleTask, analysisTask)
+ }
+ }
+
+ private static TaskProvider<Task> registerStyleAggregation(Project root,
Provider<Directory> styleXmlDir, Provider<Directory> violationsDir) {
+ // Wire property flags as Providers — values are resolved at task
execution time, not at apply() time,
+ // and Providers are configuration-cache safe to capture in task
actions
+ Provider<Boolean> checkStyleTests = GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.TEST_STYLING_PROPERTY)
+ Provider<Boolean> codenarcEnabled = GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.CODENARC_ENABLED_PROPERTY, true)
+ Provider<Boolean> checkstyleEnabled =
GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.CHECKSTYLE_ENABLED_PROPERTY, true)
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateStyleViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates CodeNarc and Checkstyle violation
reports into build/reports/violations/'
+
task.outputs.file(root.file('build/reports/violations/CODENARC_VIOLATIONS.md'))
+
task.outputs.file(root.file('build/reports/violations/CHECKSTYLE_VIOLATIONS.md'))
+ task.doLast {
+ parseStyleViolations(styleXmlDir.get(), violationsDir.get(),
+ checkStyleTests.get(), codenarcEnabled.get(),
checkstyleEnabled.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('codenarc') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(CodeNarc))
+ }
+ }
+ sub.pluginManager.withPlugin('checkstyle') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(Checkstyle))
+ }
+ }
+ }
+ aggregateTask
+ }
+
+ private static TaskProvider<Task> registerAnalysisAggregation(Project
root, Provider<Directory> analysisXmlDir, Provider<Directory> violationsDir) {
+ Provider<Boolean> checkAnalysisTests =
GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.TEST_ANALYSIS_PROPERTY)
+ Provider<Boolean> pmdEnabled = GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.PMD_ENABLED_PROPERTY)
+ Provider<Boolean> spotbugsEnabled = GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.SPOTBUGS_ENABLED_PROPERTY)
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateAnalysisViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates PMD and SpotBugs violation reports
into build/reports/violations/'
+
task.outputs.file(root.file('build/reports/violations/PMD_VIOLATIONS.md'))
+
task.outputs.file(root.file('build/reports/violations/SPOTBUGS_VIOLATIONS.md'))
+ task.doLast {
+ parseAnalysisViolations(analysisXmlDir.get(),
violationsDir.get(),
+ checkAnalysisTests.get(), pmdEnabled.get(),
spotbugsEnabled.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('pmd') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(Pmd))
+ }
+ }
+ sub.pluginManager.withPlugin('com.github.spotbugs') {
AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(SpotBugsTask))
+ }
+ }
+ }
+ aggregateTask
+ }
+
+ private static void registerJacocoAggregation(Project root,
Provider<Directory> violationsDir) {
+ // Collect all potential CSV paths at configuration time — Project
must not be referenced from task actions
+ FileCollection jacocoCsvFiles = root.files(
+ root.allprojects.collect { Project p ->
p.file('build/reports/jacoco/test/jacocoTestReport.csv') }
+ )
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateJacocoCoverage') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates JaCoCo coverage reports from all
subprojects into build/reports/violations/'
+ task.inputs.files(jacocoCsvFiles).optional(true)
+
task.outputs.file(root.file('build/reports/violations/JACOCO_COVERAGE.md'))
+ task.doLast {
+ parseJacocoCoverage(jacocoCsvFiles, violationsDir.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('jacoco') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(JacocoReport))
+ }
+ }
+ }
+ }
+
+ @CompileDynamic
+ private static void parseStyleViolations(Directory styleXmlDir, Directory
violationsDir,
+ boolean checkStyleTests, boolean codenarcEnabled, boolean
checkstyleEnabled) {
+ def slurper = new XmlSlurper()
+
slurper.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd',
false)
+ slurper.setFeature('http://xml.org/sax/features/namespaces', false)
Review Comment:
`XmlSlurper` is configured only to skip external DTD loading and namespaces,
but it still allows other XML features that can be abused (e.g., entity
expansion / XXE-style payloads) if a malicious XML file is present in the
reports directory during CI. Please harden the parser similarly to the
project’s secure XML utilities (disable external-general-entities +
external-parameter-entities and enable secure-processing; optionally disallow
DOCTYPE) before parsing any report XML.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsViolationAggregationPlugin.groovy:
##########
@@ -0,0 +1,467 @@
+/*
+ * 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 java.time.LocalDateTime
+import java.time.format.DateTimeFormatter
+
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.GradleException
+import org.gradle.api.Plugin
+import org.gradle.api.Project
+import org.gradle.api.Task
+import org.gradle.api.file.Directory
+import org.gradle.api.file.FileCollection
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+import org.gradle.api.plugins.AppliedPlugin
+import org.gradle.api.plugins.quality.Checkstyle
+import org.gradle.api.plugins.quality.CodeNarc
+import org.gradle.api.plugins.quality.Pmd
+import org.gradle.api.provider.Provider
+import org.gradle.api.tasks.TaskProvider
+import org.gradle.testing.jacoco.tasks.JacocoReport
+
+import com.github.spotbugs.snom.SpotBugsTask
+import groovy.xml.XmlSlurper
+
+/**
+ * Root-only convention plugin that aggregates code-style violation XML
reports and JaCoCo coverage
+ * CSV reports into human-readable Markdown files under
build/reports/violations/.
+ *
+ * Apply this plugin to the root project only. Subprojects should apply
+ * grails-code-style and grails-jacoco individually.
+ *
+ * Tasks registered:
+ * aggregateStyleViolations — CodeNarc + Checkstyle only
+ * aggregateAnalysisViolations — PMD + SpotBugs only (requires opt-in
properties)
+ * aggregateViolations — depends on both of the above
+ * aggregateJacocoCoverage — JaCoCo CSV → Markdown
+ */
+@CompileStatic
+class GrailsViolationAggregationPlugin implements Plugin<Project> {
+
+ private static final Logger LOGGER =
Logging.getLogger(GrailsViolationAggregationPlugin)
+
+ @Override
+ void apply(Project project) {
+ if (project != project.rootProject) {
+ throw new GradleException(
+ 'GrailsViolationAggregationPlugin must be applied to the root
project only. ' +
+ 'Apply grails-code-style and grails-jacoco to subprojects
instead.'
+ )
+ }
+
+ Provider<Directory> violationsDir =
project.layout.buildDirectory.dir('reports/violations')
+ Provider<Directory> styleXmlDir =
project.layout.buildDirectory.dir('reports/codestyle')
+ Provider<Directory> analysisXmlDir =
project.layout.buildDirectory.dir('reports/codeanalysis')
+
+ TaskProvider<Task> styleTask = registerStyleAggregation(project,
styleXmlDir, violationsDir)
+ TaskProvider<Task> analysisTask = registerAnalysisAggregation(project,
analysisXmlDir, violationsDir)
+ registerJacocoAggregation(project, violationsDir)
+
+ project.tasks.register('aggregateViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates all violation reports (style +
analysis) into build/reports/violations/'
+ task.dependsOn(styleTask, analysisTask)
+ }
+ }
+
+ private static TaskProvider<Task> registerStyleAggregation(Project root,
Provider<Directory> styleXmlDir, Provider<Directory> violationsDir) {
+ // Wire property flags as Providers — values are resolved at task
execution time, not at apply() time,
+ // and Providers are configuration-cache safe to capture in task
actions
+ Provider<Boolean> checkStyleTests = GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.TEST_STYLING_PROPERTY)
+ Provider<Boolean> codenarcEnabled = GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.CODENARC_ENABLED_PROPERTY, true)
+ Provider<Boolean> checkstyleEnabled =
GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.CHECKSTYLE_ENABLED_PROPERTY, true)
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateStyleViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates CodeNarc and Checkstyle violation
reports into build/reports/violations/'
+
task.outputs.file(root.file('build/reports/violations/CODENARC_VIOLATIONS.md'))
+
task.outputs.file(root.file('build/reports/violations/CHECKSTYLE_VIOLATIONS.md'))
+ task.doLast {
+ parseStyleViolations(styleXmlDir.get(), violationsDir.get(),
+ checkStyleTests.get(), codenarcEnabled.get(),
checkstyleEnabled.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('codenarc') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(CodeNarc))
+ }
+ }
+ sub.pluginManager.withPlugin('checkstyle') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(Checkstyle))
+ }
+ }
+ }
+ aggregateTask
+ }
+
+ private static TaskProvider<Task> registerAnalysisAggregation(Project
root, Provider<Directory> analysisXmlDir, Provider<Directory> violationsDir) {
+ Provider<Boolean> checkAnalysisTests =
GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.TEST_ANALYSIS_PROPERTY)
+ Provider<Boolean> pmdEnabled = GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.PMD_ENABLED_PROPERTY)
+ Provider<Boolean> spotbugsEnabled = GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.SPOTBUGS_ENABLED_PROPERTY)
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateAnalysisViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates PMD and SpotBugs violation reports
into build/reports/violations/'
+
task.outputs.file(root.file('build/reports/violations/PMD_VIOLATIONS.md'))
+
task.outputs.file(root.file('build/reports/violations/SPOTBUGS_VIOLATIONS.md'))
+ task.doLast {
+ parseAnalysisViolations(analysisXmlDir.get(),
violationsDir.get(),
+ checkAnalysisTests.get(), pmdEnabled.get(),
spotbugsEnabled.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('pmd') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(Pmd))
+ }
+ }
+ sub.pluginManager.withPlugin('com.github.spotbugs') {
AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(SpotBugsTask))
+ }
+ }
+ }
+ aggregateTask
+ }
+
+ private static void registerJacocoAggregation(Project root,
Provider<Directory> violationsDir) {
+ // Collect all potential CSV paths at configuration time — Project
must not be referenced from task actions
+ FileCollection jacocoCsvFiles = root.files(
+ root.allprojects.collect { Project p ->
p.file('build/reports/jacoco/test/jacocoTestReport.csv') }
+ )
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateJacocoCoverage') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates JaCoCo coverage reports from all
subprojects into build/reports/violations/'
+ task.inputs.files(jacocoCsvFiles).optional(true)
+
task.outputs.file(root.file('build/reports/violations/JACOCO_COVERAGE.md'))
+ task.doLast {
+ parseJacocoCoverage(jacocoCsvFiles, violationsDir.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('jacoco') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(JacocoReport))
+ }
+ }
+ }
+ }
+
+ @CompileDynamic
+ private static void parseStyleViolations(Directory styleXmlDir, Directory
violationsDir,
+ boolean checkStyleTests, boolean codenarcEnabled, boolean
checkstyleEnabled) {
+ def slurper = new XmlSlurper()
+
slurper.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd',
false)
+ slurper.setFeature('http://xml.org/sax/features/namespaces', false)
+
+ def getModule = { String fileName ->
+ def lastDash = fileName.lastIndexOf('-')
+ lastDash != -1 ? fileName.substring(0, lastDash) : fileName
+ }
+
+ def isTestFile = { String fileName ->
+ fileName.toLowerCase().contains('test') ||
fileName.toLowerCase().contains('integrationtest')
+ }
+
+ def shouldSkipClass = { boolean includeTests, String className, String
filePath = null ->
+ if (includeTests) {
+ return false
+ }
+ if (filePath && (filePath.contains('src/test/') ||
filePath.contains('src/integrationTest/'))) {
+ return true
+ }
+ !filePath && (className.contains('Spec') ||
className.contains('Test') || className.contains('Tests'))
+ }
+
+ def writeReport = { String fileName, List violations, String title ->
+ def outDir = violationsDir.asFile
+ outDir.mkdirs()
+ def reportFile = new File(outDir, fileName)
+ def out = new StringBuilder()
+ out.append("# ${title}\n")
+ out.append("Generated on:
${LocalDateTime.now().format(DateTimeFormatter.ofPattern('yyyy-MM-dd
HH:mm:ss'))}\n\n")
+
+ if (violations.isEmpty()) {
+ out.append('No violations found! 🎉\n')
+ } else {
+ def uniqueViolations = violations.unique().sort { v ->
"${v.module}:${v.className}:${v.line}" }
+ def groupedByModule = uniqueViolations.groupBy { it.module
}.sort()
+ groupedByModule.each { module, modViolations ->
+ out.append("## Module: ${module}\n")
+ out.append('| Class | Tool | Violation | Line | Message
|\n')
+ out.append('| :--- | :--- | :--- | :--- | :--- |\n')
+ modViolations.each { v ->
+ out.append("| ${v.className} | ${v.tool} | ${v.type} |
${v.line} | ${v.message.replaceAll(/\|/, '\\|')} |\n")
+ }
+ out.append('\n')
+ }
+ }
+ reportFile.text = out.toString()
+ LOGGER.lifecycle("Aggregated report generated:
${reportFile.absolutePath}")
+ }
+
+ // CodeNarc
+ def codenarcViolations = []
+ def codenarcDir = styleXmlDir.dir('codenarc').asFile
+ if (codenarcDir.exists() && codenarcEnabled) {
+ codenarcDir.eachFileMatch(~/.*\.xml/) { file ->
+ if (file.size() == 0 || (!checkStyleTests &&
isTestFile(file.name))) {
+ return
+ }
+ def module = getModule(file.name)
+ def xml = slurper.parse(file)
+ xml.Package.each { pkg ->
+ pkg.File.each { f ->
+ def pkgName = [email protected]()
+ def fileName = [email protected]()
+ def className = pkgName ? "${pkgName}.${fileName}" :
fileName
+ className = className.replace('.groovy',
'').replace('.java', '')
+ if (shouldSkipClass(checkStyleTests, className,
[email protected]())) {
+ return
+ }
+ f.Violation.each { v ->
+ codenarcViolations << [
+ module : module,
+ className: className,
+ tool : 'CodeNarc',
+ type : [email protected](),
+ line : [email protected](),
+ message : v.Message.text().trim()
+ ]
+ }
+ }
+ }
+ }
+ }
+ writeReport('CODENARC_VIOLATIONS.md', codenarcViolations, 'CodeNarc
Violations Summary')
+
+ // Checkstyle
+ def checkstyleViolations = []
+ def checkstyleDir = styleXmlDir.dir('checkstyle').asFile
+ if (checkstyleDir.exists() && checkstyleEnabled) {
+ checkstyleDir.eachFileMatch(~/.*\.xml/) { file ->
+ if (file.size() == 0 || (!checkStyleTests &&
isTestFile(file.name))) {
+ return
+ }
+ def module = getModule(file.name)
+ def xml = slurper.parse(file)
+ xml.file.each { f ->
+ def filePath = [email protected]()
+ def className = filePath.contains('src/main/groovy/') ?
filePath.split('src/main/groovy/')[1] :
+ filePath.contains('src/main/java/') ?
filePath.split('src/main/java/')[1] :
+ filePath.contains('src/test/groovy/') ?
filePath.split('src/test/groovy/')[1] :
+ filePath.contains('src/test/java/') ?
filePath.split('src/test/java/')[1] :
+ filePath.split('/').last()
+ className = className.replace('.groovy',
'').replace('.java', '').replace('/', '.')
+ if (shouldSkipClass(checkStyleTests, className)) {
+ return
+ }
+ f.error.each { e ->
+ checkstyleViolations << [
+ module : module,
+ className: className,
+ tool : 'Checkstyle',
+ type :
[email protected]().split(/\./).last(),
+ line : [email protected](),
+ message : [email protected]().trim()
+ ]
+ }
+ }
+ }
+ }
+ writeReport('CHECKSTYLE_VIOLATIONS.md', checkstyleViolations,
'Checkstyle Violations Summary')
+ }
+
+ @CompileDynamic
+ private static void parseAnalysisViolations(Directory analysisXmlDir,
Directory violationsDir,
+ boolean checkAnalysisTests, boolean pmdEnabled, boolean
spotbugsEnabled) {
+ def slurper = new XmlSlurper()
+
slurper.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd',
false)
+ slurper.setFeature('http://xml.org/sax/features/namespaces', false)
Review Comment:
Same XML parser hardening concern as in `parseStyleViolations`: `XmlSlurper`
should disable external entity expansion and enable secure-processing (and
ideally disallow DOCTYPE) before parsing PMD/SpotBugs XML, to avoid
entity-expansion/XXE risks from untrusted report files in CI.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsViolationAggregationPlugin.groovy:
##########
@@ -0,0 +1,467 @@
+/*
+ * 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 java.time.LocalDateTime
+import java.time.format.DateTimeFormatter
+
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.GradleException
+import org.gradle.api.Plugin
+import org.gradle.api.Project
+import org.gradle.api.Task
+import org.gradle.api.file.Directory
+import org.gradle.api.file.FileCollection
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+import org.gradle.api.plugins.AppliedPlugin
+import org.gradle.api.plugins.quality.Checkstyle
+import org.gradle.api.plugins.quality.CodeNarc
+import org.gradle.api.plugins.quality.Pmd
+import org.gradle.api.provider.Provider
+import org.gradle.api.tasks.TaskProvider
+import org.gradle.testing.jacoco.tasks.JacocoReport
+
+import com.github.spotbugs.snom.SpotBugsTask
+import groovy.xml.XmlSlurper
+
+/**
+ * Root-only convention plugin that aggregates code-style violation XML
reports and JaCoCo coverage
+ * CSV reports into human-readable Markdown files under
build/reports/violations/.
+ *
+ * Apply this plugin to the root project only. Subprojects should apply
+ * grails-code-style and grails-jacoco individually.
+ *
+ * Tasks registered:
+ * aggregateStyleViolations — CodeNarc + Checkstyle only
+ * aggregateAnalysisViolations — PMD + SpotBugs only (requires opt-in
properties)
+ * aggregateViolations — depends on both of the above
+ * aggregateJacocoCoverage — JaCoCo CSV → Markdown
+ */
+@CompileStatic
+class GrailsViolationAggregationPlugin implements Plugin<Project> {
+
+ private static final Logger LOGGER =
Logging.getLogger(GrailsViolationAggregationPlugin)
+
+ @Override
+ void apply(Project project) {
+ if (project != project.rootProject) {
+ throw new GradleException(
+ 'GrailsViolationAggregationPlugin must be applied to the root
project only. ' +
+ 'Apply grails-code-style and grails-jacoco to subprojects
instead.'
+ )
+ }
+
+ Provider<Directory> violationsDir =
project.layout.buildDirectory.dir('reports/violations')
+ Provider<Directory> styleXmlDir =
project.layout.buildDirectory.dir('reports/codestyle')
+ Provider<Directory> analysisXmlDir =
project.layout.buildDirectory.dir('reports/codeanalysis')
+
+ TaskProvider<Task> styleTask = registerStyleAggregation(project,
styleXmlDir, violationsDir)
+ TaskProvider<Task> analysisTask = registerAnalysisAggregation(project,
analysisXmlDir, violationsDir)
+ registerJacocoAggregation(project, violationsDir)
+
+ project.tasks.register('aggregateViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates all violation reports (style +
analysis) into build/reports/violations/'
+ task.dependsOn(styleTask, analysisTask)
+ }
+ }
+
+ private static TaskProvider<Task> registerStyleAggregation(Project root,
Provider<Directory> styleXmlDir, Provider<Directory> violationsDir) {
+ // Wire property flags as Providers — values are resolved at task
execution time, not at apply() time,
+ // and Providers are configuration-cache safe to capture in task
actions
+ Provider<Boolean> checkStyleTests = GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.TEST_STYLING_PROPERTY)
+ Provider<Boolean> codenarcEnabled = GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.CODENARC_ENABLED_PROPERTY, true)
+ Provider<Boolean> checkstyleEnabled =
GradleUtils.booleanProvider(root,
GrailsCodeStylePlugin.CHECKSTYLE_ENABLED_PROPERTY, true)
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateStyleViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates CodeNarc and Checkstyle violation
reports into build/reports/violations/'
+
task.outputs.file(root.file('build/reports/violations/CODENARC_VIOLATIONS.md'))
+
task.outputs.file(root.file('build/reports/violations/CHECKSTYLE_VIOLATIONS.md'))
+ task.doLast {
+ parseStyleViolations(styleXmlDir.get(), violationsDir.get(),
+ checkStyleTests.get(), codenarcEnabled.get(),
checkstyleEnabled.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('codenarc') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(CodeNarc))
+ }
+ }
+ sub.pluginManager.withPlugin('checkstyle') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(Checkstyle))
+ }
+ }
+ }
+ aggregateTask
+ }
+
+ private static TaskProvider<Task> registerAnalysisAggregation(Project
root, Provider<Directory> analysisXmlDir, Provider<Directory> violationsDir) {
+ Provider<Boolean> checkAnalysisTests =
GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.TEST_ANALYSIS_PROPERTY)
+ Provider<Boolean> pmdEnabled = GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.PMD_ENABLED_PROPERTY)
+ Provider<Boolean> spotbugsEnabled = GradleUtils.booleanProvider(root,
GrailsCodeAnalysisPlugin.SPOTBUGS_ENABLED_PROPERTY)
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateAnalysisViolations') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates PMD and SpotBugs violation reports
into build/reports/violations/'
+
task.outputs.file(root.file('build/reports/violations/PMD_VIOLATIONS.md'))
+
task.outputs.file(root.file('build/reports/violations/SPOTBUGS_VIOLATIONS.md'))
+ task.doLast {
+ parseAnalysisViolations(analysisXmlDir.get(),
violationsDir.get(),
+ checkAnalysisTests.get(), pmdEnabled.get(),
spotbugsEnabled.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('pmd') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(Pmd))
+ }
+ }
+ sub.pluginManager.withPlugin('com.github.spotbugs') {
AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(SpotBugsTask))
+ }
+ }
+ }
+ aggregateTask
+ }
+
+ private static void registerJacocoAggregation(Project root,
Provider<Directory> violationsDir) {
+ // Collect all potential CSV paths at configuration time — Project
must not be referenced from task actions
+ FileCollection jacocoCsvFiles = root.files(
+ root.allprojects.collect { Project p ->
p.file('build/reports/jacoco/test/jacocoTestReport.csv') }
+ )
+
+ TaskProvider<Task> aggregateTask =
root.tasks.register('aggregateJacocoCoverage') { Task task ->
+ task.group = 'verification'
+ task.description = 'Aggregates JaCoCo coverage reports from all
subprojects into build/reports/violations/'
+ task.inputs.files(jacocoCsvFiles).optional(true)
+
task.outputs.file(root.file('build/reports/violations/JACOCO_COVERAGE.md'))
+ task.doLast {
+ parseJacocoCoverage(jacocoCsvFiles, violationsDir.get())
+ }
+ }
+ root.subprojects { Project sub ->
+ sub.pluginManager.withPlugin('jacoco') { AppliedPlugin p ->
+ aggregateTask.configure { Task task ->
+ task.dependsOn(sub.tasks.withType(JacocoReport))
+ }
+ }
+ }
+ }
+
+ @CompileDynamic
+ private static void parseStyleViolations(Directory styleXmlDir, Directory
violationsDir,
+ boolean checkStyleTests, boolean codenarcEnabled, boolean
checkstyleEnabled) {
+ def slurper = new XmlSlurper()
+
slurper.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd',
false)
+ slurper.setFeature('http://xml.org/sax/features/namespaces', false)
+
+ def getModule = { String fileName ->
+ def lastDash = fileName.lastIndexOf('-')
+ lastDash != -1 ? fileName.substring(0, lastDash) : fileName
+ }
+
+ def isTestFile = { String fileName ->
+ fileName.toLowerCase().contains('test') ||
fileName.toLowerCase().contains('integrationtest')
+ }
+
+ def shouldSkipClass = { boolean includeTests, String className, String
filePath = null ->
+ if (includeTests) {
+ return false
+ }
+ if (filePath && (filePath.contains('src/test/') ||
filePath.contains('src/integrationTest/'))) {
+ return true
+ }
+ !filePath && (className.contains('Spec') ||
className.contains('Test') || className.contains('Tests'))
+ }
+
+ def writeReport = { String fileName, List violations, String title ->
+ def outDir = violationsDir.asFile
+ outDir.mkdirs()
+ def reportFile = new File(outDir, fileName)
+ def out = new StringBuilder()
+ out.append("# ${title}\n")
+ out.append("Generated on:
${LocalDateTime.now().format(DateTimeFormatter.ofPattern('yyyy-MM-dd
HH:mm:ss'))}\n\n")
+
+ if (violations.isEmpty()) {
+ out.append('No violations found! 🎉\n')
+ } else {
+ def uniqueViolations = violations.unique().sort { v ->
"${v.module}:${v.className}:${v.line}" }
+ def groupedByModule = uniqueViolations.groupBy { it.module
}.sort()
+ groupedByModule.each { module, modViolations ->
+ out.append("## Module: ${module}\n")
+ out.append('| Class | Tool | Violation | Line | Message
|\n')
+ out.append('| :--- | :--- | :--- | :--- | :--- |\n')
+ modViolations.each { v ->
+ out.append("| ${v.className} | ${v.tool} | ${v.type} |
${v.line} | ${v.message.replaceAll(/\|/, '\\|')} |\n")
+ }
+ out.append('\n')
+ }
+ }
+ reportFile.text = out.toString()
+ LOGGER.lifecycle("Aggregated report generated:
${reportFile.absolutePath}")
+ }
+
+ // CodeNarc
+ def codenarcViolations = []
+ def codenarcDir = styleXmlDir.dir('codenarc').asFile
+ if (codenarcDir.exists() && codenarcEnabled) {
+ codenarcDir.eachFileMatch(~/.*\.xml/) { file ->
+ if (file.size() == 0 || (!checkStyleTests &&
isTestFile(file.name))) {
+ return
+ }
+ def module = getModule(file.name)
+ def xml = slurper.parse(file)
+ xml.Package.each { pkg ->
+ pkg.File.each { f ->
+ def pkgName = [email protected]()
+ def fileName = [email protected]()
+ def className = pkgName ? "${pkgName}.${fileName}" :
fileName
+ className = className.replace('.groovy',
'').replace('.java', '')
+ if (shouldSkipClass(checkStyleTests, className,
[email protected]())) {
+ return
+ }
+ f.Violation.each { v ->
+ codenarcViolations << [
+ module : module,
+ className: className,
+ tool : 'CodeNarc',
+ type : [email protected](),
+ line : [email protected](),
+ message : v.Message.text().trim()
+ ]
+ }
+ }
+ }
+ }
+ }
+ writeReport('CODENARC_VIOLATIONS.md', codenarcViolations, 'CodeNarc
Violations Summary')
+
+ // Checkstyle
+ def checkstyleViolations = []
+ def checkstyleDir = styleXmlDir.dir('checkstyle').asFile
+ if (checkstyleDir.exists() && checkstyleEnabled) {
+ checkstyleDir.eachFileMatch(~/.*\.xml/) { file ->
+ if (file.size() == 0 || (!checkStyleTests &&
isTestFile(file.name))) {
+ return
+ }
+ def module = getModule(file.name)
+ def xml = slurper.parse(file)
+ xml.file.each { f ->
+ def filePath = [email protected]()
+ def className = filePath.contains('src/main/groovy/') ?
filePath.split('src/main/groovy/')[1] :
+ filePath.contains('src/main/java/') ?
filePath.split('src/main/java/')[1] :
+ filePath.contains('src/test/groovy/') ?
filePath.split('src/test/groovy/')[1] :
+ filePath.contains('src/test/java/') ?
filePath.split('src/test/java/')[1] :
+ filePath.split('/').last()
+ className = className.replace('.groovy',
'').replace('.java', '').replace('/', '.')
+ if (shouldSkipClass(checkStyleTests, className)) {
+ return
+ }
+ f.error.each { e ->
+ checkstyleViolations << [
+ module : module,
+ className: className,
+ tool : 'Checkstyle',
+ type :
[email protected]().split(/\./).last(),
+ line : [email protected](),
+ message : [email protected]().trim()
+ ]
+ }
+ }
+ }
+ }
+ writeReport('CHECKSTYLE_VIOLATIONS.md', checkstyleViolations,
'Checkstyle Violations Summary')
+ }
+
+ @CompileDynamic
+ private static void parseAnalysisViolations(Directory analysisXmlDir,
Directory violationsDir,
+ boolean checkAnalysisTests, boolean pmdEnabled, boolean
spotbugsEnabled) {
+ def slurper = new XmlSlurper()
+
slurper.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd',
false)
+ slurper.setFeature('http://xml.org/sax/features/namespaces', false)
+
+ def getModule = { String fileName ->
+ def lastDash = fileName.lastIndexOf('-')
+ lastDash != -1 ? fileName.substring(0, lastDash) : fileName
+ }
+
+ def isTestFile = { String fileName ->
+ fileName.toLowerCase().contains('test') ||
fileName.toLowerCase().contains('integrationtest')
+ }
+
+ def shouldSkipClass = { boolean includeTests, String className ->
+ if (includeTests) {
+ return false
+ }
+ className.contains('Spec') || className.contains('Test') ||
className.contains('Tests')
+ }
+
+ def writeReport = { String fileName, List violations, String title ->
+ def outDir = violationsDir.asFile
+ outDir.mkdirs()
+ def reportFile = new File(outDir, fileName)
+ def out = new StringBuilder()
+ out.append("# ${title}\n")
+ out.append("Generated on:
${LocalDateTime.now().format(DateTimeFormatter.ofPattern('yyyy-MM-dd
HH:mm:ss'))}\n\n")
+
+ if (violations.isEmpty()) {
+ out.append('No violations found! 🎉\n')
+ } else {
+ def uniqueViolations = violations.unique().sort { v ->
"${v.module}:${v.className}:${v.line}" }
+ def groupedByModule = uniqueViolations.groupBy { it.module
}.sort()
+ groupedByModule.each { module, modViolations ->
+ out.append("## Module: ${module}\n")
+ out.append('| Class | Tool | Violation | Line | Message
|\n')
+ out.append('| :--- | :--- | :--- | :--- | :--- |\n')
+ modViolations.each { v ->
+ out.append("| ${v.className} | ${v.tool} | ${v.type} |
${v.line} | ${v.message.replaceAll(/\|/, '\\|')} |\n")
+ }
+ out.append('\n')
+ }
+ }
+ reportFile.text = out.toString()
+ LOGGER.lifecycle("Aggregated report generated:
${reportFile.absolutePath}")
+ }
+
+ // PMD
+ def pmdViolations = []
+ def pmdDir = analysisXmlDir.dir('pmd').asFile
+ if (pmdDir.exists() && pmdEnabled) {
+ pmdDir.eachFileMatch(~/.*\.xml/) { file ->
+ if (file.size() == 0 || (!checkAnalysisTests &&
isTestFile(file.name))) {
+ return
+ }
+ def module = getModule(file.name)
+ def xml = slurper.parse(file)
+ xml.file.each { f ->
+ f.violation.each { v ->
+ def className = "${v.@package}.${v.@class}"
+ if (shouldSkipClass(checkAnalysisTests, className)) {
+ return
+ }
+ pmdViolations << [
+ module : module,
+ className: className,
+ tool : 'PMD',
+ type : [email protected](),
+ line : [email protected](),
+ message : v.text().trim()
+ ]
+ }
+ }
+ }
+ }
+ writeReport('PMD_VIOLATIONS.md', pmdViolations, 'PMD Violations
Summary')
+
+ // SpotBugs
+ def spotbugsViolations = []
+ def spotbugsDir = analysisXmlDir.dir('spotbugs').asFile
+ if (spotbugsDir.exists() && spotbugsEnabled) {
+ spotbugsDir.eachFileMatch(~/.*\.xml/) { file ->
+ if (file.size() == 0 || (!checkAnalysisTests &&
isTestFile(file.name))) {
+ return
+ }
+ def module = getModule(file.name)
+ def xml = slurper.parse(file)
+ xml.BugInstance.each { b ->
+ def className = [email protected]()
+ if (shouldSkipClass(checkAnalysisTests, className)) {
+ return
+ }
+ spotbugsViolations << [
+ module : module,
+ className: className,
+ tool : 'SpotBugs',
+ type : [email protected](),
+ line : [email protected](),
+ message : b.LongMessage.text().trim()
+ ]
+ }
+ }
+ }
+ writeReport('SPOTBUGS_VIOLATIONS.md', spotbugsViolations, 'SpotBugs
Violations Summary')
+ }
+
+ @CompileDynamic
+ private static void parseJacocoCoverage(FileCollection csvFiles, Directory
violationsDir) {
+ def jacocoCoverage = []
+ csvFiles.each { File csvReport ->
+ if (csvReport.exists()) {
+ LOGGER.debug("Processing JaCoCo report:
${csvReport.absolutePath}")
+ csvReport.splitEachLine(',') { fields ->
+ if (fields.size() < 5 || fields[0] == 'GROUP') {
+ return
+ }
+ def module = fields[0]
+ def pkg = fields[1]
+ def clazz = fields[2]
+ def missedStr = fields[3]
+ def coveredStr = fields[4]
+
+ if (missedStr.isNumber() && coveredStr.isNumber()) {
+ def m = missedStr.toInteger()
+ def c = coveredStr.toInteger()
+ def total = m + c
+ def percent = total > 0 ? (c * 100 / total).round(2) :
100.0
+
+ jacocoCoverage << [
+ module : module,
+ className: "${pkg}.${clazz}",
+ percent : percent
+ ]
+ }
+ }
+ }
+ }
+
+ if (jacocoCoverage.isEmpty()) {
+ LOGGER.info('No JaCoCo coverage reports found to aggregate')
+ return
+ }
+
+ jacocoCoverage.removeIf {
it.className.startsWith('org.grails.orm.hibernate.support.hibernate7.') }
+
Review Comment:
The JaCoCo aggregation hard-codes a filter that drops any class under
`org.grails.orm.hibernate.support.hibernate7.`. This makes the report
incomplete in a way that’s non-obvious to consumers and ties a generic
aggregation plugin to a specific package name. Consider removing this filter or
making it configurable (e.g., via a Gradle property or extension field) and
documenting the default behavior.
##########
.agents/skills/violation-fixer/SKILL.md:
##########
@@ -0,0 +1,231 @@
+---
+name: violation-fixer
+description: Guide for running, interpreting, and fixing code style and
analysis violations in grails-core using GrailsCodeStylePlugin,
GrailsCodeAnalysisPlugin, and GrailsViolationAggregationPlugin — covering
CodeNarc, Checkstyle, PMD, SpotBugs, and JaCoCo
+license: Apache-2.0
+---
+<!--
+SPDX-License-Identifier: Apache-2.0
+
+Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements; and to You under the Apache License, Version 2.0.
+-->
+
+## What I Do
+
+- Explain how `GrailsCodeStylePlugin`, `GrailsCodeAnalysisPlugin`, and
`GrailsViolationAggregationPlugin` enforce code quality across all 60+ modules.
+- Guide you through running style and analysis checks, interpreting the
per-tool Markdown violation reports, and fixing each class of violation.
+- Describe which tools are always-on vs. opt-in, how to configure them via
Gradle properties, and which violations can be auto-fixed.
+
+## When to Use Me
+
+Activate this skill when:
+
+- Running `./gradlew aggregateViolations` and interpreting the resulting
`*_VIOLATIONS.md` files.
+- Fixing CodeNarc, Checkstyle, PMD, SpotBugs, or Spotless violations reported
in those files.
+- Configuring code style or analysis tools across the repo (enabling/disabling
tools or adjusting rule files).
+- Preparing a commit — the plugin output must be clean before merging.
+
+---
+
+## Plugin Overview
+
+| Plugin | Applied to | Responsibility |
+|--------|-----------|----------------|
+| `org.apache.grails.gradle.grails-code-style` | Every subproject | Applies
Checkstyle and CodeNarc; registers per-project `codeStyle` task; redirects XML
reports to root `build/reports/codestyle/` |
+| `org.apache.grails.gradle.grails-code-analysis` | Every subproject | Applies
PMD and SpotBugs (both opt-in); registers per-project `codeAnalysis` task;
redirects XML reports to root `build/reports/codestyle/` |
Review Comment:
The skill doc says `grails-code-analysis` redirects XML reports to
`build/reports/codestyle/`, but the plugin writes analysis XML to
`build/reports/codeanalysis/` (and the aggregation plugin reads from that
location). Please update this row to avoid sending contributors to the wrong
directory.
##########
.github/workflows/codeanalysis.yml:
##########
@@ -0,0 +1,95 @@
+# 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.
+
+name: "Code Analysis"
+on:
+ push:
+ branches:
+ - '[0-9]+.[0-9]+.x'
+ - '8.0.x-hibernate7.*'
+ pull_request:
+ workflow_dispatch:
+# queue jobs and only allow 1 run per branch due to the likelihood of hitting
GitHub resource limits
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+jobs:
+ check_core_projects:
+ name: "Core Projects"
+ runs-on: ubuntu-24.04
+ steps:
+ - name: "🌐 Output Agent IP" # in the event RAO blocks this agent, this
can be used to debug it
+ run: curl -s https://api.ipify.org
+ - name: "📥 Checkout repository"
+ uses: actions/checkout@v6
+ - name: "☕️ Setup JDK"
+ uses: actions/setup-java@v4
+ with:
+ distribution: liberica
+ java-version: 21
+ - name: "🐘 Setup Gradle"
+ uses:
gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
+ with:
+ develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }}
+ - name: "🔎 Check Core Projects"
+ run: ./gradlew aggregateAnalysisViolations --continue
Review Comment:
`aggregateAnalysisViolations` aggregates reports based on the
`grails.codeanalysis.enabled.*` flags, but PMD/SpotBugs are opt-in and the
workflow doesn’t enable them. As written, this will generally produce “no
violations” reports without actually running analysis. Pass
`-Pgrails.codeanalysis.enabled.pmd=true
-Pgrails.codeanalysis.enabled.spotbugs=true` (and optionally the tests flag) so
the workflow performs real analysis checks.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsCodeStyleExtension.groovy:
##########
@@ -25,18 +25,19 @@ import groovy.transform.CompileStatic
import org.gradle.api.Project
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.model.ObjectFactory
+import org.gradle.api.provider.Property
Review Comment:
`org.gradle.api.provider.Property` is imported but never used. This will be
flagged by the new CodeNarc ruleset (`UnusedImport`) and adds noise to the
build. Please remove the unused import.
##########
.github/workflows/codestyle.yml:
##########
@@ -117,24 +110,20 @@ jobs:
uses:
gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }}
- - name: "🔎 Check Forge Projects"
- working-directory: grails-forge
- run: ./gradlew codeStyle
- - name: "📤 Upload Failure Reports"
+ - name: "🔎 Check Gradle Plugin Projects"
+ working-directory: grails-gradle
+ run: ./gradlew aggregateStyleViolations --continue
Review Comment:
This job runs `./gradlew aggregateStyleViolations` inside `grails-gradle/`,
but that build currently does not apply the
`org.apache.grails.gradle.grails-violation-aggregation` plugin (so the task
won’t exist). Either apply the aggregation plugin in
`grails-gradle/build.gradle` (root of that build) or switch this workflow step
back to a task that *does* exist there (e.g., `codeStyle`).
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsCodeAnalysisExtension.groovy:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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 javax.inject.Inject
+
+import groovy.transform.CompileStatic
+
+import org.gradle.api.Project
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.model.ObjectFactory
+
+@CompileStatic
+class GrailsCodeAnalysisExtension {
+
+ /**
+ * Defaults to project.rootProject.buildDir/codestyle/pmd.
Review Comment:
The Javadoc says the PMD config defaults to
`project.rootProject.buildDir/codestyle/pmd`, but the actual convention is
`build/codeanalysis/pmd`. Please update the comment to match the real default
path so users configure the correct directory.
##########
.agents/skills/violation-fixer/SKILL.md:
##########
@@ -0,0 +1,231 @@
+---
+name: violation-fixer
+description: Guide for running, interpreting, and fixing code style and
analysis violations in grails-core using GrailsCodeStylePlugin,
GrailsCodeAnalysisPlugin, and GrailsViolationAggregationPlugin — covering
CodeNarc, Checkstyle, PMD, SpotBugs, and JaCoCo
+license: Apache-2.0
+---
+<!--
+SPDX-License-Identifier: Apache-2.0
+
+Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements; and to You under the Apache License, Version 2.0.
+-->
+
+## What I Do
+
+- Explain how `GrailsCodeStylePlugin`, `GrailsCodeAnalysisPlugin`, and
`GrailsViolationAggregationPlugin` enforce code quality across all 60+ modules.
+- Guide you through running style and analysis checks, interpreting the
per-tool Markdown violation reports, and fixing each class of violation.
+- Describe which tools are always-on vs. opt-in, how to configure them via
Gradle properties, and which violations can be auto-fixed.
+
+## When to Use Me
+
+Activate this skill when:
+
+- Running `./gradlew aggregateViolations` and interpreting the resulting
`*_VIOLATIONS.md` files.
+- Fixing CodeNarc, Checkstyle, PMD, SpotBugs, or Spotless violations reported
in those files.
+- Configuring code style or analysis tools across the repo (enabling/disabling
tools or adjusting rule files).
+- Preparing a commit — the plugin output must be clean before merging.
+
+---
+
+## Plugin Overview
+
+| Plugin | Applied to | Responsibility |
+|--------|-----------|----------------|
+| `org.apache.grails.gradle.grails-code-style` | Every subproject | Applies
Checkstyle and CodeNarc; registers per-project `codeStyle` task; redirects XML
reports to root `build/reports/codestyle/` |
+| `org.apache.grails.gradle.grails-code-analysis` | Every subproject | Applies
PMD and SpotBugs (both opt-in); registers per-project `codeAnalysis` task;
redirects XML reports to root `build/reports/codestyle/` |
+| `org.apache.grails.gradle.grails-jacoco` | Every subproject | Applies
JaCoCo; wires `jacocoTestReport` to run after each `test` task |
+| `org.apache.grails.gradle.grails-violation-aggregation` | **Root project
only** | Registers `aggregateViolations` and `aggregateJacocoCoverage` tasks;
writes Markdown summaries to `build/reports/violations/` |
+
+---
+
+## Key Tasks
+
+| Task | Scope | Description |
+|------|-------|-------------|
+| `./gradlew codeStyle` | per-project | Runs Checkstyle and CodeNarc for that
project |
+| `./gradlew codeAnalysis` | per-project | Runs PMD and/or SpotBugs for that
project (when enabled) |
+| `./gradlew aggregateViolations` | root | Runs all checks across every
module, then writes `*_VIOLATIONS.md` to `build/reports/violations/` |
+| `./gradlew aggregateJacocoCoverage` | root | Runs JaCoCo reports across
every module, then writes `JACOCO_COVERAGE.md` to `build/reports/violations/` |
+| `./gradlew codenarcFix` | per-project | Auto-fixes a subset of CodeNarc
violations |
+
+### Quick commands
+
+```bash
+# Check a single module (style only)
+./gradlew :grails-core:codeStyle
+
+# Check a single module (analysis — must be enabled via properties)
+./gradlew :grails-core:codeAnalysis -Pgrails.codeanalysis.enabled.pmd=true
+
+# Full multi-module check + report
+./gradlew aggregateViolations
+
+# Include test sources in style checks
+./gradlew aggregateViolations -Pgrails.codestyle.enabled.tests=true
+
+# Include test sources in analysis
+./gradlew aggregateViolations -Pgrails.codeanalysis.enabled.tests=true
+
+# Ignore failures (collect reports without failing the build)
+./gradlew aggregateViolations -Pgrails.codestyle.ignoreFailures=true
-Pgrails.codeanalysis.ignoreFailures=true
+
+# Auto-fix some CodeNarc violations before running checks
+./gradlew codenarcFix codeStyle
+
+# JaCoCo coverage report
+./gradlew aggregateJacocoCoverage
+```
+
+---
+
+## Output Files
+
+After running `aggregateViolations`, these files appear under
`build/reports/violations/` in the **root project build directory**:
+
+| File | Tool | Always generated |
+|------|------|-----------------|
+| `build/reports/violations/CODENARC_VIOLATIONS.md` | CodeNarc | Yes |
+| `build/reports/violations/CHECKSTYLE_VIOLATIONS.md` | Checkstyle | Yes |
+| `build/reports/violations/PMD_VIOLATIONS.md` | PMD | Yes — contains `No
violations found!` when PMD is disabled |
+| `build/reports/violations/SPOTBUGS_VIOLATIONS.md` | SpotBugs | Yes —
contains `No violations found!` when SpotBugs is disabled |
+
+After running `aggregateJacocoCoverage`:
+
+| File | Tool | Generated |
+|------|------|-----------|
+| `build/reports/violations/JACOCO_COVERAGE.md` | JaCoCo | Only when at least
one subproject has a JaCoCo CSV report |
+
+All reports are inside `build/` and are excluded from version control via
`.gitignore`. A clean run produces `No violations found! 🎉` in each style file.
**The build must be clean before committing.**
+
+Each file is a Markdown table grouped by module, with columns: **Class**,
**Tool**, **Violation**, **Line**, **Message**.
+
+---
+
+## Tool Details
+
+### CodeNarc (Groovy — always enabled)
+
+Rule file: `build/codestyle/codenarc/codenarc.groovy` (generated by the plugin
during setup; not intended to be edited directly).
+
+Most common violations and how to fix them:
+
+| Rule | Fix |
+|------|-----|
+| `UnnecessaryGString` | Replace `"plain string"` with `'plain string'` |
+| `UnnecessarySemicolon` | Remove trailing `;` |
+| `SpaceBeforeOpeningBrace` | Add space before `{` → `method() {` |
+| `SpaceAroundMapEntryColon` | `[key: value]` not `[key:value]` |
+| `ConsecutiveBlankLines` | Collapse 3+ blank lines to 2 |
+| `ClassStartsWithBlankLine` | Remove blank line right after `class Foo {` |
+| `NoWildcardImports` | Expand `import org.foo.*` to explicit imports |
+| `UnusedImport` | Remove imports not referenced in the file |
+| `MethodName` | Method names must be camelCase (not `snake_case`) |
+| `VariableName` | Variable names must be camelCase |
+| `LineLength` | Keep lines ≤ 200 chars (default) |
+
+Auto-fixable via `codenarcFix`: `ClassStartsWithBlankLine`,
`SpaceAroundMapEntryColon`, `UnnecessaryGString`, `UnnecessarySemicolon`,
`SpaceBeforeOpeningBrace`, `ConsecutiveBlankLines`.
+
+### Checkstyle (Java — always enabled)
+
+Rule file: `build/codestyle/checkstyle/checkstyle.xml`.
+
+Common violations:
+
+| Rule | Fix |
+|------|-----|
+| `ImportOrder` | Re-order imports: `java|javax`, then `groovy`, then
`jakarta`, then blank, then `io.spring|org.springframework`, then
`grails|org.apache.grails|org.grails`, then static imports |
+| `AvoidStarImport` | Use explicit class imports |
+| `UnusedImports` | Remove unused imports |
+| `WhitespaceAround` | Add spaces around operators and keywords |
+| `NeedBraces` | Add `{}` to single-statement `if`/`for`/`while` |
+| `FileTabCharacter` | Replace tabs with 4 spaces |
+| `NewlineAtEndOfFile` | Ensure file ends with `\n` |
+
+### PMD (Java/Groovy — opt-in)
+
+Enable: `-Pgrails.codeanalysis.enabled.pmd=true`
+
+Rule file: `build/codeanalysis/pmd/pmd.xml`.
+
+### SpotBugs (Java bytecode — opt-in)
+
+Enable: `-Pgrails.codeanalysis.enabled.spotbugs=true`
+
+Runs at `Effort.MAX` / `Confidence.HIGH`. Only high-confidence bugs are
reported.
+
+### Spotless (Java auto-formatting — opt-in)
+
+Enable: `-Pgrails.codestyle.enabled.spotless=true`
+
+Uses Palantir Java Format. Can auto-fix by running:
+```bash
+./gradlew spotlessApply
+```
+
+---
+
+## Configuration Properties
+
+All properties can be set in `gradle.properties` or passed as `-P` flags:
+
+### `grails-code-style` plugin (Checkstyle + CodeNarc)
+
+| Property | Default | Description |
+|----------|---------|-------------|
+| `grails.codestyle.enabled.checkstyle` | `true` | Enable Checkstyle |
+| `grails.codestyle.enabled.codenarc` | `true` | Enable CodeNarc |
+| `grails.codestyle.enabled.spotless` | `false` | Enable Spotless |
+| `grails.codestyle.enabled.tests` | `false` | Also check test source sets |
+| `grails.codestyle.ignoreFailures` | `false` | Collect reports without
failing build |
+| `grails.codestyle.codenarc.fix` | `false` | Run `codenarcFix` before
CodeNarc tasks |
+| `grails.codestyle.dir.checkstyle` | (auto) | Custom path to Checkstyle
config dir |
+| `grails.codestyle.dir.codenarc` | (auto) | Custom path to CodeNarc config
dir |
+| `skipCodeStyle` | unset | If present, all style tasks are skipped |
+
+### `grails-code-analysis` plugin (PMD + SpotBugs)
+
+| Property | Default | Description |
+|----------|---------|-------------|
+| `grails.codeanalysis.enabled.pmd` | `false` | Enable PMD |
+| `grails.codeanalysis.enabled.spotbugs` | `false` | Enable SpotBugs |
+| `grails.codeanalysis.enabled.tests` | `false` | Also analyse test source
sets |
+| `grails.codeanalysis.ignoreFailures` | `false` | Collect reports without
failing build |
+| `grails.codeanalysis.dir.pmd` | (auto) | Custom path to PMD config dir |
+| `skipCodeStyle` | unset | If present, all analysis tasks are also skipped |
+
+---
+
+## Fixing Violations Workflow
+
+1. Run `./gradlew aggregateViolations -Pgrails.codestyle.ignoreFailures=true
-Pgrails.codeanalysis.ignoreFailures=true`
+2. Open `build/reports/violations/CODENARC_VIOLATIONS.md` and
`build/reports/violations/CHECKSTYLE_VIOLATIONS.md` to see all issues by module
+3. For CodeNarc, run `./gradlew codenarcFix` to auto-fix what it can
+4. Fix remaining violations manually using the table above
+5. Re-run `./gradlew aggregateViolations` and confirm files contain `No
violations found! 🎉`
+6. The reports are inside `build/` and do not need to be deleted before
committing
+
+---
+
+## Reports Directory Structure
+
+All XML reports are consolidated at:
+```
+build/reports/codestyle/ ← XML inputs for style aggregation
+├── checkstyle/
+│ ├── grails-core-checkstyleMain.xml
+│ ├── grails-web-mvc-checkstyleMain.xml
+│ └── ...
+├── codenarc/
+│ ├── grails-core-codenarcMain.xml
+│ └── ...
+├── pmd/ (if enabled)
+└── spotbugs/ (if enabled)
+
Review Comment:
This directory layout implies PMD/SpotBugs XML reports live under
`build/reports/codestyle/`, but the analysis plugin writes them under
`build/reports/codeanalysis/` by default. Please adjust the directory structure
section to reflect the separate `reports/codeanalysis/{pmd,spotbugs}` location
so readers can find the actual inputs used by `aggregateAnalysisViolations`.
##########
.github/workflows/codeanalysis.yml:
##########
@@ -0,0 +1,95 @@
+# 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.
+
+name: "Code Analysis"
+on:
+ push:
+ branches:
+ - '[0-9]+.[0-9]+.x'
+ - '8.0.x-hibernate7.*'
+ pull_request:
+ workflow_dispatch:
+# queue jobs and only allow 1 run per branch due to the likelihood of hitting
GitHub resource limits
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+jobs:
+ check_core_projects:
+ name: "Core Projects"
+ runs-on: ubuntu-24.04
+ steps:
+ - name: "🌐 Output Agent IP" # in the event RAO blocks this agent, this
can be used to debug it
+ run: curl -s https://api.ipify.org
+ - name: "📥 Checkout repository"
+ uses: actions/checkout@v6
+ - name: "☕️ Setup JDK"
+ uses: actions/setup-java@v4
+ with:
+ distribution: liberica
+ java-version: 21
+ - name: "🐘 Setup Gradle"
+ uses:
gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
+ with:
+ develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }}
+ - name: "🔎 Check Core Projects"
+ run: ./gradlew aggregateAnalysisViolations --continue
+ - name: "📤 Upload Reports"
+ if: always()
+ uses: actions/[email protected]
+ with:
+ name: core-reports
+ path: build/reports/violations/
+ - name: "📋 Publish Code Analysis Report in Job Summary"
+ if: always()
+ run: |
+ echo "## 🔎 Code Analysis Report - Core Projects" >>
$GITHUB_STEP_SUMMARY
+ for report in PMD_VIOLATIONS.md SPOTBUGS_VIOLATIONS.md; do
+ file="build/reports/violations/$report"
+ [ -f "$file" ] && cat "$file" >> $GITHUB_STEP_SUMMARY || true
+ done
+ check_gradle_plugin_projects:
+ name: "Gradle Plugin Projects"
+ runs-on: ubuntu-24.04
+ steps:
+ - name: "🌐 Output Agent IP" # in the event RAO blocks this agent, this
can be used to debug it
+ run: curl -s https://api.ipify.org
+ - name: "📥 Checkout repository"
+ uses: actions/checkout@v6
+ - name: "☕️ Setup JDK"
+ uses: actions/setup-java@v4
+ with:
+ distribution: liberica
+ java-version: 21
+ - name: "🐘 Setup Gradle"
+ uses:
gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
+ with:
+ develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }}
+ - name: "🔎 Check Gradle Plugin Projects"
+ working-directory: grails-gradle
+ run: ./gradlew aggregateAnalysisViolations --continue
+ - name: "📤 Upload Reports"
+ if: always()
+ uses: actions/[email protected]
+ with:
+ name: gradle-plugin-reports
+ path: grails-gradle/build/reports/violations/
+ - name: "📋 Publish Code Analysis Report in Job Summary"
+ if: always()
+ run: |
+ echo "## 🔎 Code Analysis Report - Gradle Plugin Projects" >>
$GITHUB_STEP_SUMMARY
+ for report in PMD_VIOLATIONS.md SPOTBUGS_VIOLATIONS.md; do
+ file="grails-gradle/build/reports/violations/$report"
+ [ -f "$file" ] && cat "$file" >> $GITHUB_STEP_SUMMARY || true
+ done
Review Comment:
This step runs `aggregateAnalysisViolations` in `grails-gradle/`, but that
standalone build does not currently apply the root-only
`grails-violation-aggregation` plugin, so the task won’t exist. Either apply
the plugin in `grails-gradle/build.gradle` and enable PMD/SpotBugs via
`-Pgrails.codeanalysis.enabled.*`, or change the workflow to run `codeAnalysis`
tasks that are actually registered in that build.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]