Repository navigation
9.0: Move to JLine 4 and fix the command line parser - #17018
Conversation
The interactive Forge CLI took its Tab completion from picocli-shell-jline3, which is built for JLine 3. CommandLineCompleter makes the same picocli AutoComplete call against the JLine API directly, so the prompt completes as before and no longer depends on a bridge tied to one JLine major.
jline.version tracks the JLine that groovysh is built on, but stayed at 3.30.16 when 9.0.x moved to Groovy 6, whose groovysh uses JLine 4.4.5. grails-console leaves groovysh's own JLine modules off the class path in favour of the org.jline:jline bundle, so grails shell ran groovysh 6 on JLine 3 and failed to start with ClassNotFoundException: org.jline.shell.CommandGroup, a class only JLine 4 has. The BOM now manages JLine 4.4.5. The SBOM license table drops its JLine 3 entries, which the JLine 4 correction in forcedLicenseFor replaces, and the upgrade guide describes the move.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## 9.0.x #17018 +/- ##
================================================
+ Coverage 0 65.4925% +65.4925%
- Complexity 0 32669 +32669
================================================
Files 0 2439 +2439
Lines 0 120968 +120968
Branches 0 22402 +22402
================================================
+ Hits 0 79225 +79225
- Misses 0 31735 +31735
- Partials 0 10008 +10008
🚀 New features to boost your workflow:
|
@CommandArgument and @commandoption describe the positional arguments and the options of an ApplicationCommand, so a command line tool can show them in the command's help, check them and complete them. They only describe the command, which still reads its command line as before. ApplicationCommandManifestWriter writes every command the registry finds on the classpath, with its description, arguments and options, to a JSON file that tools read without loading the commands themselves. The writer reads the annotations with getAnnotation rather than getAnnotationsByType: the static compiler links getAnnotationsByType with an Object[] return type the JDK method does not have, so the call fails with NoSuchMethodError.
The task writes the commands runCommand can run to build/grails/commands.json, running the grails-core-cli writer on runCommand's classpath without starting the application. It stays up to date while that classpath is unchanged.
Inside a Grails project, the Forge CLI offers the commands of the application and of its plugins next to its own, with their help and their completion at the prompt, and runs them through the project's runCommand task. It reads them from the manifest generateCommandManifest writes, and runs that task first when the manifest is missing or older than the build files or grails-app/commands. The Forge CLI's own commands never wait for the build, and keep their names over a project command of the same name. Declared arguments and options are checked and completed; a command that declares none takes any and passes them on.
s2-quickstart declares its four optional class name arguments and its groupClassName, uiOnly and salt options, and the s2-create-* commands the domain class name they need, so the Forge CLI checks and completes them. The s2-create-* commands also get a description of their own instead of their name.
The Forge CLI section explains which commands of a project it offers, how it learns them from generateCommandManifest and when it runs that task. Creating Custom Commands shows @CommandArgument and @commandoption, and What's New introduces the feature.
…asked for The Gradle wrapper was looked for in every directory above the project, so a gradlew in a shared parent directory, outside the project's build, would have been run, and without a wrapper gradle on the path was. Only the project's own wrapper or the one at the root of its build, the first directory above it with a settings file, runs now; a build without one offers no project commands. --help and the other options no longer run the build either. They list the project's commands from the manifest the build last wrote, and the build runs only for the interactive prompt or when a command the Forge CLI does not have is named.
matrei
left a comment
There was a problem hiding this comment.
Review of #17018 at 39cdba9685c (base 9.0.x). It is 2 commits on the current 9.0.x tip, 0fefbee4225.
What I ran, on Java 21:
- Unit suites, rerun without the build cache:
grails-console(37, with the newGroovyshApplicationContextSpec),grails-shell-cli(236),grails-bootstraptest(353) andtestCli(66),grails-forge-cli(53, with the newCommandLineCompleterSpec), andSbomPluginSpecinbuild-logic(13). No failures. - The SBOMs:
cyclonedxDirectBomandcyclonedxCliBompass in every project of the core build. The SBOMs that name JLine list onlyorg.jline:jline4.4.5, so no JLine 3 jar is left for the dropped license entries to cover. - The new console test on JLine 3: with
jline.versionback at 3.30.16,GroovyshApplicationContextSpecfails withTypeNotPresentException: Type org.jline.shell.CommandGroup not present, which is the reported bug. So the test catches it. - The dependency:
groovy-groovysh6.0.0 declares its JLine modules at 4.4.5, and theorg.jline:jline4.4.5 bundle hasorg.jline.shell, so the bundlegrails-consoleputs in their place covers them. - The completer:
CommandLineCompletermakes the sameAutoComplete.completecall asPicocliJLineCompleterfrompicocli-shell-jline34.7.7 (compared against its bytecode), with the same arguments, so the Forge prompt completes as before. - picocli's bridge on JLine 4: a small program with
picocli-shell-jline34.7.7 andjline4.4.5 on the class path. The results are in 2. - The JLine 3 to 4 API: I compared the public classes and a few key types of the
jline3.30.16 and 4.4.5 bundles. The results are in 1. - CI on this head: everything passes except the three Groovy Snapshot Canary shards. They fail with compile errors on the Groovy snapshot in
grails-core,grails-datamapping-coreandgrails-async-rxjava3, and the canary fails the same way on the9.0.xpush of0fefbee4225.
@codeconsole, thanks. The fix looks right to me: jline.version follows Groovy again, and the bundle has everything groovysh 6 needs. My comments are on the upgrade guide, plus a few small ones.
1. The guide says recompiling is enough, but JLine 4 removed APIs
upgrading90x.adoc:1459 says the line reader, terminal and completer APIs "keep their org.jline packages", and the first required action (:1463) is to recompile code that uses JLine. That reads as if a recompile is all it takes. JLine 4 removed APIs that JLine 3 had deprecated, and code that uses them doesn't compile against 4.4.5. For example:
org.jline.reader.impl.completer.FileNameCompleteris gone.org.jline.builtins.Completers.FileNameCompleterreplaces it. Grails' ownEscapingFileNameCompletoralready extends that one, and JLine 3 has it too.Terminal.stdinEncoding(),stdoutEncoding()andstderrEncoding()are gone. JLine 4 hasinputEncoding()andoutputEncoding().TerminalBuilder.codepage(int)and thePROP_JNAandPROP_JANSIconstants are gone.
The guide's own example is a completer for a command, so I'd at least name FileNameCompleter, e.g.:
- Recompile code of your own that uses JLine, such as an
org.jline.reader.Completerfor a command, against JLine 4. JLine 4 removed APIs that JLine 3 had deprecated. For example, useorg.jline.builtins.Completers.FileNameCompleterin place oforg.jline.reader.impl.completer.FileNameCompleter.
I'd also drop the end of :1459, "and the JLine code in Grails itself compiled against JLine 4 unchanged". It's about this PR rather than the reader's code, and next to the removed APIs it can be read as a promise about theirs.
And I'd leave the patch version out of :1459. jline.version follows groovy.version, and on 8.x it went from 3.30.6 to 3.30.9 to 3.30.16 as Groovy moved. So the next Groovy 6.0.x release that ships a newer JLine makes "4.4.5" wrong. None of the required actions depends on the patch version, and the picocli bullet already says "the JLine version the Grails BOM manages". The BOM table can give the exact version, as whatsNew/dependencyUpgrades.adoc does:
Grails 9 manages JLine 4 (
org.jline:jline), the line Groovy 6'sgroovyshis built on, in place of JLine 3. The link:{versionsRef}Grails%20BOM.html[Grails BOM dependency table] has the exact version.
2. picocli-shell-jline3 still works on JLine 4
:1465 lists moving to org.jline:jline-picocli as a required action, because picocli-shell-jline3 is "built for JLine 3". I ran picocli-shell-jline3 4.7.7 on jline 4.4.5 with a small two-command CommandLine:
PicocliJLineCompletercompletes an empty line andcreate-ato the command, andcreate-app --feto its option.PicocliCommandslists and describes the commands, builds itsSystemCompleterand invokes a command.- Every JLine method and field the jar references exists in 4.4.5 with the same signature, and the
CompleterandCommandRegistryinterfaces it implements are unchanged.
The only catch is that JLine 4 deprecates org.jline.console.CommandRegistry, which PicocliCommands implements. So an app on that bridge keeps working after the upgrade, and the bullet isn't a required action. I'd move it out of the list and say so, e.g.:
picocli's
info.picocli:picocli-shell-jline3runs on JLine 4, but picocli has no JLine 4 version of it, and itsPicocliCommandsimplementsorg.jline.console.CommandRegistry, which JLine 4 deprecates. JLine's own picocli bridge,org.jline:jline-picocli, is built for JLine 4. To move to it, use it at the JLine version the Grails BOM manages.
Dropping the bridge from Forge is fine with me either way. The build.gradle comment says why, and it doesn't claim the bridge fails.
3. Small things
-
CommandLineCompleterSpec.groovy:66typescreate-app --pro, but nocreate-appoption starts with--pro. The test passes because it checks the candidates before JLine narrows them to the typed prefix, so at the promptcreate-app --proand Tab would offer nothing.create-app --fewould show the case the feature name describes. The assertions can stay as they are, since the candidates aren't narrowed by the prefix. -
GroovyshApplicationContextSpecsaves and restoresuser.homeby hand insetup()andcleanup().@RestoreSystemPropertieson the class does the same, as in the other specs that change system properties. It also takes Spock's lock on system properties, so the spec stays safe if Spock's parallel execution is turned on. TheoriginalUserHomefield andcleanup()can then go:@RestoreSystemProperties class GroovyshApplicationContextSpec extends Specification { @TempDir Path userHome void setup() { // groovysh keeps its history and settings under the user's home directory System.setProperty('user.home', userHome.toString()) }
-
.agents/skills/mono-repo-integration/SKILL.md:143saysLICENSE_MAPPINGinSbomPluginis "the same placejline/sitemeshare mapped". After this PR, JLine is handled inforcedLicenseForinstead, sojline/should come out of that sentence. -
InteractiveShell.groovy:68callscommandLine.getCommandSpec(). The new line could use the property,commandLine.commandSpec, asCommandLineCompleterSpecalready does.
From my side this is ready once 1 and 2 are in the guide.
…tional to move off
…ith @RestoreSystemProperties
|
@matrei, thanks for the thorough review. Everything is in, in e0b9887 (guide) and b60b0b7 (code and tests): 1. Removed APIs. The required action now says JLine 4 removed APIs that JLine 3 had deprecated, and names them: 2. 3. Small things.
One heads-up: since your review, this PR also carries the Forge CLI plugin-commands feature (six commits, 301e488..b9c7f03), described in the new Plugin commands in the Forge CLI section of the description. It touches grails-core ( |
jdaugherty
left a comment
There was a problem hiding this comment.
Review of the plugin-commands feature at b60b0b7da3e (the JLine 4 part was covered in the earlier review, and its asks are in).
What I ran, on Java 21:
generateCommandManifestongrails-test-examples/spring-security/core/functional-test-app: it writes six commands (config-report, the threes2-*commands with their arguments and options,schema-export,url-mappings-report), isUP-TO-DATEon the second run, and works with the configuration cache.- A throwaway spec next to
ProjectCommandsSpec, with the same stand-in wrapper, for the cases in the inline comments.
The design reads well: the manifest keeps the project's classpath out of the CLI, and only the build's own wrapper is run. The inline comments are about what happens when the project's build or the manifest is not in the expected state, and about the arguments a command is run with.
| ? option.longestName() | ||
| : "${option.longestName()}=${option.stringValues().first()}".toString()) | ||
| } | ||
| given.addAll(parsed.unmatched()) |
There was a problem hiding this comment.
A command that declares nothing does not get its command line unchanged: the options are moved behind the arguments, and that changes what the command reads. Grails' CommandLineParser gives an option without = the next word as its value, so
grails> url-mappings-report --format json first
runs -Pargs=url-mappings-report json first --format. The command then sees the arguments json and first and format as true, where ./gradlew runCommand -Pargs="url-mappings-report --format json first" gives it format=json and the argument first.
For a command that declares no arguments and no options, please pass the words on in the order they were typed (for example from parsed.originalArgs()), so that it runs as it does through runCommand, as the guide says. Moving the options last is right for the declared ones, where picocli knows which word is a value.
There was a problem hiding this comment.
Fixed in 64f6e79. A command that declares no options now gets the words after its name in the order they were typed (from parseResult.originalArgs()), with only the Forge CLI's own -D words taken out. So url-mappings-report --format json first reaches the command as --format json first, the same as runCommand -Pargs="url-mappings-report --format json first". That holds whether or not the command declares arguments. Declared options still go last as --name=value, since picocli knows their values. ProjectCommandsSpec covers both cases ("a command that describes no options is given the words in the order they were typed").
| } | ||
| if (outdated(manifest)) { | ||
| console.out('Reading the commands of the project from its build...') | ||
| int exitCode = gradle.runSilently([MANIFEST_TASK]) |
There was a problem hiding this comment.
Three cases here leave the Forge CLI worse off than without the feature:
- The wrapper cannot be started.
runSilentlythrows anIOException, for example whengradlewhas lost its executable bit, and nothing catches it.createCommandLinethen fails, so the interactive prompt does not start in that project, and neither do the Forge CLI's own commands there. - The build fails while a manifest exists. With an outdated manifest and a build that fails, which is common while an application does not compile, the commands of the manifest are dropped and
url-mappings-reportis answered withUnmatched argument. The build is also run again for every command line and every start of the prompt, each time with the same warning.--helpalready reads an outdated manifest as it is; a failed build could fall back to it too. - A project of an earlier Grails version. Its build has no
generateCommandManifesttask, so every start of the prompt in a Grails 7 or 8 project runs Gradle, fails, and prints "Run its generateCommandManifest Gradle task to see why", which names a task that project does not have.
Could load catch the IOException and warn, keep the commands of an existing manifest when the build fails, and not run the build again until a build file changes (for example by remembering the failed attempt next to the manifest)?
There was a problem hiding this comment.
All three are fixed in 64f6e79:
- Wrapper cannot start:
loadcatches theIOException, andProjectGradlealso turnsProcessBuilder'sIllegalArgumentExceptioninto one. The Forge CLI warns and starts with its own commands, plus those of an existing manifest. - Build fails while a manifest exists: the manifest's commands are kept, and the warning says so. The failed attempt is recorded in
build/grails/commands.failed, next to the manifest. The build doesn't run again until a build input is newer than that record, and a later success deletes it. - Project of an earlier Grails: the same record stops the repeated builds, so the warning shows once. It now reads "...its build failed with exit code 1. Its commands are not offered, and the build is not run for them again until a build file changes. A project of Grails 9 or later lists them with its generateCommandManifest Gradle task; run it to see what went wrong."
I found one more case while testing these. A build file can change without changing the classpath. Then generateCommandManifest is UP-TO-DATE and doesn't rewrite the manifest, so the manifest stayed outdated and the build ran on every command line. After a successful run the Forge CLI now touches the manifest itself.
New specs cover each case: an unexecutable wrapper, a failed build that keeps the manifest, a failed build with no manifest that isn't retried until build.gradle changes, and an up-to-date task.
| private List<ProjectCommand> read(File manifest, ConsoleOutput console) { | ||
| Map<String, Object> parsed | ||
| try { | ||
| parsed = (Map<String, Object>) new JsonSlurper().parse(manifest, 'UTF-8') |
There was a problem hiding this comment.
FORMAT_VERSION is written but never read: a manifest with "version": 2 is read as if it were version 1, so raising the version protects no reader. Please check it here and treat a newer version as unreadable, with a warning.
Only JsonException and ClassCastException are caught, so a manifest of another shape still stops the CLI: "commands": "oops" ends in a MissingMethodException, and a command without a name in a picocli.CommandLine$InitializationException: Cannot add subcommand with null name. Both come out of createCommandLine. A manifest that cannot be read should cost the project's commands, not the Forge CLI.
There was a problem hiding this comment.
Fixed in 64f6e79. read now checks version. A manifest of a newer format is reported as "it was written in format 2, by a newer Grails, and this Grails Forge CLI reads up to format 1", and its commands aren't offered. It also checks the shape:
- the manifest must be a JSON object with an integer
version; commandsmust be a list;- every command must be an object with a non-empty string
name.
Anything else, including an exception picocli throws while building a command's spec, is caught. The warning names the manifest and the reason. It costs only the project's commands, and the Forge CLI's own commands still run. A data-driven feature in ProjectCommandsSpec covers each shape you listed, plus a manifest without a version and one that is an array.
| // its own commands never wait for the build, and its options, such as --help, list the project's | ||
| // commands from a manifest the build already wrote | ||
| if (args.length > 0 && !commandLine.subcommands.containsKey(args[0])) { | ||
| addProjectCommands(commandLine, !args[0].startsWith('-')) |
There was a problem hiding this comment.
Two things about the first word deciding:
- A Forge CLI option before a project command never runs the build. In a project without a manifest,
grails-forge-cli -x url-mappings-reportanswersUnmatched argument at index 1: 'url-mappings-report', while the same command without-xworks. Looking for the first word that is not an option would cover it. - A project command always runs in the development environment.
runCommandtakes the environment from-Dgrails.envof the Gradle JVM, andProjectGradlehas no way to pass it; on a command that declares its options,s2-quickstart ... -Dgrails.env=testis rejected as an unknown option. For thedbm-*commands the guide names, the environment matters. If that is out of scope here, please add it to the limitations in the guide.
There was a problem hiding this comment.
Both are fixed in 64f6e79.
- An option before the command:
executenow finds the command as the first word that is neither a root option nor the value of one, and stops at--. Sograils-forge-cli -x url-mappings-reportruns the build without a manifest, as the bare form does. A command line of root options alone still only reads an existing manifest. - Environment: every project command now takes
-D<property>=<value>(also-D property=value). It is passed to the wrapper as a Gradle system property, andrunCommandforwardsgrails.envfrom there. Sodbm-update -Dgrails.env=testruns in the test environment. It's listed in each command's--helpand documented in the guide with that example. A command that declares its options accepts it, and for one that declares none it's taken out of the words passed on.
| if (wrapper == null) { | ||
| throw new IOException("The build of ${projectDir} has no Gradle wrapper") | ||
| } | ||
| List<String> command = [wrapper.path, '-p', projectDir.path, '-q', '--console=plain'] |
There was a problem hiding this comment.
Has this been run on Windows? ProjectCommandsSpec is skipped there, so the gradlew.bat branch has no test. As far as I know, ProcessBuilder refuses an argument with a quote inside it for a .bat file ("Argument has embedded quote, use the explicit CMD.EXE call"), and join produces exactly that for every argument with a space: -Pargs=url-mappings-report "two words". It throws an IllegalArgumentException, which nothing here catches.
Related, in join: an argument with both kinds of quote, such as it's "x" y, is wrapped in double quotes without escaping, and translateCommandline then reads it as it's x y.
There was a problem hiding this comment.
It had not been run on Windows, and you're right about ProcessBuilder and batch files. I've removed the quoting rather than patching it.
runCommand (and the per-command tasks) gained an argsFile project property in e71bc8f. It names a JSON file holding an array of strings, each passed on unchanged after those of args. The Forge CLI writes the command's arguments to a temp file, runs runCommand -PargsFile=<path> and deletes the file afterwards (64f6e79). join is gone. No user text goes on the wrapper's command line any more, so there's nothing for cmd.exe to read, no embedded quotes and no % expansion.
That also covers it's "x" y. ProjectCommandsSpec passes two words, say "hi", it's "x" y, an empty string and %PATH% & | <> through, and checks the file runCommand got. CommandArgumentsSpec checks how the plugin reads the file, including a missing file, invalid JSON, and an array of other than strings.
What remains on the command line is the temp-file path and any -D values. For those, a ProcessBuilder rejection now becomes an IOException with the message, instead of an uncaught IllegalArgumentException. I still haven't run the gradlew.bat path on Windows, and the PR description says so.
| .arity(flag ? '0' : '1') | ||
| .type(flag ? boolean : String) | ||
| .paramLabel((option.name as String).toUpperCase(Locale.ENGLISH)) | ||
| .completionCandidates(candidates(option)) |
There was a problem hiding this comment.
The guide gives --name=value as the form of an option, but the values are only completed in the other form: opts-only --format offers json and yaml, while opts-only --format= and --format=j offer the option names again. If picocli cannot complete the = form, the guide's example should show the form that completes.
There was a problem hiding this comment.
Fixed in 64f6e79: the = form completes now. When the word being completed is --name=..., CommandLineCompleter asks picocli to complete --name with the value as a word of its own, then puts --name= in front of each candidate. So --format= offers --format=json and --format=yaml, and JLine narrows --format=j to --format=json. Both forms are in the completion spec. The guide gives both forms and shows each completing (94123f6).
| commands.collect { Map<String, Object> command -> new ProjectCommand(command, gradle) } | ||
| } | ||
|
|
||
| private boolean outdated(File manifest) { |
There was a problem hiding this comment.
Small gaps in what makes the manifest outdated, which the guide could list as limits if they stay:
- A command deleted from
grails-app/commandsis still offered, because only files newer than the manifest are looked for. - A project that changes its build directory never has a manifest at
build/grails/commands.json, so the build runs and the warning shows on every command line. - A build script applied from another file,
buildSrc, or a new snapshot of a plugin changes the commands without touching any of the files checked.
There was a problem hiding this comment.
Fixed in 64f6e79:
- A deleted command: a directory counts as changed when its own mtime is newer, and deleting, adding or renaming a file updates the directory's mtime. So deleting a command from
grails-app/commands, at any depth, makes the manifest outdated. - A changed build directory: the Forge CLI passes
-PgrailsCommandManifest=build/grails/commands.json. The task's output now defaults to that property, falling back to the build directory (e71bc8f). So the manifest lands where the Forge CLI looks, whateverbuildDiris. - Applied scripts and
buildSrc: the inputs are now every.gradle,.gradle.kts,.propertiesand.tomlfile in the project and build root directories, and everything under theirgradle/andbuildSrc/directories.buildand.gradleoutput directories inside those are skipped. - A new snapshot of a plugin: the Forge CLI can't see that one. The guide lists it, with
./gradlew generateCommandManifestas the refresh.
…ifest write where it is told
…t as expected, and pass commands their arguments as typed
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A declared option value that contains an equals sign is cut at the first one.
| } | ||
| given << (option.arity().max() == 0 | ||
| ? option.longestName() | ||
| : "${option.longestName()}=${option.stringValues().first()}".toString()) |
There was a problem hiding this comment.
--filter 'a=b' should pass a=b. This writes --filter=a=b, and the next parser keeps only a. Pass the value without splitting it on every equals sign.
There was a problem hiding this comment.
Fixed in c5c4ff6. The value was cut by Grails' CommandLineParser, not by the Forge CLI. Passing --filter=a=b is still the right form: it keeps a value that starts with - attached to its option. The parser split the word on every = and kept only the second piece. So ./gradlew runCommand -Pargs="report --filter=a=b" lost =b too. And --filter=, with an empty value, threw ArrayIndexOutOfBoundsException.
The parser now takes everything after the first = as the value. That applies to declared and undeclared options alike. CommandLineParserSpec covers these cases:
a=bx=y=z=b- an empty value
url=/a?b=c- a quoted value through
parseString
On the Forge side, 2f3a016 checks that --groupClassName 'a=b=c' and --groupClassName=a=b=c both reach runCommand as --groupClassName=a=b=c.
jdaugherty
left a comment
There was a problem hiding this comment.
Follow-up review at 94123f6965f, including the fixes responding to the earlier review.
On Java 21/macOS, all 69 cases across the seven targeted specs passed: ProjectCommandsSpec, CommandLineCompleterSpec, ApplicationCommandManifestTaskSpec, CommandArgumentsSpec, ApplicationCommandManifestWriterSpec, SecurityCommandManifestSpec, and GroovyshApplicationContextSpec.
Two additional reproducer tests exposed the remaining cases in the inline comments: a declared option value containing = changes when the Grails command parser reads it, and removing the entire commands directory does not refresh the manifest. The temporary test edits were removed after verification. The Windows wrapper path was not exercised.
The earlier fixes look substantially covered. I would address these two remaining cases before approving.
| given << (option.arity().max() == 0 | ||
| ? option.longestName() | ||
| : "${option.longestName()}=${option.stringValues().first()}".toString()) |
There was a problem hiding this comment.
[P2] Preserve equals signs in declared option values
Rewriting every declared option as --name=value changes values containing =. For a command declaring a query option, query-report --query 'status=active' becomes ['query-report', '--query=status=active']. The JSON transport preserves that string, but CommandLineParser.processOption() splits on every = and takes only the second element, so the command sees query=status rather than query=status=active. The original two-token form correctly yields status=active.
I reproduced this through ForgeCli.execute, captured the arguments handed to the wrapper, and parsed them with the same public CommandLineParser used by runCommand; the expected status=active was actually status. This means adding @CommandOption can break an otherwise working command. Please preserve the value end-to-end, either in forwarding or in the downstream parser, and add coverage that checks what the command parser receives rather than stopping at the JSON file.
There was a problem hiding this comment.
Fixed downstream, in the parser, in c5c4ff6. The forwarding stays --name=value because that form keeps a value that starts with - attached to its option. CommandLineParser now takes everything after the first = as the value, for declared and undeclared options alike. That also fixes ./gradlew runCommand -Pargs="query-report --query=status=active", which lost =active the same way without the Forge CLI. It also fixes --query=, with an empty value, which threw ArrayIndexOutOfBoundsException. CommandLineParserSpec covers a=b, x=y=z, =b, an empty value, url=/a?b=c and a quoted value through parseString.
On the Forge side, the spec now goes past the JSON file (2f3a016, 2b8156e). It sends --groupClassName 'a=b=c' and --groupClassName=a=b=c through ForgeCli.execute. Then it parses the arguments written for runCommand with new CommandLineParser().parse(...), the call runCommand makes. It checks that optionValue('groupClassName') == 'a=b=c' and that the arguments are ['com.example', 'User', 'Role']. (James raised the same point, answered in his thread.)
| private static boolean changed(File dir, long since) { | ||
| if (!dir.isDirectory()) { | ||
| return false | ||
| } |
There was a problem hiding this comment.
[P2] Invalidate the manifest when the commands directory disappears
Returning false for a missing directory misses removal of grails-app/commands itself, as can happen when checking out a branch without the application's last custom command. With the build inputs otherwise unchanged, outdated() then considers the existing manifest fresh and keeps offering the removed commands indefinitely, until another watched input changes or the manifest is refreshed manually.
The existing deletion test leaves the directory present, so its updated mtime catches that case. I added a reproducer that removed the entire commands directory after writing the manifest: ForgeCli.createCommandLine made zero Gradle invocations instead of refreshing it. Could this track directory disappearance, or check a surviving parent's timestamp, so removing the final command is detected too?
There was a problem hiding this comment.
Fixed in 2b8156e. When grails-app/commands is gone, the check compares grails-app itself. Removing the commands directory updates grails-app's modification time, and every project has grails-app, since the Forge CLI needs it to treat the directory as a project. Your case now runs the build.
ProjectCommandsSpec covers both sides:
- "the manifest is written again when the commands directory is removed with the last command": deletes the whole directory, with only
grails-appchanged, and expects the build to run. - "a project without a commands directory does not run the build while nothing changed": an application that never had the directory doesn't rebuild on every start.
The guide's list of build inputs now names the removed directory.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A command added in a sibling plugin's main sources still leaves the old command list.
| } + includedBuildDirs) | ||
| .collect { File dir -> dir.absolutePath }.unique().sort() | ||
| // a command compiled from the cli source set registers itself, so a new one adds a command | ||
| List<String> commandDirectories = root.allprojects.collectMany { Project each -> |
There was a problem hiding this comment.
A sibling plugin adds AuditCommand under src/main/groovy. The command list is already cached. grails-forge-cli audit says the command is unknown. This watch covers only the cli source set, and the list records source files only for commands it already knows. Watch a new command in main sources too.
There was a problem hiding this comment.
Fixed in 07d5333. The manifest names the main Java and Groovy source directories of every project under inputs.commandFileDirectories, and the Forge CLI records the files there named like a command (*Command.groovy, *Command.java) by name only. Adding, removing or renaming a command runs the build; editing or adding another source does not. ApplicationCommandManifestTaskSpec checks the listed directories. ProjectCommandsSpec adds AuditCommand.groovy to a plugin project's src/main/groovy and checks that the build runs once and audit runs instead of being rejected, that editing a service or adding Helper.groovy runs no build, and that removing the command does. A command whose file isn't named after it still needs ./gradlew generateCommandManifest, and the guide says so.
jdaugherty
left a comment
There was a problem hiding this comment.
Follow-up review at 1ba5e639da, including the new watches for plugin CLI sources and registration files. That addresses the preceding registration-file thread. The earlier argument-parsing and unselected-child-project fixes are covered by passing tests.
On Java 21/macOS, the latest head passes all 129 existing cases in ProjectCommandsSpec and CommandLineCompleterSpec, and all 24 cases in ApplicationCommandManifestTaskSpec and CommandArgumentsSpec. Earlier in this review, at 1de3403bb1, CommandLineParserSpec, ApplicationCommandManifestWriterSpec, SecurityCommandManifestSpec, and GroovyshApplicationContextSpec also passed. The targeted Forge run omitted the unrelated local-Maven publication dependency.
Two additional temporary reproducers through ForgeCli.createCommandLine, using the existing stand-in wrapper, still fail on the latest head; both control cases pass. The inline comments describe them. The temporary test edits were removed after verification. I would address these two cache cases before approving.
| if (problem == null) { | ||
| Inputs after = inputsOf(manifest) | ||
| save(after == before ? recorded : snapshotOrNull(after), null, console) |
There was a problem hiding this comment.
[P2] Preserve the pre-build snapshot when the input definitions change
When after != before, this discards the snapshot taken before Gradle and records the files as they are after the build. That happens during normal first-time generation, when the manifest supplies its sorted input lists, and when the build discovers additional command inputs. If a command is saved after compilation but before Gradle returns, the new contents are recorded as already compiled even though the manifest describes the old command. Subsequent lookups consider that stale manifest current.
I reproduced this by extending the existing in-flight-change test with the inputs object the manifest task writes: the second lookup makes no build invocation. The same test without inputs, as in the existing fixture, correctly rebuilds. Please retain the pre-build state of already-known inputs, or conservatively require another refresh when the input definitions change, rather than treating the post-build snapshot as evidence of what Gradle compiled.
There was a problem hiding this comment.
Fixed in 159b5a8. On a first build the manifest always names more inputs than the fallback, so the record was taken after the build. The files known before the build are now read again once it is done, and if any changed while it ran, the record from before is kept, so the next lookup runs the build again. The in-flight-change feature of ProjectCommandsSpec now runs with and without inputs; the inputs case fails without the fix. A new feature checks that a first build with inputs and no change still runs once. A file only the new manifest names has no state from before the build, so a change to it during that first build still isn't seen.
| File rootDir = gradle.rootDir | ||
| new Inputs([projectDir, rootDir].unique(), | ||
| [new File(rootDir, 'gradle'), new File(rootDir, 'buildSrc'), | ||
| new File(projectDir, 'grails-app/commands'), new File(projectDir, 'src/main/resources/META-INF')], | ||
| [new File(projectDir, 'src/cli')], []) |
There was a problem hiding this comment.
[P2] Retain the manifest's watched paths after clean
The watched-path definitions exist only in build/grails/commands.json. After a successful discovery has named another project's command sources, let a refresh fail, run clean, and start Forge while the build is still broken. With the manifest gone, this fallback replaces those definitions; the next failed attempt overwrites commands.record with only the current project's fallback inputs. Fixing the previously watched plugin command then does not retry the build, and no project commands are offered until another fallback input changes or the user manually regenerates the manifest.
A public-API reproducer that fixes plugins/audit/grails-app/commands/AuditCommand.groovy after this sequence makes zero additional build invocations. The identical case without clean retries successfully. Please persist the last discovered input definitions alongside the record outside build/, and retain them when a failed refresh has no manifest.
There was a problem hiding this comment.
Fixed in bdc635c. After a successful build the Forge CLI copies the manifest's inputs to .gradle/grails/commands.inputs, next to the record and outside build/, and watches them while there is no manifest. A manifest that names no inputs removes the copy. ProjectCommandsSpec runs your sequence: success with the plugin's AuditCommand.groovy watched, a failed refresh, build/ deleted, a start while still broken (no build), then the fix (one build, audit offered). Without the fix the start after clean runs the build, as you found.
…uring it The manifest always names more inputs than the Forge CLI watches without one, so on a first build the files were recorded as they were after the build. A command saved while the build ran then counted as compiled, and the manifest that did not list it counted as current. The files known before the build are read again once it is done. When one of them changed, the record from before the build is kept, so the next lookup runs the build again. A file only the new manifest names has no state from before the build, so a change to it during that build is still not seen.
…ves it The inputs the manifest names were only in build/grails/commands.json. After a failed refresh and ./gradlew clean, the Forge CLI fell back to the project's own inputs, and the next failed build recorded only those. Fixing a command of another project of the build then never ran the build again. After a successful build the Forge CLI copies the manifest's inputs to .gradle/grails/commands.inputs, next to the record, and watches them while there is no manifest. A manifest that names no inputs removes the copy.
A command compiled from a project's main sources registers itself, but the manifest named only the sources of the commands it already listed, so a command a plugin project of the build added to src/main/groovy left the old command list, and the Forge CLI rejected it. The manifest names the main Java and Groovy source directories of every project under inputs.commandFileDirectories. The Forge CLI records the files there named like a command, *Command.groovy or *Command.java, by name only: adding, removing or renaming a command runs the build, while editing or adding another source does not. Without a manifest naming inputs, the project's own src/main/groovy and src/main/java are watched the same way. The guide lists these, and that the inputs of the last manifest are kept for after ./gradlew clean.
sbglasius
left a comment
There was a problem hiding this comment.
This is an AI assisted review
Thanks @codeconsole. I checked my points at 07d5333ff9, and they're all in:
- The
GRAILS_FORGE_RUN_BUILD/grails.forge.runBuildopt-out is in place, documented in the guide, and covered inTHREAT_MODEL.md. - An unselected command task now drops its dependencies and classpath, so the
onlyIfissue is fixed properly rather than just skipped. requireMainClasshas its Javadoc back, the args file usesFiles.createTempFile, theCommandOptionexample is camelCase, and the groovysh spec runs on a dumb terminal with empty input.
On the split: fair enough. The completer ties the two together and the JLine part has already been reviewed, so I'm fine keeping one PR.
No further points from me. The remaining cache-case threads from @jdaugherty and @jamesfredley are theirs to resolve. The two failing jobs are the Groovy Snapshot Canary shards, which are also red on 9.0.x.
sbglasius
left a comment
There was a problem hiding this comment.
This is an AI assisted review
All my points are addressed. Approving.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A command added in main sources is seen. A first refresh that fails still leaves that command unknown after the file is fixed.
| keepInputs(manifest) | ||
| return | ||
| } | ||
| save(recorded, problem, console) |
There was a problem hiding this comment.
The cached list does not have audit. AuditCommand.groovy is added with a syntax error, so the first refresh fails. The syntax is then fixed and the command is tried again. Forge still says audit is unknown, because the failed refresh saved a snapshot of the path, and fixing the file does not change that snapshot. Do not record a refresh that failed.
There was a problem hiding this comment.
Fixed in dda082a, which moved with the feature to #17081. I kept recording failed refreshes, since without the record a broken build would run again on every command line and every start of the prompt (jdaugherty's thread 4602257628). Instead, while the last build failed, files named like a command are recorded with their time and size, so fixing one runs the build again; after a successful build they go back to being recorded by name. ProjectCommandsSpec runs your sequence: a new AuditCommand.groovy with a syntax error, a failed refresh that rejects audit, a second start that runs no build, then the fix, which runs the build once and audit runs.
jdaugherty
left a comment
There was a problem hiding this comment.
Requesting changes on scope: please reduce this PR to the JLine 4 upgrade and take the plugin commands feature out of it.
The JLine half fixes a real failure (grails shell does not start on 9.0.x with Groovy 6) and should not wait on a feature. The feature half overlaps the Forge and CLI unification for 9.0, whose design was agreed in person at Community over Code and is written up in #16348 (design), and it differs from that design in places that become public API once 9.0.0 ships. My earlier reviews here looked at how the feature is implemented; this one is about where it belongs.
Where it conflicts with the design:
- Command discovery. The design keeps the discovery the
-clicompanions already have (ApplicationContextCommandFactory, the per-command Gradle tasks), fixes its two gaps (legacy commands with no task, andgrails-app/commandsnot being listed), and describes every command in one catalog,grails help --json, that also serves completion and the IDE. This PR adds a second path next to it: agenerateCommandManifesttask and abuild/grails/commands.jsonformat of its own. - Command contract.
@CommandParameterand@CommandOptionare new public annotations inorg.apache.grails.core.cli. The design's contract also has to say where a command runs (in the console without the application context, or with it), and its catalog carries synonyms and the completer kind. Shipping these annotations first leaves us with two ways to describe a command, or a contract shaped by what was released first. - Running Gradle. The design runs Gradle through the Tooling API services the console already has (
GradleInvoker,GradleAsyncInvoker), with cancellation and a connection kept open across commands. Here each command startsgradlewas a process, and the prompt runs the project's build when it starts.GRAILS_FORGE_RUN_BUILD,argsFileandgrailsCommandProjectare new public settings that exist to support that. - Entry point. The guide now documents
grails -t forge <command>. The design removes-tin 9.0 in favour of onegrailscommand tree, so this documents a form we already plan to remove in the same release.
What I would keep in this PR:
- the
jline.versionmove to 4.4.5 independencies.gradle, and the SBOM license table change CommandLineCompleterand its spec in place ofpicocli-shell-jline3, with theInteractiveShellchange that needs it- the
GroovyshApplicationContextchange and its spec, and theEscapingFileNameCompletorSpecfix - upgrade guide section 26, JLine 4, and its part of the
grails-upgradeskill
What I would take out: generateCommandManifest and the manifest writer, the annotations, ProjectCommand, ProjectCommands, ProjectGradle, the ForgeCli changes that load project commands, the argsFile and grailsCommandProject properties, the CommandLineParser changes, the Spring Security command annotations, and the guide, What's New and upgrade guide section 27 text for them.
The work is not wasted. Passing arguments in a file, running a command in one named project, and the parser fixes are things the unified CLI needs too. Please bring the feature to #16348 so it lands as part of that design rather than ahead of it.
Files named like a command in the main sources are recorded by name only, and a failed build is recorded so it is not run again for nothing. So a new command that did not compile was recorded by name, fixing it changed nothing recorded, and the Forge CLI kept rejecting it. While the last build failed, those files are recorded with their times and sizes, so fixing one runs the build again; nothing else changing still runs no build. After a successful build they go back to being recorded by name, so editing a command or another source does not run it.
The plugin commands go to a pull request of their own, to be weighed against the unified command line of apache#16348. This change keeps the move to JLine 4, the Forge prompt's completer, the grails shell spec, and the fixes to the command line parser runCommand already uses, with upgrade guide sections 26 and 27 and their part of the grails-upgrade skill. Removed: generateCommandManifest and its writer, the @CommandParameter and @commandoption annotations, the Forge CLI's project commands, the argsFile and grailsCommandProject properties, the Spring Security command descriptions, and the guide and threat model text for them. The prompt and its completer are back to what the JLine change needs.
|
@jdaugherty, done in 7d5e11e, a new commit on top, so nothing was force-pushed. #17018 now holds the move to JLine 4, the SBOM table, I kept the command line parser fixes, with section 27 and its skill entry. They fix The plugin commands are in #17081, to be weighed separately against #16348. Its branch restores the feature on top of 7d5e11e, so merging 9.0.x into it after this lands keeps the feature. |
9.0.x added upgrade-guide sections 26 to 28, and their parts of the grails-upgrade skill, for the auto-timestamp listener changes. JLine 4 and the command lines of application commands follow them as sections 29 and 30, and both checklists are kept.
🚨 All tests passed but jobs failed 🚨Failed Jobs without Test Failures❌ Groovy Snapshot Canary Build / Build Grails (shard 0) 🏷️ Commit: 7bd0157 Rerun ControlsClick the checkbox to trigger a rerun: 🔲 Rerun jobs Learn more about TestLens at testlens.app/docs. |
jdaugherty
left a comment
There was a problem hiding this comment.
Thank you for splitting out the new features. I agree the bug fixes seem reasonable so I'm good to merge this.
Brings in apache#17018, the JLine 4 change this branch was cut from, and the open-session-in-view work. Git found two merge bases, the earlier 9.0.x merge and the commit that took the feature out of apache#17018, and merged without a conflict: the one file both sides touched, dependencies.gradle, changed on neighbouring lines (jline.version, already moved to 4.4.5 by apache#17018, and spring-boot.version).
Grails tracks the JLine version Groovy's groovysh is built on (
jline.versionindependencies.gradle), but the pin stayed at JLine 3.30.16 when 9.0.x moved to Groovy 6, whose groovysh uses JLine 4.4.5. grails-console leaves groovysh's own JLine modules off the class path in favour of theorg.jline:jlinebundle, sograils shellran groovysh 6 on JLine 3 and failed to start:org.jline.shellexists only in JLine 4. This moves the BOM to JLine 4.4.5.Forge CLI completion
The interactive Forge CLI took its Tab completion from picocli's
picocli-shell-jline3, which is built for JLine 3, and picocli has no JLine 4 module.CommandLineCompletermakes the sameAutoComplete.completecall against the JLine API directly, so the prompt completes exactly as before and the bridge dependency is gone:JLine's own bridge,
org.jline:jline-picocli, was not used: its completer is the same call wrapped in aSystemCompleter, which completes the command name itself and would change how the first word completes.Other changes
forcedLicenseForcovers theorg.jlinejars now resolved.grails-upgradeskill: recompile code of your own that uses JLine (naming APIs JLine 4 removed, such asorg.jline.reader.impl.completer.FileNameCompleter), and droporg.jline:jline-terminal-jna/jline-terminal-jansi(no JLine 4 version).picocli-shell-jline3keeps working on JLine 4; the guide namesorg.jline:jline-picoclias its JLine 4 replacement.Command line parser
Grails' command line parser, which the
grailscommand line tool andrunCommandread the command line of an application or plugin command with, keeps every=of an option value after the first (--filter=a=bgavea), reads--name=as an empty value (it threwArrayIndexOutOfBoundsException) and an argument of only"(it threwStringIndexOutOfBoundsException), and takes an empty word after an option as its empty value instead of taking the next word. It also trims the text inside a pair of quotes. Upgrade-guide section 30, Command Lines of Application Commands, and thegrails-upgradeskill list these changes.Limitations
create-app+ Tab), the Forge prompt offers the root commands rather than that command's options; typing--first completes the options. This is picocli's completion and is unchanged frompicocli-shell-jline3.