Repository navigation
Description
org.grails.cli.boot.SpringApplicationWebApplicationInitializer class (causing the NPE during Tomcat WAR deployment) is being transitively included via the Grails Database Migration functionality. Specifically:
- This originates from
org.apache.grails:grails-data-hibernate5-dbmigration - In Grails 7+, the Database Migration plugin depends on
org.apache.grails:grails-shellfor certain scripts and commands (e.g., Liquibase-related operations likedbm-*scripts). grails-shellpulls in Spring Boot CLI components, including the problematic initializer that's only intended for standalone executable JARs—not traditional WAR deployments in an external container like Tomcat.
The presence of this transitive dependency explains why the class is on the classpath and gets invoked by Tomcat during context startup, leading to the null "sources" in MANIFEST.MF.
Workaround for Grails 7, build.gradle:
bootWar {
classpath = classpath.filter {
!it.name.contains('spring-boot-cli') &&
!it.name.contains('grails-shell')
}
}
Potential updates for Grails 8:
Option 1: Gradle Feature Variant
In the plugin's build.gradle:
java {
registerFeature('cli') {
usingSourceSet(sourceSets.main)
}
}
dependencies {
// Core - always included
implementation("org.liquibase:liquibase-core:${liquibaseVersion}")
implementation("org.liquibase.ext:liquibase-hibernate5:${liquibaseVersion}")
// CLI feature - opt-in
cliApi("org.apache.grails:grails-shell-cli:${grailsVersion}") {
exclude group: 'org.slf4j', module: 'slf4j-simple'
exclude group: 'org.codehaus.groovy'
}
}
Consuming apps would then:
// Core functionality (in WAR)
implementation("org.apache.grails:grails-data-hibernate5-dbmigration:7.0.7")
// CLI commands (dev only)
developmentOnly("org.apache.grails:grails-data-hibernate5-dbmigration:7.0.7") {
capabilities {
requireCapability("org.apache.grails:grails-data-hibernate5-dbmigration-cli")
}
}
Option 2: Use compileOnlyApi + Document for Apps (Simpler)
In the plugin's build.gradle:
// Available at compile time for the plugin, but consumers must explicitly add it
compileOnlyApi("org.apache.grails:grails-shell-cli:${grailsVersion}") {
exclude group: 'org.slf4j', module: 'slf4j-simple'
exclude group: 'org.codehaus.groovy'
}
Consuming apps add:
developmentOnly("org.apache.grails:grails-shell-cli:7.0.7")
Option 3: Separate Artifact
Split into two published artifacts:
- grails-data-hibernate5-dbmigration - core runtime (no CLI)
- grails-data-hibernate5-dbmigration-cli - CLI commands (depends on core + grails-shell-cli)
Apps use:
implementation("org.apache.grails:grails-data-hibernate5-dbmigration:7.0.7")
developmentOnly("org.apache.grails:grails-data-hibernate5-dbmigration-cli:7.0.7")
Sub-issues
Collapse Sub-issuesSub-issues
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
[-]Grails 7 - grails-data-hibernate5-dbmigration bootWar: Cannot invoke "String.split(String)" because "sources" is null - In a classic servlet-container WAR deployment[/-][+]Grails 8 - grails-data-hibernate5-dbmigration bootWar: Cannot invoke "String.split(String)" because "sources" is null - In a classic servlet-container WAR deployment[/+]vigneshsiva11 commentedon Apr 22, 2026
Hi @jamesfredley and maintainers
Thanks for explaining the options. I want to help fix this issue and discuss my approach before creating a request.
I think Option 1, Gradle Feature Variant, is the long-term solution for Grails 8. This option does not break existing code, so users of "grails-data-hibernate5-dbmigration" do not need to change anything. It also follows Gradle practices for separating optional features.
Option 1 has benefits. It does not require users to make changes to their code. Unlike Option 2, users do not need to manage "compileOnlyApi" dependencies. The plugin handles the separation cleanly. Also, CLI tooling is opt-in, ensuring that WAR deployments are clean by default.
Here is my proposal:
I will create a request to fix the issue in the "grails-data-hibernate5-dbmigration" plugin. I will register a "cli" feature variant. Move the "grails-shell" dependency under that variant. This ensures that "grails-shell" and related components are not included in WAR deployments. I will test this with a WAR deployment to confirm it works.
I will create another request to update the documentation and app templates. After the plugin fix, users need guidance on how to use CLI functionality during development without affecting WAR packaging. This pull request will update the documentation to explain the developmentOnly` capability pattern.
Before I start I have a questions:
Is Option 1 the direction for Grails 8?
Should the "grails-shell' split be handled at the "grails-module level," or is fixing it in "grails-data-hibernate5-dbmigration" enough?
Are there existing integration tests for WAR deployment scenarios that I should extend?
For documentation updates is there a repository I should target?
I'm ready to start once we agree on the direction. Thanks again, for explaining the issue
jdaugherty commentedon Apr 22, 2026
This is a change we've been discussing in a wider scope @vigneshsiva11 We need to split the db migration plugin into separate plugins. Before we do that, we want to get the Hibernate 8 change merged to limit disruptions though. Please hold off on this ticket until 8.0.x-hibernate7 is merged into 8.x. We can revisit after that.
vigneshsiva11 commentedon Apr 22, 2026
Hi @jdaugherty, thanks for explaining! That makes sense. It's better to let the Hibernate 8 changes settle first before we split the plugin so we don't have many disruptions at once.
I'll wait on this task for now. Keep an eye on the "8.0.x-hibernate7" branch. Once that gets merged into "8.x," I will come back to this. Pick it up from there.
Thanks again!
Cover blank/whitespace manifest entry in dbmigration bootWar test (#1…
jdaugherty commentedon Jul 5, 2026
@jamesfredley I think we need to consider actually splitting these libraries. I don't think we should bandaid package this since every other plugin that includes the shell-cli will have the same problem (#15815). The main issue is there is command infrastructure in both the shell-cli & in grails-core. Do we force a split only when shell-cli is included or do we split the base commands from core?
My initial reaction is to split both scenarios. I iterated with AI a bit, and here's a proposal (plan) we could use to do this work:
Proposal: Move Grails CLI commands into
cliclassifier artifacts (Grails 8.0.x)Summary
Grails ships its dev/CLI commands (
grails.dev.commands.ApplicationCommand) inside runtimelibraries —
grails-core,grails-web-url-mappings, the Hibernate plugins,grails-scaffolding,and the two
dbmigrationplugins. Some of these command sets drag heavyweight, CLI-onlydependencies (notably
grails-shell/grails-shell-cli) onto the application runtime classpath,causing two classes of failure: dependency-version conflicts (a mismatched Groovy) and incorrect
framework behavior — e.g. a CLI-only Spring Boot servlet initializer that breaks WAR deployment
(#15377).
This proposal removes command code from every runtime artifact by publishing commands as a
cliclassifier of each module (via Gradle feature variants), keyed off a dedicated
META-INF/grails-cli.factoriesfile, and consumed through a new, purpose-built Gradleconfiguration
grailsCli(with existingbuildscript { classpath }placement still supported).The entire
grails/dev/commands/**package (command contract + registry + infrastructure +ConfigReportCommand) moves intograils-core:cli, renamed toorg.apache.grails.core.cli.*ona JPMS-safe, per-artifact-unique package scheme, so the default
grails-corejar — and every defaultplugin jar — ships zero command code and zero command contract. No new subprojects are
created.
This lands in the Grails 8.0.x major release as a clean break (no backward-compatibility shim).
Background & problem
The Hibernate 5/7 database-migration plugins depend on
grails-shell-clipurely so theirdbm-*commands compile and can be located by the shell. Because each plugin is a single artifact used on
both the build and runtime classpaths, that dependency (and its mismatched Groovy) leaks into
applications. The current workaround is an explicit exclusion + TODO in
grails-data-hibernate{5,7}/dbmigration/build.gradle:The same structural issue — commands living in runtime libraries — applies across the framework.
This is not only a dependency-version problem; CLI code on the runtime classpath also causes
incorrect framework behavior. See #15377: the
dbmigration plugin transitively drags
grails-shell/ Spring Boot CLI onto a consumer's classpath,including
org.grails.cli.boot.SpringApplicationWebApplicationInitializer. In a classicservlet-container WAR deployment, the container auto-discovers that
WebApplicationInitializerandinvokes it; because a plain WAR has no
Start-Classin itsMANIFEST.MF,sourcesisnullandstartup fails with
Cannot invoke "String.split(String)" because "sources" is null. In other words,Spring behaves differently — and breaks — precisely because CLI components that assume a standalone
executable JAR are on the runtime classpath. The current workaround is a manual
bootWar { classpath = classpath.filter { … } }exclusion.Removing CLI code from the runtime classpath entirely — as this proposal does — eliminates that whole
class of failure, not just the specific NPE.
Root cause (evidence)
Commands are only ever executed by the CLI, and the framework is already loosely coupled at every
integration seam:
GlobalGrailsClassInjectorTransformationClassHelper.make('grails.dev.commands.ApplicationCommand')+ name-basedisSubclassOfOrImplementsInterfaceconfigureApplicationCommands'grails.dev.commands.ApplicationCommand'string constantgrails-shell-cliApplicationContextCommandFactoryclassLoader.loadClass('grails.dev.commands.ApplicationContextCommandRegistry')grails-consoleGrailsApplicationContextCommandRunnerApplicationContextCommandRegistry.instance.findCommand(...)grails-web-bootand the core plugin manager contain zero references tograils.dev.commands; anormal
bootRun/request cycle never loads the command infrastructure, and commands are not ascanned artefact type (they are registered via a factories file, not artefact scanning), so command
classes are never class-loaded at boot. Removing the command contract from the runtime classpath is
therefore safe — no
NoClassDefFoundErroron any non-command path.The command package itself (
grails/dev/commands/**) depends only on lightweight core/bootstraptypes (
grails.codegen.*,grails.util.*,org.grails.build.parsing.CommandLine,org.grails.io.support.*) — not ongrails-shell-cli.Conclusion: commands are logically CLI-only; the machinery references them by name/reflection, so
relocating them requires no change to the machinery. Only command implementors hard-depend on the
contract.
Goals
grails-shell/grails-shell-cli) on any application runtimeclasspath — including
bootRunand packagedbootJar/bootWarartifacts. This fixes both theGroovy-version conflict and runtime-correctness failures such as the WAR-deployment NPE in
Split CLI Dependencies from runtime classpath #15377 (CLI-only Spring Boot components must not be
present when the app runs).
Non-goals
grails dbm-update,grails url-mappings-report,grails generate-controller, etc. are unchanged).grails-app/commandssource location.grails-shell-cliprofile commands (create-app, etc.), which are already build/CLI-time.Proposed design
1. Commands become a
cliclassifier via Gradle feature variants (no subprojects)Each command-bearing module keeps its coordinate and gains a feature variant whose source set
holds only the commands. Gradle publishes it as a
…-cli.jarclassifier with its own dependencyset in Gradle Module Metadata, so the
clivariant's dependencies (e.g.grails-shell-cli) do notattach to the default variant.
sourceSets { cli } // src/cli/groovy — dbmigration: relocate grails-app/commands here java { registerFeature('cli') { usingSourceSet(sourceSets.cli) capability('org.apache.grails', 'grails-scaffolding-cli', project.version) } } dependencies { cliImplementation project(path) // the module's own default variant cliImplementation 'org.apache.grails:grails-core:cli' // command contract (see §2) cliImplementation('org.apache.grails:grails-shell-cli') // CLI-only; off the default graph }2. The whole
dev.commandspackage becomesgrails-core:cliMoving the
ApplicationCommandcontract to theclitier pulls its collaborators with it(
ApplicationContextCommandRegistryimports the contract). So the entiregrails/dev/commands/**package relocates into the
grails-core:clifeature variant:ApplicationCommand,GrailsApplicationCommand,ExecutionContextApplicationContextCommandRegistryio/FileSystemInteraction(+Impl),template/TemplateRenderer(+Impl),template/TemplateExceptionConfigReportCommandThe default
grails-corejar then contains no command package at all — only the AST transform'sstring reference remains (no compile dependency).
grails-core:cliis the shared contract everyother
clivariant depends on.3. Dedicated
META-INF/grails-cli.factories(clean break)Command registrations move out of
grails.factoriesinto their own file, so command metadata onlyever lives in
clijars and tooling can look it up specifically:META-INF/grails.factories→ runtime extension registrations (ArtefactHandler,TraitInjector).META-INF/grails-cli.factories→grails.dev.commands.ApplicationCommand=….Because this is a major release, there is no dual read: readers target
grails-cli.factoriesonly; the legacy
grails.factoriesis not consulted for commands.'META-INF/grails.factories'CommandFactoriesTransformation(ingrails-core:cli, §4) writes'META-INF/grails-cli.factories'into theclisource set outputApplicationContextCommandRegistry→GrailsFactoriesLoader.loadFactories(ApplicationCommand)FactoriesLoaderSupport.FACTORIES_RESOURCE_LOCATION(single class ingrails-gradle/model, extended by the runtimeGrailsFactoriesLoaderand used by the Gradle plugin)META-INF/grails-cli.factories4. Command registration moves to a dedicated transform in
grails-core:cliToday
GlobalGrailsClassInjectorTransformation(a global transform ingrails-core) auto-registerscommands: it detects any compiled class implementing the command interface — by name, via
isSubclassOfOrImplementsInterfaceagainst theAPPLICATION_CONTEXT_COMMAND_CLASSstring constant —and appends it to
grails.factories. That is why it references the command class name: name-basedauto-detection.
Once the contract moves to
grails-core:cli, leaving that branch ingrails-corewould keep ahardcoded reference to a class that no longer lives in
grails-core— a layering leak. So the commandbranch is extracted into its own global transform,
CommandFactoriesTransformation, shipped ingrails-core:cli(registered via that artifact's ownMETA-INF/services/org.codehaus.groovy.transform.ASTTransformation).grails-datamapping-corealready ships two of its own global transforms this way;global transforms compose across jars on the compile classpath.
grails-core:cliis on the compileclasspath — which is guaranteed whenever a command compiles, since a class implementing
org.apache.grails.core.cli.ApplicationCommandcan only compile if that contract resolves. Thedetector therefore exists precisely when it can match (tighter than today, where the core transform
runs everywhere and usually matches nothing).
META-INF/grails-cli.factories(the separate file, §3), so itnever touches
grails.factories. Both remain global transforms with definedTransformWithPriority/GroovyTransformOrderslots.updateGrailsFactoriesWithType,loadFromFile,resolveCompilationTargetDirectory, usingPropertyFileUtilsfromgrails-gradle/common) is extracted into a marker-agnosticFactoriesFileWriterutil kept ingrails-coreand reused by both transforms (grails-core:clialready depends ongrails-core,so this adds no improper coupling; the util knows nothing about commands).
Net:
grails-core's transform drops the command branch and theAPPLICATION_CONTEXT_COMMAND_CLASSconstant —
grails-coreno longer references any command type. Two references legitimately remain, bothin CLI/build tooling (not
grails-coreruntime): the Grails Gradle plugin's command-class string(build-time task discovery) and shell-cli's reflective registry lookup.
5. New
grailsCliGradle configuration (notconsole, notdevelopmentOnly)The command tier needs a classpath shape no stock configuration provides: compile-visible (so
grails-app/commands/**compile against the cli-only contract) + present on the command-runnerJVM + scanned for
grails-cli.factories+ on neitherruntimeClasspathnorbootRun. The Grails Gradle plugin adds a purpose-builtgrailsCliconfiguration with exactly theseproperties:
grailsCliand wire it (validated againstGrailsGradlePlugin): create a dependencybucket
grailsCli(canBeResolved=false,canBeConsumed=false);compileClasspath.extendsFrom (grailsCli)(+testCompileClasspath) for compile visibility — the same trickcompileOnlyuses;do not let
runtimeClasspathextend it (so it is excluded frombootJar/bootWar, whichpackage
runtimeClasspath).bootRunis unaffected — the plugin'sBootRun.configureEachblocksnever modify the classpath, so
bootRunuses Spring Boot'smain.runtimeClasspath + developmentOnly. For command tasks, add a resolvable view (e.g.grailsCliClasspathextendinggrailsCli) — mirroring howconsoleis resolved asruntimeClasspath + consoletoday.console:configureApplicationCommandsbuilds its classpath frombuildClasspath(project, runtimeClasspath, grailsCli)instead ofconsole(
GrailsGradlePluginline 753); the dbm-style command-runner classpaths (lines 1243/1274) thatappend
consoleswitch tograilsCli. Theconsole/shelltasks keepconsoleuntouched.runCommand/runScripttasks and the interactive shell) resolvesfrom
grailsCliat execution time viaGrailsApplicationContextCommandRegistry. Per-commandnamed tasks keep discovering names from the buildscript classloader (see §7); the transform now
emits
grails-cli.factories, so updateFactoriesLoaderSupport's command lookup to that filename.grails-core:cli(and applied plugins':cliclassifiers) ontograilsClisocommand authoring works out of the box in generated apps.
consoleremains solely about the console/shell tools;grailsCliis solely about CLI commands.6. Package rename to
org.apache.grails.*(JPMS-safe)Since the code is moving, the command packages are renamed to the repo's canonical
org.apache.grails.*namespace (this build is already mid-migration to it), replacing the legacygrails.dev.commands.*. Each:clivariant gets a unique leaf package so no package is eversplit across artifacts (JPMS forbids split packages), and each
:clijar sets a distinctAutomatic-Module-Name(required because a module and its:cliclassifier share one coordinate;no
Automatic-Module-Nameis set today, so names currently derive from filenames).Note
org.apache.grails.cliis already owned bygrails-forge/grails-cliand must not be reused.:clivariantAutomatic-Module-Namegrails-core:cliorg.apache.grails.core.cli(wholedev.commandspackage)org.apache.grails.core.cligrails-web-url-mappings:cliorg.apache.grails.web.mapping.cliorg.apache.grails.web.mapping.cligrails-scaffolding:cliorg.apache.grails.scaffolding.cliorg.apache.grails.scaffolding.cligrails-data-hibernate5/grails-plugin:cliorg.apache.grails.data.hibernate5.cli…hibernate5.cligrails-data-hibernate7/grails-plugin:cliorg.apache.grails.data.hibernate7.cli…hibernate7.cligrails-data-hibernate5/dbmigration:cliorg.apache.grails.data.hibernate5.dbmigration.cli…hibernate5.dbmigration.cligrails-data-hibernate7/dbmigration:cliorg.apache.grails.data.hibernate7.dbmigration.cli…hibernate7.dbmigration.cliThe rename cascades to the name/reflection references (all updated to the new FQNs): the AST
transform's command-class string constant, the Gradle plugin's
APPLICATION_CONTEXT_COMMAND_CLASSconstant, shell-cli's reflective
loadClass('org.apache.grails.core.cli.ApplicationContextCommandRegistry'),and the profile
Command.groovytemplate import. The upgrade guide documents the user-facing mappinggrails.dev.commands.* → org.apache.grails.core.cli.*for application command classes.7. Consumer model — two surfaces, both supported
Command consumption has two surfaces today, and the design must serve both:
dbmUpdate, …)configureApplicationCommandscallsFactoriesLoaderSupport.loadFactoryNames(...)with the default classloaderbuildscript { dependencies { classpath … } }runtimeClasspath + consoletoday)dependenciesThis is why command libraries often have to be on the
buildscriptclasspath: task names areregistered at configuration time by scanning the plugin's own classloader.
Target design (validated against
GrailsGradlePlugin+ the configuration cache):grailsCli. The genericrunCommand/runScripttasks (and theinteractive
grails <cmd>shell) launchGrailsApplicationContextCommandRunner, which discovers thecommand at execution time via
ApplicationContextCommandRegistryscanning the classpath. Theirclasspath is a lazy
FileCollection; rerouting it fromconsoletograilsCliis CC-safe. So asingle
grailsCli 'group:artifact:cli'independencies { }is sufficient to run any command(
grails <cmd>or./gradlew runCommand -Pargs="<cmd>"), with full configuration-cache support.dbmUpdate) stay discovered from the buildscript classloader —unchanged from today (
FactoriesLoaderSupport.loadFactoryNames(...)at line 751 reads plugin-classpath resources, resolving no project configuration). Getting these convenience tasks therefore
requires the
:clijar onbuildscript { classpath … }.grailsCli. Deriving per-command task names from theproject
grailsCliconfiguration would force resolving it (and reading inside its jars) atconfiguration time — eager and CC-hostile for consumer apps — and it is unnecessary, since running
commands already works via the generic runner + shell.
The app builds and ships normally; the
:cliclassifier is available for compiling/running commandsvia the CLI but is absent from
runtimeClasspath/bootRun, so it is not in the boot/war artifact.Opt-in is explicit: an app that wants no commands omits the
grailsClientries (auto-provisioning canbe disabled).
8. Compatibility — clean break in 8.0.x (no dual read)
grails-cli.factoriesautomatically via the transform — no source change needed forconvention-based commands.
src/main/resources/META-INF/grails.factoriesto.../grails-cli.factories.:cliclassifier consumed viagrailsCli; the default plugin jar no longercarries commands.
intentional and documented in the upgrade guide.
Full command inventory
Verified implementors of
ApplicationCommand/GrailsApplicationCommand(production sources):grails-core—ConfigReportCommand(GrailsApplicationCommandis the interface, not a command)grails-web-url-mappings—UrlMappingsReportCommandgrails-data-hibernate5/grails-plugin—SchemaExportCommandgrails-data-hibernate7/grails-plugin—SchemaExportCommandgrails-scaffolding— 9 commands (GenerateAll,GenerateController,GenerateAsyncController,GenerateService,GenerateViews,GenerateScaffoldAll,CreateScaffoldController,CreateScaffoldService,InstallTemplates)grails-data-hibernate5/dbmigration— 29dbm-*commandsgrails-data-hibernate7/dbmigration— 29dbm-*commandsNot commands (no action):
grails-profiles/base/templates/artifacts/Command.groovyis the appscaffolding template;
grails-shell-cliprofile commands are already build/CLI-time.Per-module changes (
clifeature variant contents)cliclassifier contentsclideps beyond contractgrails-coregrails/dev/commands/**(contract + registry + infra +ConfigReportCommand)grails-web-url-mappingsUrlMappingsReportCommandUrlMappingsHolder(own default variant)grails-data-hibernate5/grails-pluginSchemaExportCommandgrails-data-hibernate7/grails-pluginSchemaExportCommandgrails-scaffoldingCommandLineHelper,SkipBootstrap)Model(own default variant)grails-data-hibernate5/dbmigrationdbm-*+ command traits +src/main/scripts/*grails-shell-cli, plugin's default variantgrails-data-hibernate7/dbmigrationdbm-*+ command traits +src/main/scripts/*grails-shell-cli, plugin's default variantFor dbmigration the boundary was verified acyclic — runtime classes (plugin descriptor,
liquibase/**,shared support) never reference the
commandpackage — so the runtime (default) variant dropsgrails-shell-clientirely.Work breakdown (phased)
Phase 0 —
grails-core:cli+ the factories fileclisource set tograils-core; movegrails/dev/commands/**into it, renamed toorg.apache.grails.core.cli.**;registerFeature('cli')withAutomatic-Module-Name.FactoriesLoaderSupport(+GrailsFactoriesLoader);point
ApplicationContextCommandRegistryatgrails-cli.factories.FactoriesFileWriterhelper ingrails-core; remove the commandbranch +
APPLICATION_CONTEXT_COMMAND_CLASSconstant fromGlobalGrailsClassInjectorTransformation;add
CommandFactoriesTransformation(+ its service registration) tograils-core:cli, writinggrails-cli.factoriesvia the shared helper. Update the Gradle plugin constant, the shell-clireflective class name, and the profile template import to the new FQNs.
Phase 1 —
grailsCliconfiguration4. Register
grailsCli; wire compile visibility; keep it offruntimeClasspath/bootRun.5. Reroute the command execution classpaths (
configureApplicationCommandsper-command tasks,runCommand,runScript, and dbm command-runner tasks) fromconsoletograilsCli, keeping thelazy-
FileCollectionpattern. Leave per-command name discovery on the buildscript classloader (donot resolve
grailsCliat config time — preserves configuration-cache compatibility for apps).Auto-provision
grails-core:cli(+ applied plugins':cli).Phase 2 — dbmigration (the original driver)
6. Add
clifeature to eachdbmigrationplugin; movegrails-app/commands, command traits, andsrc/main/scripts/*(+ their tests) into theclisource set. Removegrails-shell-clifrom thedefault variant. Update example apps to
implementation(runtime) +grailsCli(:cli).Phase 3 — remaining framework commands
7. Add
clifeatures tograils-scaffolding,grails-web-url-mappings, and the two Hibernategrails-plugins (schema-export). Move commands + command-only helpers; update example apps.Phase 4 — docs & verification
8. What's New entry; Upgrade guide section (breaking:
:cliclassifier ongrailsCli;grails-cli.factoriesclean break; Grails 7 command plugins must be rebuilt/migrated).9. Plugin best-practices section: "Ship CLI commands as a
cliclassifier" pattern.10. Full build + violations + module test suites; verify commands resolve in the shell and are absent
from runtime artifacts and from
bootRun.Change surface (key files)
grails-core/src/main/groovy/grails/dev/commands/**→grails-coreclisource set, renamed toorg.apache.grails.core.cli.**grails-core/.../GlobalGrailsClassInjectorTransformation.groovy— remove the command branch and theAPPLICATION_CONTEXT_COMMAND_CLASSconstantgrails-core/.../FactoriesFileWriter(new) — extract the marker-agnostic factories-writing helper; reused by both transformsgrails-core:cliCommandFactoriesTransformation(new) + itsMETA-INF/services/org.codehaus.groovy.transform.ASTTransformation— writesgrails-cli.factoriesgrails-shell-cli/.../ApplicationContextCommandFactory.groovy— reflectiveloadClass('org.apache.grails.core.cli.ApplicationContextCommandRegistry')grails-profiles/base/templates/artifacts/Command.groovy— import →org.apache.grails.core.cli.GrailsApplicationCommand:clivariant — uniqueorg.apache.grails.*.clipackage + explicitAutomatic-Module-Namegrails-gradle/model/.../FactoriesLoaderSupport.groovy— location-parameterized lookupgrails-core/.../GrailsFactoriesLoader.groovy— location-aware overloadgrails-gradle/plugins/.../GrailsGradlePlugin.groovy—grailsCliconfig; reroute command tasks offconsole(lines 753, 1243, 1274); readgrails-cli.factories; auto-provision:clibuild.gradleof each command-bearing module —clisource set +registerFeature('cli')+cli*depsgrails-test-examples/**—implementation+grailsCliwiringgrails-doc/src/en/guide/introduction/whatsNew.adocgrails-doc/src/en/guide/upgrading/upgrading80x.adocgrails-doc/src/en/guide/plugins/creatingAndInstallingPlugins.adocRejected alternatives
grails-<module>-clisubprojects (+ agrails-cli-coremodule). Works, but proliferatespublished coordinates,
settings.gradleentries and BOM entries. Thecliclassifier achieves thesame isolation on existing coordinates.
artifact(classifier: 'cli')). Separates the jar but not itsdependencies —
grails-shell-cliwould still leak via the shared POM. Feature variants fix this.consoleconfiguration.consoleis for the interactive console/shell tools;overloading it conflates two concerns and it is not compile-visible for command authoring.
developmentOnly. Not on the compile classpath (breaks command authoring against the cli-onlycontract) and it is on the
bootRunclasspath (re-addsgrails-shell-cli+ mismatched Groovyto the running dev app — the original bug). Fails on both counts.
Risks & open questions
grailsCliand the command-task reroute are additions toGrailsGradlePlugin. Larger blast radius than a pure library change; needs its own tests.(Validated:
grailsClias a bucket +compileClasspath.extendsFrom+ a resolvable view givescompile visibility without
runtimeClasspath/bootRun/bootJar— see §5.)grails-app/commandssource-set relocation (validated).configureGrailsSourceDirs(line 781)auto-adds every
grails-app/<subdir>to main. This convention is unchanged for apps (theircommands stay in
main). For framework plugins only, relocate command sources to theclisource set (
src/cli/groovy) — sincegrails-app/commandsthen no longer exists,mainwon't pickit up; alternatively add
'commands'to the mutableexcludedGrailsAppSourceDirs. Ensure theclisource set has
grails-coreon itscompileClasspathso the global AST transform runs and emitsgrails-cli.factoriesinto theclijar.:cliclassifier is a touch more verbosethan a standalone module; mitigated by the plugin auto-provisioning
grails-core:cliand by docs.mitigation is documentation, not a shim.
runtimeClasspath + grailsCli) mustinclude
grails-core:cli; confirm the plugin wiresgrailsCliinto every command-runner task.CommandFactoriesTransformationingrails-core:cliadds a globaltransform alongside
grails-core's. Precedent exists (grails-datamapping-coreships two), and thetwo write different files so there is no contention; still, give it an explicit
TransformWithPriorityorder and verify it activates on both frameworkclisource sets and appgrails-app/commandscompilation (both havegrails-core:clion the compile classpath).Naming / conventions (decided)
<module>:cli— a feature-variant classifier containing that module's commands (andcommand-only helpers).
grails-core:cliadditionally holds the shared command contract/registry.grailsCli— the app/plugin Gradle configuration that carries:cliclassifiers: compile-visibleand on the command-runner classpath, but not on
runtimeClasspath/bootRun. BothgrailsCli(project dependencies) and
buildscript { classpath }placement register command tasks.org.apache.grails.<area>.cli— the package for each:clivariant; unique per artifact(JPMS: no split packages), replacing legacy
grails.dev.commands.*. Each:clijar sets amatching
Automatic-Module-Name.org.apache.grails.cliis reserved (grails-forge/grails-cli).META-INF/grails-cli.factories— command registrations, separate fromgrails.factories.References
components (
SpringApplicationWebApplicationInitializer) transitively on the runtime classpath viadbmigration →
grails-shell.grails-data-hibernate{5,7}/dbmigration/build.gradle— the existinggrails-shell-cliGroovyexclusion + TODO calling for this split.
jdaugherty commentedon Jul 8, 2026
We decided to do the split but move away from teh classifier and use a separate jar name instead.
[-]Grails 8 - grails-data-hibernate5-dbmigration bootWar: Cannot invoke "String.split(String)" because "sources" is null - In a classic servlet-container WAR deployment[/-][+]Split CLI Dependencies from runtime classpath[/+]jdaugherty commentedon Jul 9, 2026
This was the updated plan that I initially used to create the associated PR
Proposal: Move Grails CLI commands into companion
-cliartifacts (Grails 8.0.x)Summary
Grails ships its dev/CLI commands (
grails.dev.commands.ApplicationCommand) inside runtimelibraries —
grails-core,grails-web-url-mappings, the Hibernate plugins,grails-scaffolding,and the two
dbmigrationplugins. Some of these command sets drag heavyweight, CLI-onlydependencies (notably
grails-shell/grails-shell-cli) onto the application runtime classpath,causing two classes of failure: dependency-version conflicts (a mismatched Groovy) and incorrect
framework behavior — e.g. a CLI-only Spring Boot servlet initializer that breaks WAR deployment
(#15377).
This proposal removes command code from every runtime artifact by publishing each module's commands
as a companion artifact with its own Maven coordinate, suffixed
-cli: the module'smainsource set publishes as today (
org.apache.grails:grails-core→grails-core.jar) and a newclisource set in the same Gradle project publishes as a second publication under
org.apache.grails:grails-core-cli→grails-core-cli.jar, with its own POM/module metadataand its own dependency graph. Commands are keyed off a dedicated
META-INF/grails-cli.factoriesfile and consumed through a new, purpose-built Gradleconfiguration
grailsCli(with existingbuildscript { classpath }placement still supported).The entire
grails/dev/commands/**package (command contract + registry + infrastructure +ConfigReportCommand) moves intograils-core-cli, renamed toorg.apache.grails.core.cli.*ona JPMS-safe, per-artifact-unique package scheme, so the default
grails-corejar — and every defaultplugin jar — ships zero command code and zero command contract. No new Gradle subprojects are
created; the new coordinates are additional publications of the existing projects.
This lands in the Grails 8.0.x major release as a clean break (no backward-compatibility shim).
Background & problem
The Hibernate 5/7 database-migration plugins depend on
grails-shell-clipurely so theirdbm-*commands compile and can be located by the shell. Because each plugin is a single artifact used on
both the build and runtime classpaths, that dependency (and its mismatched Groovy) leaks into
applications. The current workaround is an explicit exclusion + TODO in
grails-data-hibernate{5,7}/dbmigration/build.gradle:The same structural issue — commands living in runtime libraries — applies across the framework.
This is not only a dependency-version problem; CLI code on the runtime classpath also causes
incorrect framework behavior. See #15377: the
dbmigration plugin transitively drags
grails-shell/ Spring Boot CLI onto a consumer's classpath,including
org.grails.cli.boot.SpringApplicationWebApplicationInitializer. In a classicservlet-container WAR deployment, the container auto-discovers that
WebApplicationInitializerandinvokes it; because a plain WAR has no
Start-Classin itsMANIFEST.MF,sourcesisnullandstartup fails with
Cannot invoke "String.split(String)" because "sources" is null. In other words,Spring behaves differently — and breaks — precisely because CLI components that assume a standalone
executable JAR are on the runtime classpath. The current workaround is a manual
bootWar { classpath = classpath.filter { … } }exclusion.Removing CLI code from the runtime classpath entirely — as this proposal does — eliminates that whole
class of failure, not just the specific NPE.
Root cause (evidence)
Commands are only ever executed by the CLI, and the framework is already loosely coupled at every
integration seam:
GlobalGrailsClassInjectorTransformationClassHelper.make('grails.dev.commands.ApplicationCommand')+ name-basedisSubclassOfOrImplementsInterfaceconfigureApplicationCommands'grails.dev.commands.ApplicationCommand'string constantgrails-shell-cliApplicationContextCommandFactoryclassLoader.loadClass('grails.dev.commands.ApplicationContextCommandRegistry')grails-consoleGrailsApplicationContextCommandRunnerApplicationContextCommandRegistry.instance.findCommand(...)grails-web-bootand the core plugin manager contain zero references tograils.dev.commands; anormal
bootRun/request cycle never loads the command infrastructure, and commands are not ascanned artefact type (they are registered via a factories file, not artefact scanning), so command
classes are never class-loaded at boot. Removing the command contract from the runtime classpath is
therefore safe — no
NoClassDefFoundErroron any non-command path.The command package itself (
grails/dev/commands/**) depends only on lightweight core/bootstraptypes (
grails.codegen.*,grails.util.*,org.grails.build.parsing.CommandLine,org.grails.io.support.*) — not ongrails-shell-cli.Conclusion: commands are logically CLI-only; the machinery references them by name/reflection, so
relocating them requires no change to the machinery. Only command implementors hard-depend on the
contract.
Goals
grails-shell/grails-shell-cli) on any application runtimeclasspath — including
bootRunand packagedbootJar/bootWarartifacts. This fixes both theGroovy-version conflict and runtime-correctness failures such as the WAR-deployment NPE in
Split CLI Dependencies from runtime classpath #15377 (CLI-only Spring Boot components must not be
present when the app runs).
org.apache.grails:<module>-cli) — resolvable by anybuild tool without Gradle Module Metadata, classifiers, or capability syntax.
-cliartifacts are additional publications ofexisting projects.
Non-goals
grails dbm-update,grails url-mappings-report,grails generate-controller, etc. are unchanged).grails-app/commandssource location.grails-shell-cliprofile commands (create-app, etc.), which are already build/CLI-time.Proposed design
1. Commands become a companion
-cliartifact (own coordinate, same Gradle project)Each command-bearing module keeps its coordinate and gains a
clisource set(
src/cli/groovy) holding only the commands. That source set is published as a secondpublication of the same project under its own coordinate — the module's artifactId with a
-clisuffix — carrying its own dependency set in its own POM and Gradle Module Metadata. The
CLI-only dependencies (e.g.
grails-shell-cli) therefore never appear in the default artifact'smetadata at all.
Mechanically (encapsulated in a build-logic convention plugin, see §1a):
sourceSets { cli } // src/cli/groovy — dbmigration: relocate grails-app/commands here java { registerFeature('cli') { usingSourceSet(sourceSets.cli) // capability == the published -cli coordinate, so in-repo variant selection // and the published GMM agree capability('org.apache.grails', "${project.name}-cli", project.version) } } dependencies { cliApi project(path) // the module's own default artifact cliApi(project(':grails-core')) { // command contract (see §2) capabilities { requireCapability('org.apache.grails:grails-core-cli') } } cliImplementation(project(':grails-shell-cli')) // CLI-only; off the default graph }javacomponent(
components.java.withVariantsFromConfiguration(cliApiElements|cliRuntimeElements) { skip() }),so the default publication (
org.apache.grails:grails-core) contains no trace of the cli tier —no classifier jar, no
<optional>POM pollution, no extra GMM variants.softwareComponentFactory.adhoc('cli')) is built fromcliApiElements/cliRuntimeElements(+ cli sources/javadoc jars) and published as a secondMavenPublicationwithartifactId = "${pomArtifactId ?: project.name}-cli".requireCapabilityform above); Gradle maps that project dependency to theorg.apache.grails:<module>-clicoordinate in the published POM/GMM because the publication ownsthat capability. External consumers just use the plain coordinate.
1a. Publishing wiring (grails-publish + build-logic + BOM)
Publishing in this build is layered: the external
org.apache.grails.gradle:grails-publishplugin creates the (single)
mavenpublication per project and handles signing/Nexus staging, andthe in-repo
org.apache.grails.buildsrc.publishconvention configures theGrailsPublishExtensionplus checksum/artifact-list tasks. Today grails-publish assumes one publication per project
(one
artifactId, one component). This proposal extends it — we own grails-publish, so it will beenhanced rather than bypassed:
grails-gradle-publish, 8.x line; grails-core then bumps itspinned version in
dependencies.gradle). Signing (sign(publishing.publications)), Nexusstaging, repositories, and the
installalias are already publication-agnostic — a secondpublication is covered for free. What is hardcoded to the single publication and must change:
GrailsPublishExtensiongains an additional publications API — each registration pairs anartifactId with a named software component (e.g.
additionalPublication('cli') { artifactId = "${name}-cli"; componentName = 'cli' }).publications.create(gpe.publicationName...)+doAddArtefactattachingcomponents.java) loops over primary + additional registrations;the inline POM-metadata block (license/developers/scm/
withXml) is extracted into a methodapplied to every publication.
versionMappinghardcodesfromResolutionOf('runtimeClasspath')— the resolutionconfiguration becomes per-publication (
cliRuntimeClasspathfor the cli publication).setDependencyVersionsresolves onlycompileClasspath/runtimeClasspath(+ testFixtures) to patch missing POM versions — it must also resolve the additional
publication's classpaths (
cliCompileClasspath/cliRuntimeClasspath), or cli-only deps failwith "No version found for dependency".
publication gets its own sources/javadoc jars built from its source set. Latent leak to
fix: the existing
sourcesJardoesjar.from sourceSets.collect { it.allSource }(allsource sets), which would put cli sources into the main sources jar — exclude source sets
owned by additional publications.
getDefaultExtraArtifact(thegrails-plugin.xml/plugin-classifier artifact) staysprimary-publication-only.
org.apache.grails.gradle.grails-plugin-cli(
GrailsCliArtifactGradlePluginin grails-gradle/plugins), applied by each command-bearingmodule — the framework dogfoods the same plugin third-party authors use. It encapsulates
everything in §1: the
clisource set, feature registration, skipping the cli variants from thejavacomponent, the adhocclicomponent, theGrails-Cli-Artifactruntime-jar manifestmarker, default cli dependencies (opt-out via
cliArtifact { defaultDependencies = false },which framework modules use to wire project dependencies instead), registration with
grails-publish, and the
cliArtifactIdext tag downstream build logic uses to discover theextra coordinate. (A build-logic wrapper was tried and deleted — it reduced to two lines of
configuration each module now sets directly.)
grails-bom/baseauto-enumerates published subprojects (api project(...)) — that onlycaptures each project's primary coordinate. Extend the enumeration to also add a constraint for
org.apache.grails:${cliArtifactId}:${projectVersion}for every project tagged by the conventionplugin, and extend the
projectArtifactIds/projectCoordinatePropertiesmaps used byExtractDependenciesTaskaccordingly. No hand-maintained list.savePublishedArtifacts,publishedChecksums, and theversion-mapping block in
PublishPluginalready iteratepublications.withType(MavenPublication)generically;
ensureJarContainsASFFilesalready covers everyJartask (the cli jar getsLICENSE/NOTICE for free).
publish-root-config.gradle'spublishedProjectslist is unchanged —the cli publications live in projects already on it.
2. The whole
dev.commandspackage becomesgrails-core-cliMoving the
ApplicationCommandcontract to the-clitier pulls its collaborators with it(
ApplicationContextCommandRegistryimports the contract). So the entiregrails/dev/commands/**package relocates into the
clisource set ofgrails-core, published asorg.apache.grails:grails-core-cli:ApplicationCommand,GrailsApplicationCommand,ExecutionContextApplicationContextCommandRegistryio/FileSystemInteraction(+Impl),template/TemplateRenderer(+Impl),template/TemplateExceptionConfigReportCommandThe default
grails-corejar then contains no command package at all — only the AST transform'sstring reference remains (no compile dependency).
grails-core-cliis the shared contract everyother
-cliartifact depends on.3. Dedicated
META-INF/grails-cli.factories(clean break)Command registrations move out of
grails.factoriesinto their own file, so command metadata onlyever lives in
-clijars and tooling can look it up specifically:META-INF/grails.factories→ runtime extension registrations (ArtefactHandler,TraitInjector).META-INF/grails-cli.factories→grails.dev.commands.ApplicationCommand=….Because this is a major release, there is no dual read: readers target
grails-cli.factoriesonly; the legacy
grails.factoriesis not consulted for commands.'META-INF/grails.factories'CommandFactoriesTransformation(ingrails-core-cli, §4) writes'META-INF/grails-cli.factories'into theclisource set outputApplicationContextCommandRegistry→GrailsFactoriesLoader.loadFactories(ApplicationCommand)FactoriesLoaderSupport.FACTORIES_RESOURCE_LOCATION(single class ingrails-gradle/model, extended by the runtimeGrailsFactoriesLoaderand used by the Gradle plugin)META-INF/grails-cli.factories4. Command registration moves to a dedicated transform in
grails-core-cliToday
GlobalGrailsClassInjectorTransformation(a global transform ingrails-core) auto-registerscommands: it detects any compiled class implementing the command interface — by name, via
isSubclassOfOrImplementsInterfaceagainst theAPPLICATION_CONTEXT_COMMAND_CLASSstring constant —and appends it to
grails.factories. That is why it references the command class name: name-basedauto-detection.
Once the contract moves to
grails-core-cli, leaving that branch ingrails-corewould keep ahardcoded reference to a class that no longer lives in
grails-core— a layering leak. So the commandbranch is extracted into its own global transform,
CommandFactoriesTransformation, shipped ingrails-core-cli(registered via that artifact's ownMETA-INF/services/org.codehaus.groovy.transform.ASTTransformation).grails-datamapping-corealready ships two of its own global transforms this way;global transforms compose across jars on the compile classpath.
grails-core-cliis on the compileclasspath — which is guaranteed whenever a command compiles, since a class implementing
org.apache.grails.core.cli.ApplicationCommandcan only compile if that contract resolves. Thedetector therefore exists precisely when it can match (tighter than today, where the core transform
runs everywhere and usually matches nothing).
META-INF/grails-cli.factories(the separate file, §3), so itnever touches
grails.factories. Both remain global transforms with definedTransformWithPriority/GroovyTransformOrderslots.updateGrailsFactoriesWithType,loadFromFile,resolveCompilationTargetDirectory, usingPropertyFileUtilsfromgrails-gradle/common) is extracted into a marker-agnosticFactoriesFileWriterutil kept ingrails-coreand reused by both transforms (grails-core-clialready depends ongrails-core,so this adds no improper coupling; the util knows nothing about commands).
Net:
grails-core's transform drops the command branch and theAPPLICATION_CONTEXT_COMMAND_CLASSconstant —
grails-coreno longer references any command type. Two references legitimately remain, bothin CLI/build tooling (not
grails-coreruntime): the Grails Gradle plugin's command-class string(build-time task discovery) and shell-cli's reflective registry lookup.
5. New
grailsCliGradle configuration (notconsole, notdevelopmentOnly)The command tier needs a classpath shape no stock configuration provides: compile-visible (so
grails-app/commands/**compile against the cli-only contract) + present on the command-runnerJVM + scanned for
grails-cli.factories+ on neitherruntimeClasspathnorbootRun. The Grails Gradle plugin adds a purpose-builtgrailsCliconfiguration with exactly theseproperties:
grailsCliand wire it (validated againstGrailsGradlePlugin): create a dependencybucket
grailsCli(canBeResolved=false,canBeConsumed=false);compileClasspath.extendsFrom (grailsCli)(+testCompileClasspath) for compile visibility — the same trickcompileOnlyuses;do not let
runtimeClasspathextend it (so it is excluded frombootJar/bootWar, whichpackage
runtimeClasspath).bootRunis unaffected — the plugin'sBootRun.configureEachblocksnever modify the classpath, so
bootRunuses Spring Boot'smain.runtimeClasspath + developmentOnly. For command tasks, add a resolvable view (e.g.grailsCliClasspathextendinggrailsCli) — mirroring howconsoleis resolved asruntimeClasspath + consoletoday.console:configureApplicationCommandsbuilds its classpath frombuildClasspath(project, runtimeClasspath, grailsCli)instead ofconsole(
GrailsGradlePluginline 753); the dbm-style command-runner classpaths (lines 1243/1274) thatappend
consoleswitch tograilsCli. Theconsole/shelltasks keepconsoleuntouched.runCommand/runScripttasks and the interactive shell) resolvesfrom
grailsCliat execution time viaGrailsApplicationContextCommandRegistry. Per-commandnamed tasks keep discovering names from the buildscript classloader (see §7); the transform now
emits
grails-cli.factories, so updateFactoriesLoaderSupport's command lookup to that filename.org.apache.grails:grails-core-cli(and applied plugins'-clicompanions) ontograilsCliso command authoring works out of the box in generated apps.consoleremains solely about the console/shell tools;grailsCliis solely about CLI commands.6. Package rename to
org.apache.grails.*(JPMS-safe)Since the code is moving, the command packages are renamed to the repo's canonical
org.apache.grails.*namespace (this build is already mid-migration to it), replacing the legacygrails.dev.commands.*. Each-cliartifact gets a unique leaf package so no package is eversplit across artifacts (JPMS forbids split packages — e.g. the module and its
-clicompanion mustnot both contain classes in the module's package), and each
-clijar sets an explicitAutomatic-Module-Namematching its package (noAutomatic-Module-Nameis set anywhere today, sonames currently derive from filenames; setting it explicitly makes the module name stable and
intentional).
Note
org.apache.grails.cliis already owned bygrails-forge/grails-cliand must not be reused.-cliartifactAutomatic-Module-Namegrails-core-cliorg.apache.grails.core.cli(wholedev.commandspackage)org.apache.grails.core.cligrails-web-url-mappings-cliorg.apache.grails.web.mapping.cliorg.apache.grails.web.mapping.cligrails-scaffolding-cliorg.apache.grails.scaffolding.cliorg.apache.grails.scaffolding.cligrails-data-hibernate5-cliorg.apache.grails.data.hibernate5.cli…hibernate5.cligrails-data-hibernate7-cliorg.apache.grails.data.hibernate7.cli…hibernate7.cligrails-data-hibernate5-dbmigration-cliorg.apache.grails.data.hibernate5.dbmigration.cli…hibernate5.dbmigration.cligrails-data-hibernate7-dbmigration-cliorg.apache.grails.data.hibernate7.dbmigration.cli…hibernate7.dbmigration.cliThe rename cascades to the name/reflection references (all updated to the new FQNs): the AST
transform's command-class string constant, the Gradle plugin's
APPLICATION_CONTEXT_COMMAND_CLASSconstant, shell-cli's reflective
loadClass('org.apache.grails.core.cli.ApplicationContextCommandRegistry'),and the profile
Command.groovytemplate import. The upgrade guide documents the user-facing mappinggrails.dev.commands.* → org.apache.grails.core.cli.*for application command classes.7. Consumer model — two surfaces, both supported
Command consumption has two surfaces today, and the design must serve both:
dbmUpdate, …)configureApplicationCommandscallsFactoriesLoaderSupport.loadFactoryNames(...)with the default classloaderbuildscript { dependencies { classpath … } }runtimeClasspath + consoletoday)dependenciesThis is why command libraries often have to be on the
buildscriptclasspath: task names areregistered at configuration time by scanning the plugin's own classloader.
Target design (validated against
GrailsGradlePlugin+ the configuration cache):grailsCli. The genericrunCommand/runScripttasks (and theinteractive
grails <cmd>shell) launchGrailsApplicationContextCommandRunner, which discovers thecommand at execution time via
ApplicationContextCommandRegistryscanning the classpath. Theirclasspath is a lazy
FileCollection; rerouting it fromconsoletograilsCliis CC-safe. So asingle
grailsCli 'org.apache.grails:<module>-cli'independencies { }is sufficient to runany command (
grails <cmd>or./gradlew runCommand -Pargs="<cmd>"), with fullconfiguration-cache support.
dbmUpdate) stay discovered from the buildscript classloader —unchanged from today (
FactoriesLoaderSupport.loadFactoryNames(...)at line 751 reads plugin-classpath resources, resolving no project configuration). Getting these convenience tasks therefore
requires the
-clijar onbuildscript { classpath … }.grailsCli. Deriving per-command task names from theproject
grailsCliconfiguration would force resolving it (and reading inside its jars) atconfiguration time — eager and CC-hostile for consumer apps — and it is unnecessary, since running
commands already works via the generic runner + shell.
Both forms are plain coordinates — no classifier or capability syntax anywhere in a consumer
build. The app builds and ships normally; the
-clicompanion is available for compiling/runningcommands via the CLI but is absent from
runtimeClasspath/bootRun, so it is not in the boot/warartifact. Opt-in is explicit: an app that wants no commands omits the
grailsClientries(auto-provisioning can be disabled).
8. Compatibility — clean break in 8.0.x (no dual read)
grails-cli.factoriesautomatically via the transform — no source change needed forconvention-based commands.
src/main/resources/META-INF/grails.factoriesto.../grails-cli.factories.-cliartifact consumed viagrailsCli; the default plugin jar nolonger carries commands.
intentional and documented in the upgrade guide.
Full command inventory
Verified implementors of
ApplicationCommand/GrailsApplicationCommand(production sources):grails-core—ConfigReportCommand(GrailsApplicationCommandis the interface, not a command)grails-web-url-mappings—UrlMappingsReportCommandgrails-data-hibernate5/grails-plugin—SchemaExportCommandgrails-data-hibernate7/grails-plugin—SchemaExportCommandgrails-scaffolding— 9 commands (GenerateAll,GenerateController,GenerateAsyncController,GenerateService,GenerateViews,GenerateScaffoldAll,CreateScaffoldController,CreateScaffoldService,InstallTemplates)grails-data-hibernate5/dbmigration— 29dbm-*commandsgrails-data-hibernate7/dbmigration— 29dbm-*commandsNot commands (no action):
grails-profiles/base/templates/artifacts/Command.groovyis the appscaffolding template;
grails-shell-cliprofile commands are already build/CLI-time.Per-module changes (
-cliartifact contents)-cliartifact contents-clideps beyond contractgrails-core→grails-core-cligrails/dev/commands/**(contract + registry + infra +ConfigReportCommand)grails-web-url-mappings→…-cliUrlMappingsReportCommandUrlMappingsHolder(own default artifact)grails-data-hibernate5→…-cliSchemaExportCommandgrails-data-hibernate7→…-cliSchemaExportCommandgrails-scaffolding→…-cliCommandLineHelper,SkipBootstrap)Model(own default artifact)grails-data-hibernate5-dbmigration→…-clidbm-*+ command traits +src/main/scripts/*grails-shell-cli, plugin's default artifactgrails-data-hibernate7-dbmigration→…-clidbm-*+ command traits +src/main/scripts/*grails-shell-cli, plugin's default artifactFor dbmigration the boundary was verified acyclic — runtime classes (plugin descriptor,
liquibase/**,shared support) never reference the
commandpackage — so the runtime (default) artifact dropsgrails-shell-clientirely.Work breakdown (phased)
Phase 0 — publishing infrastructure
org.apache.grails.gradle:grails-publish) to support additionalpublications per project (component + artifactId registration; POM metadata, signing,
sources/javadoc, staging parity with the primary publication). Release/consume the updated plugin.
org.apache.grails.gradle.grails-plugin-clishipped plugin (§1a):clisource set, feature, skip cli variants from the
javacomponent, adhocclicomponent, second publication
${artifactId}-cli,Automatic-Module-Name, manifest marker,cliArtifactIdtag.grails-bom/baseenumeration (+ExtractDependenciesTaskmaps) to emit constraints forevery tagged
-clicoordinate; verifyvalidateDependencyVersionspasses.Phase 1 —
grails-core-cli+ the factories file4. Apply the convention plugin to
grails-core; movegrails/dev/commands/**into theclisourceset, renamed to
org.apache.grails.core.cli.**.5. Add a location-parameterized overload to
FactoriesLoaderSupport(+GrailsFactoriesLoader);point
ApplicationContextCommandRegistryatgrails-cli.factories.6. Extract a marker-agnostic
FactoriesFileWriterhelper ingrails-core; remove the commandbranch +
APPLICATION_CONTEXT_COMMAND_CLASSconstant fromGlobalGrailsClassInjectorTransformation;add
CommandFactoriesTransformation(+ its service registration) tograils-core-cli, writinggrails-cli.factoriesvia the shared helper. Update the Gradle plugin constant, the shell-clireflective class name, and the profile template import to the new FQNs.
7. Verify the published output:
grails-core.pom/.modulecarry no cli variant or dependency;grails-core-cli.pom/.modulecarry the cli graph with in-repo capability deps mapped to the-clicoordinates.Phase 2 —
grailsCliconfiguration8. Register
grailsCli; wire compile visibility; keep it offruntimeClasspath/bootRun.9. Reroute the command execution classpaths (
configureApplicationCommandsper-command tasks,runCommand,runScript, and dbm command-runner tasks) fromconsoletograilsCli, keeping thelazy-
FileCollectionpattern. Leave per-command name discovery on the buildscript classloader (donot resolve
grailsCliat config time — preserves configuration-cache compatibility for apps).Auto-provision
grails-core-cli(+ applied plugins'-clicompanions).Phase 3 — dbmigration (the original driver)
10. Apply the convention plugin to each
dbmigrationplugin; movegrails-app/commands, commandtraits, and
src/main/scripts/*(+ their tests) into theclisource set. Removegrails-shell-clifrom the default artifact. Update example apps toimplementation(runtime) +grailsCli(…-dbmigration-cli).Phase 4 — remaining framework commands
11. Apply the convention plugin to
grails-scaffolding,grails-web-url-mappings, and the twoHibernate
grails-plugins (schema-export). Move commands + command-only helpers; update exampleapps.
Phase 5 — docs & verification
12. What's New entry; Upgrade guide section (breaking: commands move to
<module>-cliartifacts ongrailsCli;grails-cli.factoriesclean break; Grails 7 command plugins must berebuilt/migrated).
13. Plugin best-practices section: "Ship CLI commands as a companion
-cliartifact" pattern.14. Full build + violations + module test suites; verify commands resolve in the shell and are absent
from runtime artifacts and from
bootRun; verify a localpublishToMavenLocal/staging runproduces signed, checksummed
-cliartifacts alongside the primary ones.Change surface (key files)
GrailsPublishExtensiongrails-gradle/plugins/.../GrailsCliArtifactGradlePlugin(new shipped plugin) + testsgrails-bom/base/build.gradle— enumerate tagged-clicoordinates;ExtractDependenciesTaskartifactId/coordinate maps
grails-core/src/main/groovy/grails/dev/commands/**→grails-coreclisource set, renamed toorg.apache.grails.core.cli.**grails-core/.../GlobalGrailsClassInjectorTransformation.groovy— remove the command branch and theAPPLICATION_CONTEXT_COMMAND_CLASSconstantgrails-core/.../FactoriesFileWriter(new) — extract the marker-agnostic factories-writing helper; reused by both transformsgrails-core-cliCommandFactoriesTransformation(new) + itsMETA-INF/services/org.codehaus.groovy.transform.ASTTransformation— writesgrails-cli.factoriesgrails-shell-cli/.../ApplicationContextCommandFactory.groovy— reflectiveloadClass('org.apache.grails.core.cli.ApplicationContextCommandRegistry')grails-profiles/base/templates/artifacts/Command.groovy— import →org.apache.grails.core.cli.GrailsApplicationCommand-cliartifact — uniqueorg.apache.grails.*.clipackage + explicitAutomatic-Module-Namegrails-gradle/model/.../FactoriesLoaderSupport.groovy— location-parameterized lookupgrails-core/.../GrailsFactoriesLoader.groovy— location-aware overloadgrails-gradle/plugins/.../GrailsGradlePlugin.groovy—grailsCliconfig; reroute command tasks offconsole(lines 753, 1243, 1274); readgrails-cli.factories; auto-provision-clicompanionsbuild.gradleof each command-bearing module — apply thecli-artifactconvention plugin +cli*depsgrails-test-examples/**—implementation+grailsCliwiringgrails-doc/src/en/guide/introduction/whatsNew.adocgrails-doc/src/en/guide/upgrading/upgrading80x.adocgrails-doc/src/en/guide/plugins/creatingAndInstallingPlugins.adocRejected alternatives
cliclassifier via feature variants (previous draft of this proposal). Publishes the commandsas a
…-cli.jarclassifier of the module's own coordinate, relying on Gradle Module Metadata tokeep the dependency graphs apart. Rejected because the separation is Gradle-only: the shared
POM lists the cli dependencies as
<optional>on the main artifact, Maven consumers of the cliclassifier get no dependency graph at all, and every consumer (including
buildscript { classpath }placement and third-party docs) must use classifier/capability syntax. Separate coordinates make
the cli tier a first-class citizen for Maven, the BOM, and dependency tooling.
grails-<module>-cliGradle subprojects (+ agrails-cli-coremodule). Achieves the samepublished coordinates, but proliferates
settings.gradleentries and project scaffolding, andmoves command sources away from the module they belong to. The chosen design gets identical
coordinates from a
clisource set inside the existing project.artifact(classifier: 'cli')on the main publication. Separates the jar but notits dependencies —
grails-shell-cliwould still leak via the shared POM.consoleconfiguration.consoleis for the interactive console/shell tools;overloading it conflates two concerns and it is not compile-visible for command authoring.
developmentOnly. Not on the compile classpath (breaks command authoring against the cli-onlycontract) and it is on the
bootRunclasspath (re-addsgrails-shell-cli+ mismatched Groovyto the running dev app — the original bug). Fails on both counts.
Risks & open questions
the concrete change list is in §1a (verified against the
grails-gradle-publish8.x source —signing and Nexus staging are already publication-agnostic; publication creation, POM metadata,
version-mapping,
setDependencyVersions, and per-coordinate sources/javadoc jars are not). Thisadds a cross-repo release-ordering dependency: grails-gradle-publish ships first, grails-core
bumps
grails-publish-plugin.versionindependencies.gradle, then thecli-artifactconvention plugin builds on it. The in-repo
PublishPlugintasks (savePublishedArtifacts,publishedChecksums) already iterate all publications and need no structural change.Implemented and validated in grails-publish: a project publishing multiple coordinates must form a
single component tree — grails-publish now wraps the primary component in a
GrailsRootSoftwareComponent(ComponentWithVariants) with each additional publication'scomponent as a child (the Kotlin-Multiplatform model; without it Gradle fails with "Publishing is
not able to resolve a dependency on a project with multiple publications that have different
coordinates"). Consequences: the primary GMM lists the cli variants as capability-gated
available-atredirects (inert for normal consumers), and self/project dependencies resolve to theprimary coordinate. Still open for grails-core: a consumer POM (e.g.
grails-data-hibernate7-dbmigration-clidepending ongrails-core-cliviarequireCapability) records component-level coordinates (grails-core) — correct for Gradleconsumers via the
available-atredirect, but wrong for Maven consumers. Thecli-artifactconvention plugin must enable Gradle's incubating dependency mapping
(
ConfigurationVariantDetails.dependencyMapping { publishResolvedCoordinates = true }) on the clivariants so consumer POMs record the
-clicoordinates; validate the generated.pomfiles inPhase 1 step 7.
validateDependencyVersions. The-clicoordinates are not auto-picked-upby
grails-bom's subproject scan; the tagged-project enumeration (§1a) must cover them, andvalidateDependencyVersionsmust see the BOM managing them.grailsCliand the command-task reroute are additions toGrailsGradlePlugin. Larger blast radius than a pure library change; needs its own tests.(Validated:
grailsClias a bucket +compileClasspath.extendsFrom+ a resolvable view givescompile visibility without
runtimeClasspath/bootRun/bootJar— see §5.)grails-app/commandssource-set relocation (validated).configureGrailsSourceDirs(line 781)auto-adds every
grails-app/<subdir>to main. This convention is unchanged for apps (theircommands stay in
main). For framework plugins only, relocate command sources to theclisource set (
src/cli/groovy) — sincegrails-app/commandsthen no longer exists,mainwon't pickit up; alternatively add
'commands'to the mutableexcludedGrailsAppSourceDirs. Ensure theclisource set has
grails-coreon itscompileClasspathso the global AST transform runs and emitsgrails-cli.factoriesinto theclijar.mitigation is documentation, not a shim.
runtimeClasspath + grailsCli) mustinclude
grails-core-cli; confirm the plugin wiresgrailsCliinto every command-runner task.CommandFactoriesTransformationingrails-core-cliadds a globaltransform alongside
grails-core's. Precedent exists (grails-datamapping-coreships two), and thetwo write different files so there is no contention; still, give it an explicit
TransformWithPriorityorder and verify it activates on both frameworkclisource sets and appgrails-app/commandscompilation (both havegrails-core-clion the compile classpath).Naming / conventions (decided)
<artifactId>-cli— the companion Maven coordinate (org.apache.grailsgroup, same version)containing that module's commands (and command-only helpers), published as a second publication of
the same Gradle project from its
clisource set.grails-core-cliadditionally holds the sharedcommand contract/registry.
grailsCli— the app/plugin Gradle configuration that carries-cliartifacts: compile-visibleand on the command-runner classpath, but not on
runtimeClasspath/bootRun. BothgrailsCli(project dependencies) and
buildscript { classpath }placement register command tasks.org.apache.grails.<area>.cli— the package for each-cliartifact; unique per artifact(JPMS: no split packages), replacing legacy
grails.dev.commands.*. Each-clijar sets amatching
Automatic-Module-Name.org.apache.grails.cliis reserved (grails-forge/grails-cli).META-INF/grails-cli.factories— command registrations, separate fromgrails.factories.References
components (
SpringApplicationWebApplicationInitializer) transitively on the runtime classpath viadbmigration →
grails-shell.grails-data-hibernate{5,7}/dbmigration/build.gradle— the existinggrails-shell-cliGroovyexclusion + TODO calling for this split.
Add positive-path coverage and tidy manifest test data (#15377)
Merge pull request #16041 from apache/fix/7.0.x-dbmigration-bootwar-n…
Fix bootWar NPE from stray CLI WebApplicationInitializer (apache#15377)