Repository navigation
8.0 (fix): Point development reloading at the build's own classes and resources directories - #16472
Conversation
In development a changed source file is compiled again into BuildSettings.BUILD_CLASSES_PATH, which is the grails.project.class.dir system property or else build/classes/groovy/main. The Gradle plugin passed only grails.project.target.dir (the build directory's name), so an application built into another directory (-PbuildDir, a second instance of one checkout) had each change compiled into build/classes, which it does not load classes from. The artefact was reloaded from the class already loaded: the bean was replaced, and the old code went on answering. Forked JVM tasks now get grails.project.class.dir: the main source set's Groovy classes directory, relative to the project directory, as GrailsApp.recompile joins it to the application directory. It is read when the task runs, so a build directory set after the plugin is applied is the one passed.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16472 +/- ##
==================================================
+ Coverage 59.2797% 59.3687% +0.0890%
- Complexity 24773 24825 +52
==================================================
Files 2170 2171 +1
Lines 108118 108185 +67
Branches 19707 19727 +20
==================================================
+ Hits 64092 64228 +136
+ Misses 35151 35031 -120
- Partials 8875 8926 +51
🚀 New features to boost your workflow:
|
matrei
left a comment
There was a problem hiding this comment.
Reviewed at head 47f7c72e82. The base is 8.0.x at d13aa33282, which is also the merge-base, so the branch is up to date and merges cleanly.
What I ran locally:
GrailsGradlePluginToolchainSpecwithcleanTest --no-build-cache: 14/14 pass, including the two new features.- The whole
:grails-gradle-plugins:testsuite withcleanTest --no-build-cache: 321 tests in 46 specs, all pass.
The diagnosis is right, and passing the main source set's own classes directory is the right fix. With the default layout the value is the same as BuildSettings' fallback, so a standard application sees no change. I have one thing I'd like changed before merge, one question about multi-project builds, and two follow-ups that don't need to block this PR.
Findings
1. On Windows the property is written with backslashes, and IOUtils compares it with URL strings
GrailsProjectClassesDirProvider.asArguments() uses Path.relativize(...).toString(), so on Windows the value is build\classes\groovy\main. Before this PR, BUILD_CLASSES_PATH was always the forward-slash constant build/classes/groovy/main. Two IOUtils methods rely on that, because they compare it with a URL string, which always uses /:
IOUtils.findRootResourcesURL(grails-gradle/model/.../IOUtils.groovy:195)IOUtils.findResourceRelativeToClass(:239)
Both check rootPath.endsWith(BuildSettings.BUILD_CLASSES_PATH) and then point the lookup at build/resources in place of build/classes/groovy. BinaryGrailsPlugin uses the first for its resources root (BinaryGrailsPlugin.java:108), and PluginUtils.getConfigurationResource uses the second to find a plugin's plugin.yml/plugin.groovy (PluginUtils.java:551). So on Windows, a plugin subproject loaded from its classes directory in development would no longer find its configuration and resources. That happens with the default build directory too, which this PR otherwise leaves unchanged.
The other consumers already convert with replace('/', File.separator) (IOUtils.groovy:274, :359) or pass the value to new File(...), and both work with / on Windows. Emitting forward slashes keeps every consumer working:
String relative = projectDir.toPath().relativize(directory.asFile.toPath()).iterator().join('/')The two new features assert File.separator, which would pin the backslash form. They should then expect build/classes/groovy/main and build-parent/build-8070/classes/groovy/main on every platform.
2. Question: plugin subprojects whose build directory isn't laid out like the application's
GrailsApp.recompile joins BUILD_CLASSES_PATH to the directory of the project that owns the changed file (GrailsApp.groovy:373), and IOUtils applies it to every class root. That includes plugin subprojects watched through BinaryGrailsPlugin.projectDirectory. The property now carries the application's own relative path, so a change in a plugin subproject compiles into <plugin>/<application's relative classes path>.
That's fine when every project uses the same relative build directory, either the default or an allprojects { layout.buildDirectory = layout.projectDirectory.dir(...) }. It breaks when only the application moves its build directory, or when the build directories are relative to the root (for example rootProject.layout.buildDirectory.dir(project.name)). Before this PR, plugin changes landed in <plugin>/build/classes/groovy/main in those setups, and that is where the plugin loads its classes from. Have you tried this with a multi-project build? If it isn't worth handling here, a sentence in the provider's Javadoc saying that the path is assumed to be the same for every project would help whoever runs into it later.
Follow-ups (not blocking)
3. The resources directory has the same problem
BuildSettings.TARGET_DIR is BASE_DIR joined to grails.project.target.dir, which the plugin still sets to the build directory's name (GrailsGradlePlugin.groovy:1043). RESOURCES_DIR is derived from it. In the scenario from the description, both resolve to build-8070/... in place of build-parent/build-8070/..., so they don't exist. I18nGrailsPlugin.onChange skips the copy when RESOURCES_DIR doesn't exist (I18nGrailsPlugin.groovy:184), so a second instance doesn't reload message bundles. When it does copy, it writes into the fixed BUILD_RESOURCES_PATH, so a bundle edit would land in the other instance's build/resources/main.
Passing grails.project.resource.dir from the main source set's output.resourcesDir, in the same way as this PR passes the classes directory, would close that gap. That can be a separate PR.
4. 7.0.x has the same code
configureForkSettings on 7.0.x passes only grails.project.target.dir too (GrailsGradlePlugin.groovy:571 there), so the bug exists on 7 as well. Did you choose to fix it only on 8? If not, targeting 7.0.x and merging up would cover both.
Nit
mainGroovyClassesDirchecks for aSourceSetContainerand amainsource set and returns null without them.GrailsGradlePluginalways applies thegroovyplugin (:151), so both are always present, and so is theGroovySourceDirectorySetextension that theflatMapreads. The check doesn't hurt, butproject.extensions.getByType(SourceSetContainer).named(SourceSet.MAIN_SOURCE_SET_NAME)alone would be simpler, and theif (classesDir != null)at the call site could go too.
Verified as correct
BuildSettingsuses the property as bothCLASSES_DIR(new File(fromSystem), resolved against the working directory, which is the project directory forbootRunandtest) andBUILD_CLASSES_PATH(joined to the application directory inGrailsApp.recompile). A path relative to the project directory is right for both. An absolute path would have broken the join, as the description says.IOUtils.findApplicationDirectoryandfindApplicationDirectoryFilenow findbuild-parent/build-8070/classes/groovy/mainin the class location and strip it to get the application directory. Before, they fell back tofindGrailsApp. Both give the same directory.findRootResourcesURLon Linux and macOS with a moved build directory:endsWithnow matches, but the hard-coded/build/classes/groovy/replacement doesn't, so the result is the same as before. That is a pre-existing limitation, not something this PR introduces.- The provider reads
classesDirectorylazily inasArguments(), so alayout.buildDirectoryassigned after the plugin is applied is picked up. The second feature exercises that. Holding aFileand aProvider<Directory>keeps it configuration-cache safe. @Internalon both properties matchesGrailsAppBaseDirProvider. The classes are already on the task's classpath, and aDirectoryinput under the build directory would add the implicit-dependency warnings that theGrailsAppBaseDirProviderJavadoc describes.Testtasks get the property too. With the default layout the value matches the fallback, so tests see no change.
sbglasius
left a comment
There was a problem hiding this comment.
Review findings (from reading the diff; not reproduced by running anything):
GrailsProjectClassesDirProvider.groovy:66—relativizecan throw.Path.relativizethrowsIllegalArgumentExceptionwhen the project dir and build dir have different roots (e.g. different Windows drives). That would failbootRunitself, where before it only lost reloading. There is no fallback.GrailsProjectClassesDirProvider.groovy:66— a build dir outside the project gives a../…value forBUILD_CLASSES_PATH.IOUtilsusesrootPath.endsWith(BuildSettings.BUILD_CLASSES_PATH)on resource paths that contain no..segments, so the match fails.MainClassFinderandI18nGrailsPluginalso build paths from it. Recompile may work, but base-dir/resource detection and i18n reload could misbehave. The Javadoc only reasons aboutGrailsApp.recompile.GrailsGradlePluginToolchainSpec.groovy:196— test coverage gap. Both new tests only check the argument string for a build dir inside the project. The outside-project and cross-root cases are not covered.
The path is now joined from its names with /, as the build/classes/groovy/main fallback is: IOUtils compares it with class locations written as URLs, which a Windows separator would never match. A classes directory with no path relative to the project, such as one on another Windows drive, passes no property and keeps the fallback instead of failing the task. The Javadoc says how a path outside the project resolves, and that plugin subprojects are assumed to lay out their build directories like the application. mainGroovyClassesDir no longer checks for a main source set the groovy plugin always adds.
|
@matrei Thanks, all four hold.
Nit: done. |
|
@sbglasius Thanks. 1 and 3 hold and are fixed; 2 holds in part.
|
jdaugherty
left a comment
There was a problem hiding this comment.
Reviewed at head 5dc78857fa. It merges cleanly with the current 8.0.x (813221ea4c).
GrailsProjectClassesDirProviderSpec (5 tests) and GrailsGradlePluginToolchainSpec (15 tests) pass locally. The points @matrei and @sbglasius raised are addressed at this head: the path is joined with /, a classes directory that has no path relative to the project passes nothing, and the Javadoc now covers ../ paths and the plugin subproject assumption.
I also checked what the forked JVM is actually given, using a throwaway JavaExec task that runs -XshowSettings:properties -version:
- Default layout:
grails.project.class.dir = build/classes/groovy/main. layout.buildDirectoryset tooutwith--configuration-cache:out/classes/groovy/main, both on the run that stores the entry and on the run that reuses it.
I've left two small comments inline. Neither blocks the merge.
One note for the resources follow-up: BuildSettings.TARGET_DIR reads project.target.dir (BuildSettings.groovy:337), not grails.project.target.dir. Nothing reads the BuildSettings.PROJECT_TARGET_DIR property the plugin passes at GrailsGradlePlugin.groovy:1040, so TARGET_DIR is always <base.dir>/build. Whoever adds grails.project.resource.dir will want to look at that as well.
| task.jvmArgumentProviders.add(new GrailsAppBaseDirProvider(project.projectDir)) | ||
| // Where development reloading compiles a changed class: the build's own classes, wherever the build | ||
| // directory is, not the build/classes/groovy/main BuildSettings falls back to | ||
| task.jvmArgumentProviders.add(new GrailsProjectClassesDirProvider(project.projectDir, mainGroovyClassesDir(project))) |
There was a problem hiding this comment.
This replaces a value the build sets itself. Gradle puts jvmArgumentProviders after systemProperties on the command line, and the last -D wins. With
tasks.named('bootRun') {
systemProperty 'grails.project.class.dir', 'user/chosen/dir'
}the forked JVM gets build/classes/groovy/main. I checked this with a JavaExec task that runs -XshowSettings:properties -version. Before this PR, setting the property on the task was how a build pointed reloading at another directory. A build that already does that now loses its value, and nothing says so. Most of those builds will have set the same directory this computes, but a build that set it on purpose should keep its value.
Could the provider pass nothing when the task already sets the property? One way is to give it task.systemProperties and check that in asArguments(). If replacing the value is intended, a sentence in the Javadoc would do. Either way, inspectBootRunClassesDir only reads jvmArgumentProviders, so it can't catch this. task.allJvmArgs would show what the JVM is actually given.
There was a problem hiding this comment.
Fixed. The provider now takes the task's systemProperties and passes nothing when the build sets the property there. They're read when the task runs, so a tasks.named('bootRun') { systemProperty ... } that comes after the plugin counts too. inspectBootRunClassesDir now reports the last -D in task.allJvmArgs, and a new feature sets grails.project.class.dir on bootRun and expects that value; it fails without the change.
| @Override | ||
| Iterable<String> asArguments() { | ||
| String relative = relativePath(projectDir.toPath(), classesDir.get().asFile.toPath()) | ||
| relative ? ["-D${BuildSettings.PROJECT_CLASSES_DIR}=${relative}".toString()] : [] |
There was a problem hiding this comment.
When relativePath returns null, the application quietly falls back to build/classes/groovy/main. That is the failure this PR describes: changes are compiled where the application doesn't load classes from, and nothing in the log says so. Could this log a warning that names the classes directory? Then someone whose build directory is on another drive would know that reloading won't pick up their changes.
There was a problem hiding this comment.
Agreed. It now logs a warning naming the property, the directory and the project directory, and saying that changes won't be reloaded.
…p a property the build sets The plugin now also passes grails.project.resource.dir, the main source set's resources directory relative to the project. BuildSettings.RESOURCES_DIR already read it; BUILD_RESOURCES_PATH now does too, so the i18n plugin copies a changed message bundle into the build the application runs from. IOUtils maps a class root to its resources root by the build's classes and resources paths rather than replacing /build/classes/groovy/ with /build/resources/, which never matched a moved build directory. GrailsProjectClassesDirProvider becomes GrailsProjectOutputDirProvider, used for both properties. It passes nothing when the task already sets the property (systemProperty 'grails.project.class.dir', ...), since argument providers come after system properties and the last -D wins, and it logs a warning when the directory has no path relative to the project, since reloading then goes where the application does not load from. inspectBootRunClassesDir reads task.allJvmArgs, which shows what the JVM is given.
|
@jdaugherty Thanks for the approval, and for checking what the forked JVM gets with the configuration cache. Both inline points are fixed; I've replied in the threads. I've also folded the resources follow-up into this PR, since it's the same gap:
I left Since this now touches |
jdaugherty
left a comment
There was a problem hiding this comment.
Reviewed again at head 3c1a893b79, which merges cleanly with the current 8.0.x (813221ea4c). GrailsProjectOutputDirProviderSpec (8 tests), GrailsGradlePluginToolchainSpec (16) and IOUtilsSpec (8) pass locally.
I also checked whether gradle/gradle#38395 applies to the new providers. In that issue, a forked compiler daemon is reused by a later compile task whose providers pass nothing, so that task sees the -D values from the task that started the daemon. That doesn't happen here, because the providers are only added to Test and JavaExec, and those start a new JVM every time they run. I checked with two projects run with --max-workers=1: in one the provider passes grails.project.class.dir, in the other it passes nothing. Each Test and JavaExec ran in its own JVM, and the second project's JVMs didn't get the first project's value. The second project's forked GroovyCompile did run in the first project's daemon and got its value, so the issue is real, but only for compiles.
| } | ||
|
|
||
| static { | ||
| BUILD_RESOURCES_PATH = System.getProperty(PROJECT_RESOURCES_DIR) ?: 'build/resources/main' |
There was a problem hiding this comment.
RESOURCES_DIR, further down this block (line 340, outside the diff), uses the property as given: new File(System.getProperty(PROJECT_RESOURCES_DIR)). Now that the plugin always passes a relative path, RESOURCES_DIR is resolved against the forked JVM's working directory. Before, it was new File(TARGET_DIR, 'resources/main'), which base.dir ties to the application. I ran BuildSettings from this branch with -Dbase.dir=<app> and the working directory set to a directory next to the application:
property not passed: RESOURCES_DIR = <app>/build/resources/main exists=true
-Dgrails.project.resource.dir=build/...: RESOURCES_DIR = <elsewhere>/build/resources/main exists=false
bootRun and test run in the project directory by default, so the tests here can't see the difference. A build that sets workingDir on bootRun does. For example, I18nGrailsPlugin.onChange checks RESOURCES_DIR.exists() before it copies a changed bundle, so in that setup it skips the copy and logs nothing.
The provider's Javadoc says the path is relative because it is joined to a project directory. Could RESOURCES_DIR join a relative value to BASE_DIR? An absolute value that a build passes itself would keep working as before:
String resourcesDir = System.getProperty(PROJECT_RESOURCES_DIR)
File resourcesFile = resourcesDir ? new File(resourcesDir) : null
RESOURCES_DIR = !GRAILS_APP_DIR_PRESENT ? null :
(resourcesFile ? (resourcesFile.absolute ? resourcesFile : new File(BASE_DIR, resourcesDir)) : new File(TARGET_DIR, 'resources/main'))A test for it needs a JVM whose working directory isn't the application's, since BuildSettings sets these values once, when the class loads.
There was a problem hiding this comment.
Right, that was a regression here. RESOURCES_DIR now joins a relative grails.project.resource.dir to BASE_DIR (BuildSettings.resourcesDir), and keeps an absolute one as it is. BuildSettingsSpec covers the three cases, and runs BuildSettings in a JVM whose working directory is next to the application, as you did: with the property it's <app>/build-parent/build-8070/resources/main, and without it <app>/build/resources/main. That forked case fails with the previous line.
I've left CLASSES_DIR as it was. It has always resolved against the working directory, its fallback included, and the whole block is gated on grails-app being in the working directory, so with workingDir moved it's already null and the property is ignored.
| // Where development reloading compiles a changed class and copies a changed message bundle, and where | ||
| // the application reads resources from: the build's own directories, wherever the build directory is, not | ||
| // the build/classes/groovy/main and build/resources/main BuildSettings falls back to | ||
| task.jvmArgumentProviders.add(new GrailsProjectOutputDirProvider(BuildSettings.PROJECT_CLASSES_DIR, |
There was a problem hiding this comment.
These providers reach Test and JavaExec, but not the Groovy compiler, and the compiler looks for the build's classes too. An @Integration spec without applicationClass gets its application class at compile time: IntegrationTestAstTransformation calls MainClassFinder.searchMainClass, which only looks in <project>/build/classes/main and <project>/build/classes/groovy/main. When it finds nothing, the spec gets no @ContextConfiguration, and its tests run without an application.
I tried this with the enable-mvc-check example, moving its build directory to build-parent/build-8070 from an init script:
- With no
build/in the project, the compiledWebMvcDefaultsFunctionalSpechas@Integrationbut no@ContextConfiguration, and all 7integrationTesttests fail withIllegalStateException: No baseUrl set. - With the default layout, the spec gets
@ContextConfiguration(classes = Application, loader = GrailsApplicationContextLoader)and all 7 pass. - With the build directory moved again but a
build/left by another build of the same checkout, all 7 pass, because the lookup findsApplicationin that other build.
So the two-instance case in the description doesn't show this, but a checkout that only ever builds outside build/ does. This PR doesn't cause it, but it's the same gap. Could it be covered here, or in a follow-up issue?
Passing grails.project.class.dir to the compiler wouldn't be enough on its own. The compiler daemon runs in ~/.gradle/workers, so BuildSettings finds no grails-app there and ignores the property: CLASSES_DIR is null and BUILD_CLASSES_PATH is build/classes/main. Gradle also reuses a forked compiler daemon for a later compile whose argument providers pass nothing, and that compile then sees the earlier task's values (gradle/gradle#38395). So a value given to the compiler has to be passed on every compile, as GrailsAppBaseDirProvider passes base.dir. The integration test compile classpath already contains the main classes directory wherever the build puts it (build-parent/build-8070/classes/groovy/main here), so looking there may be simpler than passing a property.
There was a problem hiding this comment.
Covered here. MainClassFinder.searchMainClass now also takes the compile classpath and searches its directories that belong to the spec's own project first (the nearest build.gradle or grails-app above the directory is the spec's), before the guesses under build/. IntegrationTestAstTransformation passes it the compiler's classpath: the configuration's entries and the URLs of the class loaders it compiles against. A plugin subproject's classes directory on the classpath isn't searched, even one inside the application directory, so its own Application can't be picked. No property is involved, so the reused compiler daemon from gradle/gradle#38395 doesn't come into it.
MainClassFinderSpec covers both. And with enable-mvc-check moved to build-parent/build-8070 by an init script and no build/ in the project, all 7 integrationTest tests pass; without the change all 7 fail with No baseUrl set, as you saw.
RESOURCES_DIR took the property as given, so the relative path the Gradle plugin now passes was resolved against the forked JVM's working directory, where before it was TARGET_DIR/resources/main, tied to base.dir. A build that moves bootRun's workingDir got a resources directory that does not exist, and the i18n plugin skipped copying a changed bundle without a word. A relative value is now joined to BASE_DIR; an absolute one is kept as it is. BuildSettingsSpec covers the three cases and checks them in a JVM whose working directory is not the application's, as BuildSettings resolves them once, when it loads.
Without applicationClass, IntegrationTestAstTransformation asks MainClassFinder
for the application class, which looked only under build/: in
<project>/build/classes/main and <project>/build/classes/groovy/main. With the
build directory elsewhere and no build/ in the project, it found nothing, the
spec got no @ContextConfiguration, and its tests ran without an application
("No baseUrl set").
MainClassFinder.searchMainClass takes the compile classpath too and searches
its directories that belong to the spec's own project first: the classpath
carries the main classes directory wherever the build puts it. A directory of
another project on it, such as a plugin subproject's, even one inside the
application directory, is not searched. No system property is involved, so
the reused compiler daemon (gradle/gradle#38395) does not come into it.
|
@jdaugherty Thanks, and for ruling out gradle/gradle#38395 for the providers. Both points are fixed in the last two commits: |
jdaugherty
left a comment
There was a problem hiding this comment.
Reviewed again at head 2d85090c0d, which merges cleanly with the current 8.0.x (84b1e8a4d7). BuildSettingsSpec, MainClassFinderSpec and the plugin's org.grails.gradle.plugin.core specs pass locally.
Both points from the last round are fixed. RESOURCES_DIR now joins a relative value to the application, and the forked-JVM feature is the right test for it. For @Integration, I ran enable-mvc-check with its build directory moved to build-parent/build-8070 by an init script and no build/ in the project. The compiled spec gets @ContextConfiguration and all 7 integrationTest tests pass.
I've left three more comments inline. The first is the one that matters: the lookup still finds nothing when the build directory is outside the project.
| if (rootDir) { | ||
| File projectDir = rootDir.canonicalFile | ||
| for (File entry in classpath) { | ||
| if (entry.isDirectory() && findRootDirectory(entry)?.canonicalFile == projectDir) { |
There was a problem hiding this comment.
This only accepts a classes directory inside the spec's own project, so a build directory at the root or outside the checkout still finds nothing. The bootRun provider handles those layouts (the ../ feature), but @Integration doesn't.
I moved enable-mvc-check's build directory to <root>/build-out/<project> from an init script, which is the rootProject.layout.buildDirectory.dir(project.name) layout, and left no build/ in the project. The spec gets no @ContextConfiguration, and all 7 integrationTest tests fail with No baseUrl set. Calling searchMainClass directly with the classes from this head gives the same answer. It returns null for a root-level build directory and for one outside the checkout, and finds example.Application when the build directory is inside the project.
The compile's own output directory could decide this instead of where the directory sits. Gradle sets CompilerConfiguration.targetDirectory to the task's destination (<build>/classes/groovy/integrationTest), and the main classes directory is next to it under <build>/classes, wherever the build directory is. A plugin subproject's classes directory is under that subproject's own build directory, so it is still left out. As a throwaway probe, I passed source.configuration.targetDirectory from the transform and also accepted a classpath directory that shares the target's <build>/classes parent. With that change the root-level layout passes all 7 tests. The current check could stay as the fallback for a compile with no target directory.
While some layouts find nothing, this also affects the build cache. Whether the application class is found isn't part of compileIntegrationTestGroovy's cache key, because Gradle compares the compile classpath by its contents, not by where its directories are. After the root-level run, a run with the build directory inside the project restored the spec from the local build cache without @ContextConfiguration, and all 7 tests failed. The same run with --no-build-cache and a clean output directory passed. Once every layout finds the class, the compiled output is the same for all of them and this goes away.
There was a problem hiding this comment.
Fixed along the lines of your probe. The transform now passes source.configuration.targetDirectory, and MainClassFinder first accepts classpath directories under the same <build>/classes as the target, so a plugin subproject's classes, under its own build directory, stay out. That only applies when the target is laid out as <build>/classes/<language>/<sourceSet>, so an unusual target can't widen the search; the same-project check stays as the fallback. With enable-mvc-check in the rootProject.layout.buildDirectory.dir(project.name) layout and no build/, all 7 integrationTest tests pass with --no-build-cache. Since the class is now found in each of these layouts, the compiled spec no longer depends on which layout filled the build cache.
| * static flow typing would hold the loop's class loader to the first one's type and fail on its parent. | ||
| */ | ||
| @CompileDynamic | ||
| private static Collection<File> compileClasspath(SourceUnit source) { |
There was a problem hiding this comment.
Nothing tests compileClasspath. MainClassFinderSpec passes the classpath in directly, so no test checks what the transform hands it, and Codecov reports the new lines in this file as uncovered. Could a spec compile an @Integration class the way a build does? That means a source file inside a project directory, compiled against an application class in a classes directory that isn't under build/, and then checking that the compiled class has @ContextConfiguration(classes = Application). It would also be the natural place to cover the root-level layout from the other comment.
There was a problem hiding this comment.
Added IntegrationTestApplicationClassSpec. It compiles an @Integration spec the way a build does: a source file inside a project directory, compiled with a CompilationUnit into <build>/classes/groovy/integrationTest, against a classpath holding a plugin subproject's classes (with an Application of its own, listed first) and the application's. It then loads the spec and checks @ContextConfiguration(classes = Application), with the build directory inside the project but not build/, at the root of the checkout, and outside it. The last two fail without the target-directory change.
| * @param targetDir the target directory | ||
| * @return the resources directory | ||
| */ | ||
| static File resourcesDir(String fromSystem, File baseDir, File targetDir) { |
There was a problem hiding this comment.
Minor: resourcesDir is public, so BuildSettings gains a public static method that only the first feature in BuildSettingsSpec calls. Could it be private, with that feature's absolute case moved into the forked-JVM feature? That feature already checks RESOURCES_DIR itself, which is what the application reads.
There was a problem hiding this comment.
Done. It's private now, and the forked-JVM feature covers the absolute case alongside the relative one and no property.
|
@codeconsole you're clearly using this as part of some workflow, my guess is where you're running multiple copies. Can you help us by documenting this workflow in the docs so we can also benefit from it? |
…uild directory is Accepting only classpath directories inside the spec's own project left an @Integration spec without an application class when the build directory is at the root of the checkout (rootProject.layout.buildDirectory.dir(project.name)) or outside it. The transform now passes the compile's target directory too, and MainClassFinder first accepts classpath directories under the same <build>/classes as that target (<build>/classes/<language>/<sourceSet>), wherever <build> is; a plugin subproject's classes are under its own build directory and stay out. The same-project check remains for a compile without such a target. IntegrationTestApplicationClassSpec compiles an @Integration spec as a build does, with the build directory inside the project, at the root and outside the checkout and a plugin subproject's main class on the classpath, and checks its @ContextConfiguration. Since every layout now finds the class, the compiled spec no longer depends on which layout filled the build cache.
A section of Development Reloading: why two builds of one checkout get in each other's way, giving each instance a build directory and a Gradle project cache of its own, and what the Grails Gradle plugin passes so that reloading and @Integration tests follow the build directory.
|
@jdaugherty Sure. I've added a section to the guide's Development Reloading page, "Running More Than One Instance of a Checkout". It covers why two builds of one checkout get in each other's way, how to give each instance its own build directory ( The three inline points are fixed too; I've replied in the threads, and the description is updated. |
Environment.isDevtoolsRestart writes .grailspid into BuildSettings.TARGET_DIR, which read a project.target.dir property nothing sets and so was always <base>/build. With the build directory moved and no build/, every development start logged "spring-dev-tools restart unable to write pid file"; with build/ there, two instances of one checkout overwrote each other's marker. The grails.project.target.dir the plugin passed, documented as the property to set when the build location changes, was the build directory's name, and nothing read it. The plugin now passes the build directory relative to the project through the same provider as the classes and resources directories, and BuildSettings reads it, joined to the application directory, falling back to project.target.dir and then build. The CLI resolves TARGET_DIR in its own process, which gets no such property, so stop-app is unaffected.
jdaugherty
left a comment
There was a problem hiding this comment.
Thanks for writing this up. I ran the section end to end with the exploded example and its plugin subproject: the allprojects block applied to both, and two bootRuns on 8081 and 8082 started with these flags. Each instance got its own grails.project.class.dir and grails.project.resource.dir. An edited app controller, an edited messages.properties and an edited plugin-subproject controller were each compiled or copied into that instance's own build-parent/build-808x, and both instances served the change. Nothing was written to build/, apart from the pid file below. IntegrationTestApplicationClassSpec passes at this head, including the layout this section uses, and the three points from the last round are addressed.
Two things came up while running it, inline.
| ./gradlew bootRun -PinstanceBuildDir=build-parent/build-8081 \ | ||
| --project-cache-dir=build-parent/build-8081/.gradle \ | ||
| --args='--server.port=8081' |
There was a problem hiding this comment.
Two problems with these paths, both from running this recipe:
--project-cache-diris inside the root project's build directory, socleandeletes the project cache of the build that is running it../gradlew -PinstanceBuildDir=build-parent/build-8081 --project-cache-dir=build-parent/build-8081/.gradle cleanremovesexecutionHistory,fileHashes,buildOutputCleanupand their.lockfiles from under the running build, and still reports success.- A generated app's
.gitignorehasbuild/and.gradle, which match at any depth, but nothing matchesbuild-parent/build-8081/. So every class an instance compiles shows up as untracked ingit status.
A per-instance directory that holds both, with the build directory still named build, fixes both. The default .gitignore then covers instances/8081/build/ (in subprojects too) and instances/8081/.gradle/, and clean leaves the sibling cache alone. I checked both layouts with git check-ignore against the forge .gitignore template, and ran clean with each.
| ./gradlew bootRun -PinstanceBuildDir=build-parent/build-8081 \ | |
| --project-cache-dir=build-parent/build-8081/.gradle \ | |
| --args='--server.port=8081' | |
| ./gradlew bootRun -PinstanceBuildDir=instances/8081/build \ | |
| --project-cache-dir=instances/8081/.gradle \ | |
| --args='--server.port=8081' |
There was a problem hiding this comment.
Both confirmed, and fixed in 938dbb5 with your layout. With the cache inside the build directory, clean exited 0 and took buildOutputCleanup and vcs-1 out of the running build's project cache; with instances/8081/.gradle beside instances/8081/build, it left the cache alone. Against the forge .gitignore template, git check-ignore matches instances/8081/build/…, instances/8081/.gradle/… and a subproject's sub/instances/8081/build/…, while build-parent/build-8081/classes/… shows as untracked. The paragraph under the command now says to keep the cache beside the build directory, not inside it, and why the two names stay out of version control.
|
|
||
| The project cache (the checkout's `.gradle/` directory) does not move with the build directory, and two builds running at once contend for it, so `--project-cache-dir` gives each build its own. | ||
|
|
||
| The Grails Gradle plugin tells the application where its build directory is. It passes `grails.project.class.dir` and `grails.project.resource.dir` to `bootRun` and the other forked `JavaExec` and `Test` tasks, so development reloading compiles a changed class and copies a changed message bundle into that instance's build directory, and the application reads its resources from there. An `@Integration` test without an `applicationClass` finds the application class next to its own compiled classes, wherever the build directory is. |
There was a problem hiding this comment.
With this section applied, every start and every devtools restart logs an ERROR with a stack trace:
ERROR grails.util.Environment : spring-dev-tools restart unable to write pid file: {}
java.io.FileNotFoundException: .../grails-test-examples/exploded/build/.grailspid (No such file or directory)
at grails.util.Environment.writeDevToolsPidFile(Environment.groovy:381)
at grails.util.Environment.isDevtoolsRestart(Environment.groovy:368)
at grails.boot.GrailsApp.run(GrailsApp.groovy:142)
Environment.isDevtoolsRestart() writes .grailspid to BuildSettings.TARGET_DIR. That still resolves to <app>/build, which doesn't exist in this setup. The plugin does pass a target directory, but it has no effect. configureForkSettings passes grails.project.target.dir with only the directory name (build-8081), and BuildSettings reads project.target.dir.
Could TARGET_DIR follow the build directory the way the classes and resources directories now do? For example, BuildSettings could read PROJECT_TARGET_DIR joined to BASE_DIR, with project.target.dir kept as the fallback, and the plugin could pass the build directory relative to the project through GrailsProjectOutputDirProvider instead of its name. Each instance's pid file would then go into its own build directory, not a shared build/.grailspid. Any moved build directory already hits this, but this section is what will lead people into that setup.
There was a problem hiding this comment.
Fixed in 52ffa6a much as you suggest: the plugin passes the build directory relative to the project through GrailsProjectOutputDirProvider, and BuildSettings.TARGET_DIR reads grails.project.target.dir joined to BASE_DIR (an absolute one kept as it is).
One difference, in bdb139d: project.target.dir comes first, not as the fallback. It was the only property read, and -Dgrails.project.target.dir given to Gradle reaches the application as project.target.dir, since configureForkSettings passes grails.* system properties on without their prefix, so reading the plugin's value first would override anyone who set it that way.
BuildSettingsSpec covers a relative and an absolute property, project.target.dir alone and over it, neither, and a development start given a moved build directory and no build/: .grailspid lands in that directory, no build/ is created and nothing is logged. An application started with its build directory moved and no build/ now starts without the ERROR, its marker in its own build directory.
…rectory project.target.dir was the only property TARGET_DIR read, and a build sets it by hand: -Dgrails.project.target.dir given to Gradle reaches the application as project.target.dir, since the plugin passes grails.* system properties on without their prefix. Reading the plugin's grails.project.target.dir first would have overridden it, so a value set by hand now comes first, and an existing setup resolves TARGET_DIR as it did.
…guide The recipe put the project cache inside the root project's build directory, so clean deleted the cache of the build running it (buildOutputCleanup, vcs-1) and still succeeded; and nothing in a generated application's .gitignore matched build-parent/build-8081/, so every class an instance compiled showed as untracked. instances/8081/build and instances/8081/.gradle fix both: clean leaves the sibling cache alone, and the template's build/ and .gradle match them at any depth, in subprojects too.
jdaugherty
left a comment
There was a problem hiding this comment.
Re-checked at 938dbb5. Both points from my last review are fixed.
- I ran the guide's recipe on
grails-test-examples/exploded(with its plugin subproject) with-PinstanceBuildDir=instances/8081/build --project-cache-dir=instances/8081/.gradle. The forked JVM gets-Dgrails.project.target.dir=instances/8081/build, and.grailspidis written toinstances/8081/build/. Nobuild/is created in the app or the plugin subproject, and startup no longer logs theFileNotFoundException. cleanwith the same flags removesinstances/8081/buildin both projects and leavesinstances/8081/.gradlealone.- Against the base profile's
.gitignore,git check-ignoreignoresinstances/8081/build/…,instances/8081/.gradle/…and a subproject'sinstances/8081/build/…. BuildSettingsSpec(9 tests) andGrailsGradlePluginToolchainSpec(16 tests) pass locally, andcodeStyleis clean for both modules.
Reading project.target.dir first makes sense. configureForkSettings strips the grails. prefix, so a -Dgrails.project.target.dir given to Gradle reaches the app under that name, and it keeps winning as it did before. stop-app is unaffected too, because it resolves run-app.pid from the CLI JVM's own TARGET_DIR, and the CLI JVM never receives the property.
One minor note inline. It doesn't block merging.
| File dir = directory.get().asFile | ||
| String relative = relativePath(projectDir.toPath(), dir.toPath()) | ||
| if (relative == null) { | ||
| LOG.warn('{} is not passed: {} has no path relative to the project directory {}, so development reloading ' + |
There was a problem hiding this comment.
Minor, not blocking. Now that the target directory goes through this provider too, a build directory with no path relative to the project (one on another drive on Windows) logs this warning three times for each forked task, once per property. For grails.project.target.dir the wording is also off: that property has nothing to do with reloading, and without it the .grailspid write is what fails. Could the warning name the consequence for each property, or be logged only for the classes directory, which already explains why reloading breaks?
Similarly, the class Javadoc (line 68) says the directories are tracked through the task's classpath, which isn't true of the build directory itself.
There was a problem hiding this comment.
Thanks, done in 03699f5. Each property's warning now says what its own fallback breaks: for grails.project.class.dir that a changed class is compiled into build/classes/groovy/main and not reloaded; for grails.project.resource.dir that resources are read from, and a changed message bundle copied into, build/resources/main; and for grails.project.target.dir that the restart marker goes to build/ and an error is logged at each start if there is none. A directory on another drive still logs one line per property, but each says something different, and GrailsProjectOutputDirProviderSpec checks the three. The class Javadoc now says only the classes and resources directories are tracked through the classpath; the build directory itself only says where the application writes its restart marker, which nothing the task produces depends on.
With the target directory passed through the provider too, a build directory with no path relative to the project warned three times per forked task, each time that changes would not be reloaded, which is untrue of the resources directory in part and of the target directory entirely: without it the restart marker goes to build/, and its write fails when there is none. Each warning now names its own property's consequence. The class Javadoc no longer says every directory is tracked through the task's classpath, which the build directory itself is not.
✅ All tests passed ✅🏷️ Commit: 03699f5 Learn more about TestLens at testlens.app/docs. |
Problem
In development a changed source file is compiled again by
GrailsApp.recompile, intonew File(appDir, BuildSettings.BUILD_CLASSES_PATH).BUILD_CLASSES_PATHis thegrails.project.class.dirsystem property, or else the fixedbuild/classes/groovy/main. The Gradle plugin's fork settings pass onlygrails.project.target.dir, set to the build directory's name, nevergrails.project.class.dir.So an application whose build directory is not
build/has each change compiled where it does not load classes from. A second instance of one checkout built with-PbuildDir=build-parent/build-8070, so that a build does not rewrite the classes the first instance runs from, is the case we hit: the edit lands inbuild/classes/groovy/main, the plugin manager is told of the change and replaces the artefact's bean (Overriding bean definition for bean '…Controller' with a different definition), but the class it loads is the one already on the instance's classpath. The old code goes on answering, with nothing in the log to say so. And the class written intobuild/classesrestarts any other instance of the checkout that does run frombuild/.Resources have the same gap.
BuildSettings.RESOURCES_DIR, where the application reads resources from in development, isgrails.project.resource.diror else<base>/build/resources/main.BUILD_RESOURCES_PATH, where the i18n plugin copies a changed message bundle, is fixed atbuild/resources/main. AndIOUtilsmaps a class root to its resources root by replacing/build/classes/groovy/with/build/resources/. With the build directory moved, all three point intobuild/, so a second instance reads resources from, and copies message bundles into, the other instance's build.So does the development restart marker.
Environment.isDevtoolsRestartwrites.grailspidintoBuildSettings.TARGET_DIR, which read onlyproject.target.dir, set by nothing, so it was always<base>/build. With the build directory moved and nobuild/, every development start logsspring-dev-tools restart unable to write pid file; withbuild/there, two instances share one marker. The plugin passedgrails.project.target.dir, documented as the property to set when the build location changes, but only as the build directory's name, and nothing read it.Change
GrailsProjectOutputDirProvider, besideGrailsAppBaseDirProvider, is added to forked JVM tasks three times:grails.project.class.diris the main source set's Groovy classes directory,grails.project.resource.diris its resources directory, andgrails.project.target.diris the build directory itself, in place of its name. Each is relative to the project directory, because it is joined to a project directory, with its names joined by/on every platform, becauseIOUtilscompares the classes path with class locations written as URLs. It is read when the task runs, so a build directory changed after the plugin is applied is the one passed, and it is@Internal, as the classes and resources directories are already the task's classpath and the build directory holds them.-Dwins, so the provider passes nothing when the task'ssystemPropertiesalready have it.BuildSettings.BUILD_RESOURCES_PATHnow comes fromgrails.project.resource.dir, elsebuild/resources/main, asBUILD_CLASSES_PATHdoes, so it is no longer a compile-time constant.RESOURCES_DIRjoins a relative value toBASE_DIR, not the working directory, which a build can move; an absolute value is kept as it is.BuildSettings.TARGET_DIRreadsgrails.project.target.dir, joined toBASE_DIR(an absolute one kept as it is), so the restart marker is in the instance's own build directory. Aproject.target.dirset by hand still comes first: it was the only property read, and-Dgrails.project.target.dirgiven to Gradle reaches the application as it, since the plugin passesgrails.*system properties on without their prefix. Without either it isbuild, as before.IOUtils.findRootResourcesURLandfindResourceRelativeToClassmap a class root to its resources root by the build's classes and resources paths (resourcesRootFor). With the default layout the result is the same as before.@Integrationspec withoutapplicationClassgets its application class fromMainClassFinder.searchMainClass, which looked only underbuild/. With the build directory elsewhere and nobuild/in the project, the spec got no@ContextConfigurationand its tests ran without an application.IntegrationTestAstTransformationnow passes the compile classpath and target directory, andMainClassFindersearches the classpath directories under the same<build>/classesas the target (<build>/classes/<language>/<sourceSet>) first, since the classpath carries the main classes directory wherever the build puts it: inside the project, at the root of the checkout, or outside it. A plugin subproject's classes are under its own build directory, so they aren't searched; for a compile without such a target, the directories in the spec's own project are searched instead. No system property is involved, so the reused compiler daemon (Forked compiler daemon reuse ignores forkOptions.jvmArgumentProviders, leaking system properties between compile tasks gradle/gradle#38395) doesn't come into it.With the default build directory the values passed are
build/classes/groovy/main,build/resources/mainandbuild, whatBuildSettingsalready chose, so nothing changes there.Limits, also in the provider's Javadoc:
-PbuildDir, or anallprojectsblock).../path. Joining it resolves correctly; theIOUtilscomparisons don't match it and fall back as before.stop-appstill looks for the run-app PID file under<base>/build, as before: the CLI resolvesTARGET_DIRin its own process, which gets none of these properties, and the forked application writes that file through a property of its own underlayout.buildDirectory(configureBootRunPidFilealready says a moved build directory isn't supported there).Tests
GrailsProjectOutputDirProviderSpec:/separators, a path outside the project, the different-roots fallback, a value the task sets being kept, and the resources property.GrailsGradlePluginToolchainSpecwith thebootrun-classes-dirtest project, reading the three properties fromtask.allJvmArgs(the last-D, as the JVM gets it): the default layout, the build directory moved tobuild-parent/build-8070and to../outside-build, and a build that setsgrails.project.class.dironbootRunkeeping its value.IOUtilsSpec:resourcesRootForfor the default layout, a moved build directory, another source set, a directory name that only ends like the path, and a JAR.BuildSettingsSpec, in a JVM whose working directory is next to the application:RESOURCES_DIRfor a relative, an absolute and no property (the relative case fails with the previous line);TARGET_DIRfor a relative and an absolutegrails.project.target.dir,project.target.diralone and over it, and neither; and a development start givenbuild-parent/build-8070and nobuild/writing.grailspidthere, creating nobuild/and logging no pid-file error. The relative, absolute and restart-marker cases fail with the previousTARGET_DIRline, and the by-hand case with the plugin's property read first.MainClassFinderSpec: a main class outsidebuild/is found only through the classpath; with the build directory at the root of the checkout or outside it, it is found next to the compile output; a plugin subproject's main class is not picked; and a target not laid out as<build>/classes/...doesn't widen the search.IntegrationTestApplicationClassSpec: compiles an@Integrationspec as a build does (a source file in a project directory, aCompilationUnitwith the target directory and classpath) with the build directory inside the project, at the root and outside the checkout, and checks its@ContextConfiguration. The last two fail without the target-directory change.enable-mvc-checkwith its build directory moved by an init script and nobuild/in the project: tobuild-parent/build-8070, all 7integrationTesttests pass, and without the@Integrationchange all 7 fail withNo baseUrl set; to<root>/build-out/<project>, all 7 pass with--no-build-cache.codeStyleis clean forgrails-gradle-plugins,grails-gradle-modelandgrails-testing-support-core, and the wholegrails-gradle-modeltest suite passes. I have not run the whole./gradlew build.Verified end to end for classes in an application started with
-PbuildDir=build-parent/build-<port>: before, a controller edit compiled intobuild/classesand the page kept serving the old code; with the property passed, the edit compiled into the instance's own classes, devtools restarted it, and the change was served. The resources part is covered by the tests above but not yet by an end-to-end run.And for the restart marker, a test application started with its build directory at
build-parent/build-8070and nobuild/: before, it loggedspring-dev-tools restart unable to write pid fileand wrote no marker; with this change it starts without the error,.grailspidis inbuild-parent/build-8070, and nobuild/is created.Docs
A section of the guide's Development Reloading page, "Running More Than One Instance of a Checkout": why two builds of one checkout get in each other's way, giving each instance its own build directory (
layout.buildDirectoryfrom a property, for every project) and Gradle project cache, side by side underinstances/<port>/so thatcleanleaves the cache alone and a generated application's.gitignorecovers both, and what the plugin passes so that reloading, the restart marker and@Integrationfollow the build directory.