This is an automated email from the ASF dual-hosted git repository.

jdaugherty pushed a commit to branch fix/16711-gsp-compile-environment
in repository https://gitbox.apache.org/repos/asf/grails-core.git

commit d9f20b8432b06336d9736d455f9d7826fec2098f
Author: James Daugherty <[email protected]>
AuthorDate: Wed Oct 21 14:35:52 2026 -0400

    Compile views for a stated Grails environment, and key the build cache on it
    
    The forked compilers that compile GSP pages, JSON views and markup views 
ahead
    of time read application.yml and application.groovy for the environment they
    run in: CodeGenConfig merges that environment's block over the rest, and the
    page parser writes the codecs it reads there into the compiled page as
    constants. The environment was never stated to the compiler. It fell back to
    GRAILS_ENV, inherited from the Gradle daemon and so from the shell, and to
    development where that was not set; -Dgrails.env given to Gradle never 
reached
    it. The compile tasks have been cacheable since 8a3cf63ae2 with no input for
    the environment, so two clean builds that differed only in GRAILS_ENV 
shared a
    cache entry, and a production build could be handed pages compiled with
    development's codecs.
    
    The tasks now carry the environment as an input, grailsEnvironment, and pass
    it to the compiler as the grails.env system property, so nothing the 
compiler
    inherits decides. It defaults to the environment the build runs with - a
    -Dgrails.env the build already gave the compiler among the fork options, 
else
    the grails.env system property given to Gradle, else GRAILS_ENV, each read 
for
    a blank before the next is consulted, as the application's own resolution
    reads them - and to production where none is set, which is what the archive
    the views are packaged into is built for, and what grails.build.info already
    records. The fork argument is read as the default and withheld from the
    compiler, which gets the input, and a blank input fails the build rather 
than
    leaving the compiler to what it inherits. A build that set GSP codecs only
    under environments.development used to ship them in its archive; it now gets
    the production configuration there, as the running application does.
    
    An environment change has to reach every page. The page compiler leaves a 
page
    alone whose class in the destination is newer than its source, and leaves 
the
    class of a page that is gone, so a production build after a development one
    would keep development's pages and store them in the cache under 
production's
    key. Each compile task now empties its destination before it compiles, and
    the destination holds exactly what the execution compiled, which is what the
    cache keeps under its key. The page compile task's source directory is
    internal rather than an input directory, since the pages are fingerprinted
    through the source and the directory need not exist.
    
    Fixes #16711
---
 grails-doc/src/en/guide/conf/environments.adoc     |  26 ++
 .../views/AbstractGroovyTemplateCompileTask.groovy |  46 +++-
 .../plugin/views/ViewCompileEnvironment.groovy     | 163 ++++++++++++
 .../views/gsp/GroovyPageForkCompileTask.groovy     |  58 ++++-
 .../grails/plugin/json/view/JsonViewCompiler.java  |  58 +++++
 ...ractViewCompileEnvironmentFunctionalSpec.groovy | 280 +++++++++++++++++++++
 .../plugin/views/ViewCompileEnvironmentSpec.groovy | 171 +++++++++++++
 ...oovyPageCompileEnvironmentFunctionalSpec.groovy |  58 +++++
 ...GsonViewCompileEnvironmentFunctionalSpec.groovy |  60 +++++
 .../grails/web/pages/GroovyPageForkedCompiler.java |  58 +++++
 .../gson-compile-environment/build.gradle          |  12 +
 .../gson-compile-environment/settings.gradle       |   1 +
 .../gsp-compile-environment/build.gradle           |  16 ++
 .../gsp-compile-environment/settings.gradle        |   1 +
 14 files changed, 1003 insertions(+), 5 deletions(-)

diff --git a/grails-doc/src/en/guide/conf/environments.adoc 
b/grails-doc/src/en/guide/conf/environments.adoc
index 472d809c1c..01b89cfbf8 100644
--- a/grails-doc/src/en/guide/conf/environments.adoc
+++ b/grails-doc/src/en/guide/conf/environments.adoc
@@ -139,6 +139,32 @@ grails -Dgrails.env=UAT run-app
 ./gradlew bootRun -Dgrails.env=UAT
 ----
 
+Views are compiled ahead of time by the build: GSP pages by the 
`compileGroovyPages` and `compileWebappGroovyPages` tasks, JSON views by 
`compileGsonViews` and markup views by `compileGmlViews`. The page compiler 
reads `application.yml` and `application.groovy`, and the view compilers 
`application.yml`, for one environment, so the settings a compiled view 
carries, such as the GSP codecs under `grails.views.gsp.codecs`, are those of 
that environment. The build compiles its views for the e [...]
+
+[source,bash]
+----
+./gradlew bootJar -Dgrails.env=UAT
+----
+
+The same compiled views serve the tests, so a setting a compiled view carries 
belongs at the top level of the configuration rather than under 
`environments.test`, or the tests are run with the environment stated as above.
+
+A build can state the environment on the compile tasks instead, each of which 
has a `grailsEnvironment` property:
+
+[source,groovy]
+----
+import org.grails.gradle.plugin.views.AbstractGroovyTemplateCompileTask
+import org.grails.gradle.plugin.views.gsp.GroovyPageForkCompileTask
+
+tasks.withType(GroovyPageForkCompileTask).configureEach {
+    grailsEnvironment = 'uat'
+}
+tasks.withType(AbstractGroovyTemplateCompileTask).configureEach {
+    grailsEnvironment = 'uat'
+}
+----
+
+The environment is part of what the compiled views are, so the build cache 
keeps views compiled for different environments apart.
+
 
 === Programmatic Environment Detection
 
diff --git 
a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/AbstractGroovyTemplateCompileTask.groovy
 
b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/AbstractGroovyTemplateCompileTask.groovy
index ff69e8a401..2f7d3a5f4d 100644
--- 
a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/AbstractGroovyTemplateCompileTask.groovy
+++ 
b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/AbstractGroovyTemplateCompileTask.groovy
@@ -25,6 +25,7 @@ import groovy.transform.CompileDynamic
 import groovy.transform.CompileStatic
 
 import org.gradle.api.Action
+import org.gradle.api.GradleException
 import org.gradle.api.file.ConfigurableFileCollection
 import org.gradle.api.file.DirectoryProperty
 import org.gradle.api.file.FileTree
@@ -46,9 +47,21 @@ import org.gradle.process.ExecResult
 import org.gradle.process.JavaExecSpec
 import org.gradle.work.InputChanges
 
+import grails.util.Environment
+
 /**
  * Abstract Gradle task for compiling templates, using 
GenericGroovyTemplateCompiler
  *
+ * <p>Cacheable. What a view compiles to depends on the Groovy that compiles 
it and the classes it
+ * is compiled against, which {@code AbstractCompile} declares as the 
classpath input, on the Java it
+ * is compiled for, and on the Grails environment whose configuration it is 
compiled with, which is
+ * {@link #getGrailsEnvironment()}.</p>
+ *
+ * <p>Compiles from an empty destination. The compiler leaves the class of a 
view that is gone, so a
+ * destination that kept what an earlier execution compiled would carry views 
that no longer exist
+ * into the archive and the build cache. The destination is emptied before 
each execution and holds
+ * exactly what it compiled, which is what the cache keeps under its key.</p>
+ *
  * @author Graeme Rocher
  * @since 1.0
  */
@@ -83,6 +96,24 @@ abstract class AbstractGroovyTemplateCompileTask extends 
AbstractCompile {
     @Input
     final SetProperty<String> projectPackageNames
 
+    /**
+     * The Grails environment the views are compiled for, by name.
+     *
+     * <p>A view is compiled against the configuration of one environment: the 
forked compiler merges
+     * that environment's block of {@code application.yml} over the rest 
before it reads the settings
+     * of its view type. The environment is therefore part of what the views 
are, and part of the cache
+     * key, so views compiled for one environment are not restored into a 
build for another.</p>
+     *
+     * <p>Defaults as {@link ViewCompileEnvironment#defaultFor} says: to an 
environment the fork
+     * options of {@link #getCompileOptions()} already name, else to the one 
the build runs with, else
+     * to {@code production}. Stated to the forked compiler as the {@code 
grails.env} system property,
+     * in place of any the fork options name, so that nothing the compiler 
inherits decides.</p>
+     *
+     * @since 7.0.18
+     */
+    @Input
+    final Property<String> grailsEnvironment
+
     @PathSensitive(PathSensitivity.RELATIVE)
     @Override
     FileTree getSource() {
@@ -100,6 +131,7 @@ abstract class AbstractGroovyTemplateCompileTask extends 
AbstractCompile {
         fileExtension = 
objectFactory.property(String).convention(extensionDefault)
         scriptBaseName = 
objectFactory.property(String).convention(scriptBaseNameDefault)
         compilerName = 
objectFactory.property(String).convention(compilerNameDefault)
+        grailsEnvironment = 
objectFactory.property(String).convention(ViewCompileEnvironment.defaultFor(project.providers,
 compileOptions))
         grailsConfigurationPaths = objectFactory.fileCollection()
         grailsConfigurationPaths.from(
                 //TODO: historically this only used .yml, should it explore 
all configuration paths?
@@ -122,6 +154,8 @@ abstract class AbstractGroovyTemplateCompileTask extends 
AbstractCompile {
 
     @TaskAction
     void execute(InputChanges inputs) {
+        emptyDestination()
+        String environment = 
ViewCompileEnvironment.forCompiler(grailsEnvironment, path)
         ExecResult result = execOperations.javaexec(
                 new Action<JavaExecSpec>() {
                     @Override
@@ -130,12 +164,13 @@ abstract class AbstractGroovyTemplateCompileTask extends 
AbstractCompile {
                         javaExecSpec.mainClass.set(compilerName)
                         javaExecSpec.classpath = classpath
 
-                        List<String> jvmArgs = 
compileOptions.forkOptions.jvmArgs
+                        List<String> jvmArgs = 
ViewCompileEnvironment.withoutStated(compileOptions.forkOptions.jvmArgs)
                         if (jvmArgs) {
                             javaExecSpec.jvmArgs(jvmArgs)
                         }
                         javaExecSpec.maxHeapSize = 
compileOptions.forkOptions.memoryMaximumSize
                         javaExecSpec.minHeapSize = 
compileOptions.forkOptions.memoryInitialSize
+                        javaExecSpec.systemProperty(Environment.KEY, 
environment)
 
                         String packageImports = 
projectPackageNames.get().join(',') ?: packageName.get()
 
@@ -163,6 +198,15 @@ abstract class AbstractGroovyTemplateCompileTask extends 
AbstractCompile {
         // no-op
     }
 
+    /** Empties the destination, so that it holds exactly what this execution 
compiles; see the class comment. */
+    private void emptyDestination() {
+        File destination = destinationDirectory.get().asFile
+        if (destination.exists() && !destination.deleteDir()) {
+            throw new GradleException("Could not empty ${destination} before 
compiling the views into it")
+        }
+        destination.mkdirs()
+    }
+
     Set<String> getProjectPackageNames(File baseDir) {
         File rootDir = baseDir ? new File(baseDir, 
"grails-app${File.separator}domain") : null
         Set<String> packageNames = []
diff --git 
a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironment.groovy
 
b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironment.groovy
new file mode 100644
index 0000000000..b5ae076d70
--- /dev/null
+++ 
b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironment.groovy
@@ -0,0 +1,163 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.gradle.plugin.views
+
+import java.util.concurrent.Callable
+
+import groovy.transform.CompileStatic
+
+import org.gradle.api.InvalidUserDataException
+import org.gradle.api.Transformer
+import org.gradle.api.provider.Provider
+import org.gradle.api.provider.ProviderFactory
+
+import grails.util.Environment
+
+/**
+ * The Grails environment a build compiles its views for.
+ *
+ * <p>Pages, JSON views and markup views are compiled ahead of time by a 
forked compiler that reads
+ * the application's configuration for the environment it runs in, so what a 
view compiles to - the
+ * codecs a page carries, for one - depends on that environment. The compile 
tasks state the
+ * environment as an input and hand it to the compiler, rather than leaving 
the compiler to whatever
+ * it inherits. This is where the input's default comes from, and how the 
input is read.</p>
+ *
+ * @since 7.0.18
+ */
+@CompileStatic
+final class ViewCompileEnvironment {
+
+    /** The JVM argument a build gave the compiler its environment by, before 
the task had an input for it. */
+    private static final String STATED_ARGUMENT = "-D${Environment.KEY}="
+
+    /** The names Grails accepts for the environments it knows, each with the 
environment's full name. */
+    private static final Map<String, String> NAMES = [
+            dev: Environment.DEVELOPMENT.name,
+            development: Environment.DEVELOPMENT.name,
+            prod: Environment.PRODUCTION.name,
+            production: Environment.PRODUCTION.name,
+            test: Environment.TEST.name,
+    ].asImmutable()
+
+    private ViewCompileEnvironment() {
+    }
+
+    /**
+     * The default for a compile task's {@code grailsEnvironment}: an 
environment the build gave the
+     * compiler itself, as a {@code -Dgrails.env} JVM argument among the fork 
options of
+     * {@code options}, which is how a build chose the environment before the 
task had an input for
+     * it, else {@link #ofBuild the one the build runs with}.
+     *
+     * @param providers the build's providers
+     * @param options the task's compile options, whose fork options may name 
the environment
+     * @return the name of the environment, never absent
+     */
+    static Provider<String> defaultFor(ProviderFactory providers, 
ViewCompileOptions options) {
+        providers.provider({ -> statedIn(options.forkOptions.jvmArgs) } as 
Callable<String>)
+                .orElse(ofBuild(providers))
+    }
+
+    /**
+     * The environment the build runs with: the {@code grails.env} system 
property given to Gradle,
+     * else the {@code GRAILS_ENV} environment variable, and {@code 
production} where neither is set,
+     * as the archive the views are packaged into is built for production 
unless the build says
+     * otherwise.
+     *
+     * @param providers the build's providers, which read the property and the 
variable
+     * @return the name of the environment, never absent
+     */
+    static Provider<String> ofBuild(ProviderFactory providers) {
+        resolve(providers.systemProperty(Environment.KEY), 
providers.environmentVariable(Environment.ENV_KEY))
+    }
+
+    /**
+     * The environment {@code stated} names, else the one {@code inherited} 
names, else
+     * {@code production}. Each is read as {@link #canonicalName} reads it, so 
a blank one counts as
+     * not set and leaves the choice to the next, as the application's own 
resolution does.
+     *
+     * @param stated the name the build was given, the {@code grails.env} 
system property
+     * @param inherited the name the build inherited, the {@code GRAILS_ENV} 
environment variable
+     * @return the name of the environment, never absent
+     */
+    static Provider<String> resolve(Provider<String> stated, Provider<String> 
inherited) {
+        Transformer<String, String> canonical = { String name -> 
canonicalName(name) } as Transformer<String, String>
+        stated.map(canonical)
+                .orElse(inherited.map(canonical))
+                .orElse(Environment.PRODUCTION.name)
+    }
+
+    /**
+     * The environment a compile task states to the compiler: its {@code 
grailsEnvironment}, by the
+     * environment's full name. A blank one fails the build: the compiler 
would read an environment
+     * from what it inherits instead, which the input would not record.
+     *
+     * @param stated the task's {@code grailsEnvironment}
+     * @param task the path of the task, for the message
+     * @return the environment's full name
+     */
+    static String forCompiler(Provider<String> stated, String task) {
+        String name = canonicalName(stated.getOrNull())
+        if (name == null) {
+            throw new InvalidUserDataException("The grailsEnvironment of 
${task} is blank; it has to name the environment the views are compiled for")
+        }
+        name
+    }
+
+    /**
+     * The environment a build gave the compiler itself, as a {@code 
-Dgrails.env} JVM argument among
+     * the fork options of its compile task. The last one wins, as it does on 
a JVM command line.
+     *
+     * @param jvmArgs the JVM arguments of the compiler, possibly null
+     * @return the environment's full name, or null where none is given or the 
one given is blank
+     */
+    static String statedIn(List<String> jvmArgs) {
+        String argument = jvmArgs?.reverse()?.find { String arg -> 
arg.startsWith(STATED_ARGUMENT) }
+        argument == null ? null : 
canonicalName(argument.substring(STATED_ARGUMENT.length()))
+    }
+
+    /**
+     * {@code jvmArgs} without any {@code -Dgrails.env} among them: the task 
states the environment to
+     * the compiler from its input, which that argument was read into, so that 
the input is what the
+     * compiler gets whatever the argument says.
+     *
+     * @param jvmArgs the JVM arguments of the compiler, possibly null
+     * @return the arguments to start the compiler with
+     */
+    static List<String> withoutStated(List<String> jvmArgs) {
+        jvmArgs?.findAll { String arg -> !arg.startsWith(STATED_ARGUMENT) } ?: 
[]
+    }
+
+    /**
+     * The full name of the environment {@code name} refers to: for an 
environment Grails knows, the
+     * name it gives it, whatever the case and whether {@code name} is the 
short form such as
+     * {@code prod}; for any other, {@code name} as given, since a custom 
environment's configuration
+     * block is named by it. {@code null} where {@code name} is blank, so that 
a blank setting counts
+     * as none.
+     *
+     * @param name the name as stated
+     * @return the environment's full name, or null for a blank name
+     */
+    static String canonicalName(String name) {
+        String trimmed = name?.trim()
+        if (!trimmed) {
+            return null
+        }
+        NAMES.get(trimmed.toLowerCase(Locale.ROOT)) ?: trimmed
+    }
+}
diff --git 
a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageForkCompileTask.groovy
 
b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageForkCompileTask.groovy
index c9f181895d..ede3ab8ec3 100644
--- 
a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageForkCompileTask.groovy
+++ 
b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageForkCompileTask.groovy
@@ -28,6 +28,7 @@ import groovy.transform.CompileDynamic
 import groovy.transform.CompileStatic
 
 import org.gradle.api.Action
+import org.gradle.api.GradleException
 import org.gradle.api.file.ConfigurableFileCollection
 import org.gradle.api.file.Directory
 import org.gradle.api.file.DirectoryProperty
@@ -36,8 +37,8 @@ import org.gradle.api.model.ObjectFactory
 import org.gradle.api.provider.Property
 import org.gradle.api.tasks.CacheableTask
 import org.gradle.api.tasks.Input
-import org.gradle.api.tasks.InputDirectory
 import org.gradle.api.tasks.InputFiles
+import org.gradle.api.tasks.Internal
 import org.gradle.api.tasks.LocalState
 import org.gradle.api.tasks.Nested
 import org.gradle.api.tasks.Optional
@@ -50,6 +51,8 @@ import org.gradle.process.ExecOperations
 import org.gradle.process.ExecResult
 import org.gradle.process.JavaExecSpec
 
+import grails.util.Environment
+import org.grails.gradle.plugin.views.ViewCompileEnvironment
 import org.grails.gradle.plugin.views.ViewCompileOptions
 
 /**
@@ -57,6 +60,17 @@ import org.grails.gradle.plugin.views.ViewCompileOptions
  * This Task is a Forked Java Task that is configurable with fork options 
provided
  * by {@link ViewCompileOptions}
  *
+ * <p>Cacheable. What a page compiles to depends on the Groovy that compiles 
it and the classes it
+ * is compiled against, which {@code AbstractCompile} declares as the 
classpath input, on the Java it
+ * is compiled for, and on the Grails environment whose configuration it is 
compiled with, which is
+ * {@link #getGrailsEnvironment()}.</p>
+ *
+ * <p>Compiles from an empty destination. The compiler leaves a page alone 
whose class is newer than
+ * its source, and leaves the class of a page that is gone, so a destination 
that kept what an earlier
+ * execution compiled would carry pages of another environment, classpath or 
configuration, or pages
+ * that no longer exist, into the archive and the build cache. The destination 
is emptied before each
+ * execution and holds exactly what it compiled, which is what the cache keeps 
under its key.</p>
+ *
  * @author David Estes
  * @since 4.0
  */
@@ -72,8 +86,12 @@ abstract class GroovyPageForkCompileTask extends 
AbstractCompile {
     @PathSensitive(PathSensitivity.RELATIVE)
     final ConfigurableFileCollection grailsConfigurationPaths
 
-    @InputDirectory
-    @PathSensitive(PathSensitivity.RELATIVE)
+    /**
+     * The directory of the pages, which the compiler names them under. 
Internal rather than an input
+     * directory: its pages are fingerprinted as part of {@link #getSource()}, 
and it need not exist -
+     * a project without {@code src/main/webapp} has no webapp pages.
+     */
+    @Internal
     final DirectoryProperty srcDir
 
     @Nested
@@ -86,6 +104,25 @@ abstract class GroovyPageForkCompileTask extends 
AbstractCompile {
     @Optional
     final Property<String> serverpath
 
+    /**
+     * The Grails environment the pages are compiled for, by name.
+     *
+     * <p>A page is compiled against the configuration of one environment: the 
forked compiler merges
+     * that environment's block of {@code application.yml} and {@code 
application.groovy} over the rest
+     * before it reads the codecs and the other settings a page carries once 
compiled. The environment
+     * is therefore part of what the pages are, and part of the cache key, so 
pages compiled for one
+     * environment are not restored into a build for another.</p>
+     *
+     * <p>Defaults as {@link ViewCompileEnvironment#defaultFor} says: to an 
environment the fork
+     * options of {@link #getCompileOptions()} already name, else to the one 
the build runs with, else
+     * to {@code production}. Stated to the forked compiler as the {@code 
grails.env} system property,
+     * in place of any the fork options name, so that nothing the compiler 
inherits decides.</p>
+     *
+     * @since 7.0.18
+     */
+    @Input
+    final Property<String> grailsEnvironment
+
     private ExecOperations execOperations
 
     @OutputDirectory
@@ -98,6 +135,7 @@ abstract class GroovyPageForkCompileTask extends 
AbstractCompile {
         srcDir = objectFactory.directoryProperty()
         compileOptions = objectFactory.newInstance(ViewCompileOptions)
         serverpath = objectFactory.property(String)
+        grailsEnvironment = 
objectFactory.property(String).convention(ViewCompileEnvironment.defaultFor(project.providers,
 compileOptions))
         grailsConfigurationPaths = objectFactory.fileCollection()
         grailsConfigurationPaths.from(
                 
project.layout.projectDirectory.file('grails-app/conf/application.yml'),
@@ -138,6 +176,8 @@ abstract class GroovyPageForkCompileTask extends 
AbstractCompile {
     }
 
     protected void compile() {
+        emptyDestination()
+        String environment = 
ViewCompileEnvironment.forCompiler(grailsEnvironment, path)
         ExecResult result = execOperations.javaexec(
                 new Action<JavaExecSpec>() {
                     @Override
@@ -146,12 +186,13 @@ abstract class GroovyPageForkCompileTask extends 
AbstractCompile {
                         javaExecSpec.mainClass.set(getCompilerName())
                         javaExecSpec.setClasspath(getClasspath())
 
-                        def jvmArgs = compileOptions.forkOptions.jvmArgs
+                        List<String> jvmArgs = 
ViewCompileEnvironment.withoutStated(compileOptions.forkOptions.jvmArgs)
                         if (jvmArgs) {
                             javaExecSpec.jvmArgs(jvmArgs)
                         }
                         
javaExecSpec.setMaxHeapSize(compileOptions.forkOptions.memoryMaximumSize)
                         
javaExecSpec.setMinHeapSize(compileOptions.forkOptions.memoryInitialSize)
+                        javaExecSpec.systemProperty(Environment.KEY, 
environment)
 
                         String configFiles = 
grailsConfigurationPaths.files.collect { it.canonicalPath }.join(',')
 
@@ -182,6 +223,15 @@ abstract class GroovyPageForkCompileTask extends 
AbstractCompile {
         // no-op
     }
 
+    /** Empties the destination, so that it holds exactly what this execution 
compiles; see the class comment. */
+    private void emptyDestination() {
+        File destination = destinationDirectory.get().asFile
+        if (destination.exists() && !destination.deleteDir()) {
+            throw new GradleException("Could not empty ${destination} before 
compiling the pages into it")
+        }
+        destination.mkdirs()
+    }
+
     @Input
     protected String getCompilerName() {
         'org.grails.web.pages.GroovyPageForkedCompiler'
diff --git 
a/grails-gradle/plugins/src/test/groovy/grails/plugin/json/view/JsonViewCompiler.java
 
b/grails-gradle/plugins/src/test/groovy/grails/plugin/json/view/JsonViewCompiler.java
new file mode 100644
index 0000000000..39974b2cbc
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/groovy/grails/plugin/json/view/JsonViewCompiler.java
@@ -0,0 +1,58 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package grails.plugin.json.view;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.util.List;
+
+/**
+ * Stands in for grails-views-gson's forked view compiler, which the plugin's 
tests cannot depend
+ * on, and records what {@code GsonViewCompilerTask} starts it with - the 
directory of the views,
+ * the environment it is told to compile for and the one it would otherwise 
have inherited - to
+ * {@code compiler.txt} in the destination directory. Leaves that file alone 
where it is already
+ * there, as the real compiler leaves a page alone whose class is newer than 
its source, and appends
+ * what each run found to {@code runs.txt}.
+ */
+public final class JsonViewCompiler {
+
+    private JsonViewCompiler() {
+    }
+
+    public static void main(String[] args) throws IOException {
+        Path destination = Paths.get(args[1]);
+        Files.createDirectories(destination);
+        Path compiled = destination.resolve("compiler.txt");
+        String environment = System.getProperty("grails.env");
+        boolean keptEarlier = Files.exists(compiled);
+        if (!keptEarlier) {
+            Files.write(compiled, List.of(
+                    "source=" + args[0],
+                    "grailsEnvironment=" + environment,
+                    "inheritedEnvironment=" + System.getenv("GRAILS_ENV")), 
StandardCharsets.UTF_8);
+        }
+        Files.write(destination.resolve("runs.txt"),
+                List.of("grailsEnvironment=" + environment + " keptEarlier=" + 
keptEarlier),
+                StandardCharsets.UTF_8, StandardOpenOption.CREATE, 
StandardOpenOption.APPEND);
+    }
+}
diff --git 
a/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/AbstractViewCompileEnvironmentFunctionalSpec.groovy
 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/AbstractViewCompileEnvironmentFunctionalSpec.groovy
new file mode 100644
index 0000000000..a7c85164f2
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/AbstractViewCompileEnvironmentFunctionalSpec.groovy
@@ -0,0 +1,280 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.gradle.plugin.views
+
+import org.gradle.testkit.runner.BuildResult
+import org.gradle.testkit.runner.GradleRunner
+import org.gradle.testkit.runner.TaskOutcome
+
+import org.grails.gradle.plugin.core.GradleSpecification
+
+/**
+ * Covers the Grails environment a view compile task compiles for, for each 
kind of view compiler.
+ *
+ * <p>The forked compiler reads the application's configuration for one 
environment, so the
+ * environment is part of what the views are. The task states it rather than 
leaving the compiler
+ * to whatever it inherits, compiles from an empty destination so that nothing 
of an earlier build
+ * is left in it, and the build cache keeps views compiled for one environment 
away from a build for
+ * another. The compiler is a stand-in that records what it was started with, 
and keeps an output
+ * it finds, as the real page compiler keeps a page whose class is newer than 
its source.</p>
+ *
+ * @since 7.0.18
+ */
+abstract class AbstractViewCompileEnvironmentFunctionalSpec extends 
GradleSpecification {
+
+    private GradleRunner runner
+    private File checkout
+
+    /** The test project under {@code src/test/resources/test-projects} that 
applies the plugin. */
+    abstract String getProjectName()
+
+    /** The task of the plugin that compiles the views. */
+    abstract String getTaskName()
+
+    /** Where the task writes, relative to the project. */
+    abstract String getDestination()
+
+    /** The class resource of the stand-in compiler, which the project puts on 
the compiler's classpath. */
+    abstract String getStandIn()
+
+    /**
+     * Writes a view named {@code name} for the task to compile.
+     *
+     * @return the view
+     */
+    abstract File view(File checkout, String name)
+
+    void cleanup() {
+        runner?.withEnvironment(null)
+    }
+
+    def "views are compiled for production unless the build is told 
otherwise"() {
+        given:
+        projectWithViews()
+
+        when:
+        compileViews()
+
+        then:
+        compiled().grailsEnvironment == 'production'
+    }
+
+    def "the environment variable of the build selects the environment"() {
+        given:
+        projectWithViews()
+
+        when:
+        compileViews([GRAILS_ENV: 'development'])
+
+        then:
+        compiled().grailsEnvironment == 'development'
+    }
+
+    def "the system property given to Gradle outranks the variable, and a 
short name is expanded"() {
+        given:
+        projectWithViews()
+
+        when:
+        compileViews([GRAILS_ENV: 'development'], ['-Dgrails.env=prod'])
+
+        then: 'the compiler is told, not left to what it inherits'
+        compiled().grailsEnvironment == 'production'
+        compiled().inheritedEnvironment == 'development'
+    }
+
+    def "a blank system property leaves the choice to the variable, as the 
application does"() {
+        given:
+        projectWithViews()
+
+        when:
+        compileViews([GRAILS_ENV: 'development'], ['-Dgrails.env='])
+
+        then:
+        compiled().grailsEnvironment == 'development'
+    }
+
+    def "a build can state the environment on the task, by any name Grails 
accepts for it"() {
+        given:
+        projectWithViews()
+        configureTask("grailsEnvironment = ' Prod '")
+
+        when:
+        compileViews([GRAILS_ENV: 'development'])
+
+        then:
+        compiled().grailsEnvironment == 'production'
+    }
+
+    def "a blank environment stated on the task fails the build"() {
+        given:
+        projectWithViews()
+        configureTask("grailsEnvironment = ' '")
+
+        when:
+        BuildResult result = failToCompileViews([GRAILS_ENV: 'development'])
+
+        then:
+        result.output.contains("The grailsEnvironment of :${taskName} is 
blank")
+    }
+
+    def "an environment a build gave the compiler as a JVM argument is kept"() 
{
+        given:
+        projectWithViews()
+        configureTask("compileOptions.forkOptions.jvmArgs = 
['-Dgrails.env=uat']")
+
+        when:
+        compileViews([GRAILS_ENV: 'development'], ['-Dgrails.env=prod'])
+
+        then:
+        compiled().grailsEnvironment == 'uat'
+    }
+
+    def "an environment stated on the task outranks the one its JVM arguments 
give the compiler"() {
+        given:
+        projectWithViews()
+        configureTask("compileOptions.forkOptions.jvmArgs = 
['-Dgrails.env=uat']; grailsEnvironment = 'production'")
+
+        when:
+        compileViews()
+
+        then:
+        compiled().grailsEnvironment == 'production'
+    }
+
+    def "an environment change compiles every view again, from an empty 
destination"() {
+        given:
+        projectWithViews()
+        cached()
+
+        when: 'the environment changes between two builds with no clean in 
between'
+        compileViews([GRAILS_ENV: 'development'], ['--build-cache'])
+        BuildResult production = compileViews([GRAILS_ENV: 'production'], 
['--build-cache'])
+
+        then: 'the compiler finds nothing of the earlier build to keep'
+        production.task(":${taskName}").outcome == TaskOutcome.SUCCESS
+        lastRun().keptEarlier == 'false'
+        compiled().grailsEnvironment == 'production'
+
+        when: 'a clean build for production is restored from the cache'
+        executeTask('clean')
+        BuildResult restored = compileViews([GRAILS_ENV: 'production'], 
['--build-cache'])
+
+        then: 'it gets what production compiled, not what was left of 
development'
+        restored.task(":${taskName}").outcome == TaskOutcome.FROM_CACHE
+        compiled().grailsEnvironment == 'production'
+    }
+
+    def "a change to the views alone compiles from an empty destination as 
well"() {
+        given:
+        projectWithViews()
+        File other = view(checkout, 'other')
+        compileViews()
+
+        when: 'a view is edited'
+        other << '\n'
+        BuildResult edited = compileViews()
+
+        then:
+        edited.task(":${taskName}").outcome == TaskOutcome.SUCCESS
+        lastRun().keptEarlier == 'false'
+
+        when: 'a view is removed'
+        other.delete()
+        BuildResult removed = compileViews()
+
+        then:
+        removed.task(":${taskName}").outcome == TaskOutcome.SUCCESS
+        lastRun().keptEarlier == 'false'
+    }
+
+    def "views compiled for one environment are not restored into a build for 
another"() {
+        given:
+        projectWithViews()
+        cached()
+
+        when:
+        BuildResult development = compileViews([GRAILS_ENV: 'development'], 
['--build-cache'])
+        executeTask('clean')
+        BuildResult production = compileViews([GRAILS_ENV: 'production'], 
['--build-cache'])
+        executeTask('clean')
+        BuildResult developmentAgain = compileViews([GRAILS_ENV: 
'development'], ['--build-cache'])
+
+        then: 'each environment compiles its own views'
+        development.task(":${taskName}").outcome == TaskOutcome.SUCCESS
+        production.task(":${taskName}").outcome == TaskOutcome.SUCCESS
+
+        and: 'and gets them back'
+        developmentAgain.task(":${taskName}").outcome == TaskOutcome.FROM_CACHE
+        compiled().grailsEnvironment == 'development'
+    }
+
+    private void projectWithViews() {
+        runner = setupTestResourceProject(projectName)
+        checkout = runner.projectDir
+        File compiler = new File(checkout, "compiler/${standIn}")
+        compiler.parentFile.mkdirs()
+        compiler.bytes = getClass().classLoader.getResource(standIn).bytes
+        view(checkout, 'index')
+    }
+
+    /** Configures the compile task in the build script, with {@code 
configuration} as its body. */
+    private void configureTask(String configuration) {
+        new File(checkout, 'build.gradle') << "\ntasks.named('${taskName}') { 
${configuration} }\n"
+    }
+
+    /** Keeps the project's build cache in a directory of its own, so that 
only this test's builds fill it. */
+    private void cached() {
+        File cache = new File(checkout.parentFile, 
"${projectName}-build-cache")
+        new File(checkout, 'settings.gradle') << """
+            buildCache { local { directory = 
file('${cache.absolutePath.replace('\\', '/')}') } }
+        """
+    }
+
+    /** Compiles the views in a build whose environment carries {@code 
variables} and no {@code GRAILS_ENV} otherwise. */
+    private BuildResult compileViews(Map<String, String> variables = [:], 
List<String> arguments = []) {
+        environment(variables)
+        executeTask(taskName, arguments)
+    }
+
+    private BuildResult failToCompileViews(Map<String, String> variables = 
[:], List<String> arguments = []) {
+        environment(variables)
+        runner.withArguments([taskName, '--stacktrace'] + 
arguments).forwardOutput().buildAndFail()
+    }
+
+    private void environment(Map<String, String> variables) {
+        Map<String, String> environment = new HashMap<>(System.getenv())
+        environment.remove('GRAILS_ENV')
+        environment.putAll(variables)
+        runner.withEnvironment(environment)
+    }
+
+    /** What the compiler recorded when it wrote the output: the environment 
it was told, and the one it inherited. */
+    private Map<String, String> compiled() {
+        new File(checkout, 
"${destination}/compiler.txt").readLines().collectEntries { String line ->
+            line.split('=', 2) as List
+        }
+    }
+
+    /** What the compiler found on its last run: the environment it was told, 
and whether an earlier output was there to keep. */
+    private Map<String, String> lastRun() {
+        new File(checkout, 
"${destination}/runs.txt").readLines().last().split(' ').collectEntries { 
String pair ->
+            pair.split('=', 2) as List
+        }
+    }
+}
diff --git 
a/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironmentSpec.groovy
 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironmentSpec.groovy
new file mode 100644
index 0000000000..873e272711
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironmentSpec.groovy
@@ -0,0 +1,171 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.gradle.plugin.views
+
+import org.gradle.api.InvalidUserDataException
+import org.gradle.api.Project
+import org.gradle.api.provider.ProviderFactory
+import org.gradle.testfixtures.ProjectBuilder
+import spock.lang.IgnoreIf
+import spock.lang.Specification
+import spock.util.environment.RestoreSystemProperties
+
+/**
+ * Covers how {@link ViewCompileEnvironment} reads the environment a build 
runs with, and the one a
+ * task states. What reaches a forked compiler, and the variable, are covered 
by the functional specs
+ * of the compile tasks.
+ *
+ * @since 7.0.18
+ */
+class ViewCompileEnvironmentSpec extends Specification {
+
+    Project project = ProjectBuilder.builder().build()
+    ProviderFactory providers = project.providers
+
+    @RestoreSystemProperties
+    def "the system property given to the build decides, expanded to the 
environment it names"() {
+        given:
+        System.setProperty('grails.env', stated)
+
+        expect:
+        ViewCompileEnvironment.ofBuild(providers).get() == compiledFor
+
+        where:
+        stated       | compiledFor
+        'prod'       | 'production'
+        'dev'        | 'development'
+        'test'       | 'test'
+        'production' | 'production'
+        ' prod '     | 'production'
+        'UAT'        | 'UAT'
+    }
+
+    @IgnoreIf(value = { env.GRAILS_ENV }, reason = 'the variable stands in for 
the missing property')
+    @RestoreSystemProperties
+    def "production where the build states nothing"() {
+        given:
+        System.clearProperty('grails.env')
+
+        expect:
+        ViewCompileEnvironment.ofBuild(providers).get() == 'production'
+    }
+
+    def "a blank name leaves the choice to the next, as the application's own 
resolution does"() {
+        expect:
+        ViewCompileEnvironment.resolve(providers.provider { stated }, 
providers.provider { inherited }).get() == compiledFor
+
+        where:
+        stated | inherited     | compiledFor
+        null   | null          | 'production'
+        ''     | 'development' | 'development'
+        ' '    | 'dev'         | 'development'
+        'prod' | 'development' | 'production'
+        null   | 'UAT'         | 'UAT'
+        null   | ' '           | 'production'
+    }
+
+    @IgnoreIf(value = { env.GRAILS_ENV }, reason = 'the variable would stand 
in for the missing property')
+    @RestoreSystemProperties
+    def "a task defaults to the environment its fork options give the 
compiler, else to the build's"() {
+        given:
+        System.clearProperty('grails.env')
+        ViewCompileOptions options = 
project.objects.newInstance(ViewCompileOptions)
+        options.forkOptions.jvmArgs = jvmArgs
+
+        expect:
+        ViewCompileEnvironment.defaultFor(providers, options).get() == 
compiledFor
+
+        where:
+        jvmArgs                       | compiledFor
+        null                          | 'production'
+        ['-Xmx1g']                    | 'production'
+        ['-Dgrails.env=uat']          | 'uat'
+        ['-Dgrails.env=dev']          | 'development'
+    }
+
+    def "the last grails.env among the compiler's JVM arguments is the one it 
would have read"() {
+        expect:
+        ViewCompileEnvironment.statedIn(jvmArgs) == stated
+
+        where:
+        jvmArgs                                   | stated
+        null                                      | null
+        []                                        | null
+        ['-Xmx1g']                                | null
+        ['-Dgrails.env=uat']                      | 'uat'
+        ['-Dgrails.env=prod']                     | 'production'
+        ['-Dgrails.env=dev', '-Dgrails.env=prod'] | 'production'
+        ['-Dgrails.env=']                         | null
+        ['-Dgrails.environment=prod']             | null
+    }
+
+    def "the compiler is started without the argument the task states for 
it"() {
+        expect:
+        ViewCompileEnvironment.withoutStated(jvmArgs) == started
+
+        where:
+        jvmArgs                                      | started
+        null                                         | []
+        []                                           | []
+        ['-Xmx1g']                                   | ['-Xmx1g']
+        ['-Xmx1g', '-Dgrails.env=uat', '-Dfoo=bar']  | ['-Xmx1g', '-Dfoo=bar']
+        ['-Dgrails.env=dev', '-Dgrails.env=prod']    | []
+    }
+
+    def "a task states its environment to the compiler by the full name"() {
+        expect:
+        ViewCompileEnvironment.forCompiler(providers.provider { stated }, 
':compileGroovyPages') == compiledFor
+
+        where:
+        stated   | compiledFor
+        'prod'   | 'production'
+        ' Prod ' | 'production'
+        'uat'    | 'uat'
+    }
+
+    def "a task whose environment is blank fails, naming the task"() {
+        when:
+        ViewCompileEnvironment.forCompiler(providers.provider { stated }, 
':compileGroovyPages')
+
+        then:
+        InvalidUserDataException failure = thrown()
+        failure.message.startsWith('The grailsEnvironment of 
:compileGroovyPages is blank')
+
+        where:
+        stated << [null, '', '  ']
+    }
+
+    def "a name resolves to the environment it is short for, and any other is 
kept as given"() {
+        expect:
+        ViewCompileEnvironment.canonicalName(name) == canonical
+
+        where:
+        name         | canonical
+        'prod'       | 'production'
+        'PROD'       | 'production'
+        'Production' | 'production'
+        'dev'        | 'development'
+        'test'       | 'test'
+        'UAT'        | 'UAT'
+        'custom'     | 'custom'
+        ''           | null
+        '  '         | null
+        null         | null
+    }
+}
diff --git 
a/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageCompileEnvironmentFunctionalSpec.groovy
 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageCompileEnvironmentFunctionalSpec.groovy
new file mode 100644
index 0000000000..7a9cb26ae7
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageCompileEnvironmentFunctionalSpec.groovy
@@ -0,0 +1,58 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.gradle.plugin.views.gsp
+
+import 
org.grails.gradle.plugin.views.AbstractViewCompileEnvironmentFunctionalSpec
+
+/**
+ * Covers the environment {@link GroovyPageForkCompileTask} compiles pages for.
+ *
+ * @since 7.0.18
+ */
+class GroovyPageCompileEnvironmentFunctionalSpec extends 
AbstractViewCompileEnvironmentFunctionalSpec {
+
+    @Override
+    String getProjectName() {
+        'gsp-compile-environment'
+    }
+
+    @Override
+    String getTaskName() {
+        'compileGroovyPages'
+    }
+
+    @Override
+    String getDestination() {
+        'build/gsp-classes/main'
+    }
+
+    // the page compiler comes from grails-web-gsp, which this build cannot 
depend on
+    @Override
+    String getStandIn() {
+        'org/grails/web/pages/GroovyPageForkedCompiler.class'
+    }
+
+    @Override
+    File view(File checkout, String name) {
+        File page = new File(checkout, "grails-app/views/book/${name}.gsp")
+        page.parentFile.mkdirs()
+        page.text = '${book.title}'
+        page
+    }
+}
diff --git 
a/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/json/GsonViewCompileEnvironmentFunctionalSpec.groovy
 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/json/GsonViewCompileEnvironmentFunctionalSpec.groovy
new file mode 100644
index 0000000000..90eaa424ef
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/json/GsonViewCompileEnvironmentFunctionalSpec.groovy
@@ -0,0 +1,60 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.gradle.plugin.views.json
+
+import 
org.grails.gradle.plugin.views.AbstractViewCompileEnvironmentFunctionalSpec
+
+/**
+ * Covers the environment {@link GsonViewCompilerTask} compiles JSON views 
for: the view compiler
+ * reads the application's configuration for one environment too, from the 
same kind of forked task
+ * as the page compiler.
+ *
+ * @since 7.0.18
+ */
+class GsonViewCompileEnvironmentFunctionalSpec extends 
AbstractViewCompileEnvironmentFunctionalSpec {
+
+    @Override
+    String getProjectName() {
+        'gson-compile-environment'
+    }
+
+    @Override
+    String getTaskName() {
+        'compileGsonViews'
+    }
+
+    @Override
+    String getDestination() {
+        'build/gson-classes/main'
+    }
+
+    // the view compiler comes from grails-views-gson, which this build cannot 
depend on
+    @Override
+    String getStandIn() {
+        'grails/plugin/json/view/JsonViewCompiler.class'
+    }
+
+    @Override
+    File view(File checkout, String name) {
+        File view = new File(checkout, "grails-app/views/book/${name}.gson")
+        view.parentFile.mkdirs()
+        view.text = 'json { title book.title }'
+        view
+    }
+}
diff --git 
a/grails-gradle/plugins/src/test/groovy/org/grails/web/pages/GroovyPageForkedCompiler.java
 
b/grails-gradle/plugins/src/test/groovy/org/grails/web/pages/GroovyPageForkedCompiler.java
new file mode 100644
index 0000000000..3a8c7e28f8
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/groovy/org/grails/web/pages/GroovyPageForkedCompiler.java
@@ -0,0 +1,58 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.web.pages;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.util.List;
+
+/**
+ * Stands in for grails-web-gsp's forked page compiler, which the plugin's 
tests cannot depend on,
+ * and records what {@code GroovyPageForkCompileTask} starts it with - the 
directory of the pages,
+ * the environment it is told to compile for and the one it would otherwise 
have inherited - to
+ * {@code compiler.txt} in the destination directory. Leaves that file alone 
where it is already
+ * there, as the real compiler leaves a page alone whose class is newer than 
its source, and appends
+ * what each run found to {@code runs.txt}.
+ */
+public final class GroovyPageForkedCompiler {
+
+    private GroovyPageForkedCompiler() {
+    }
+
+    public static void main(String[] args) throws IOException {
+        Path destination = Paths.get(args[1]);
+        Files.createDirectories(destination);
+        Path compiled = destination.resolve("compiler.txt");
+        String environment = System.getProperty("grails.env");
+        boolean keptEarlier = Files.exists(compiled);
+        if (!keptEarlier) {
+            Files.write(compiled, List.of(
+                    "source=" + args[0],
+                    "grailsEnvironment=" + environment,
+                    "inheritedEnvironment=" + System.getenv("GRAILS_ENV")), 
StandardCharsets.UTF_8);
+        }
+        Files.write(destination.resolve("runs.txt"),
+                List.of("grailsEnvironment=" + environment + " keptEarlier=" + 
keptEarlier),
+                StandardCharsets.UTF_8, StandardOpenOption.CREATE, 
StandardOpenOption.APPEND);
+    }
+}
diff --git 
a/grails-gradle/plugins/src/test/resources/test-projects/gson-compile-environment/build.gradle
 
b/grails-gradle/plugins/src/test/resources/test-projects/gson-compile-environment/build.gradle
new file mode 100644
index 0000000000..1831da512d
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/resources/test-projects/gson-compile-environment/build.gradle
@@ -0,0 +1,12 @@
+// A project whose JSON views are compiled by a stand-in for the view 
compiler, which the test puts
+// in the compiler directory, so that what the compile task starts the 
compiler with can be read back.
+// Spring Boot is applied because the views plugin wires its task to Boot's 
main class resolution.
+plugins {
+    id 'groovy'
+    id 'org.springframework.boot'
+    id 'org.apache.grails.gradle.grails-gson'
+}
+
+dependencies {
+    implementation files('compiler')
+}
diff --git 
a/grails-gradle/plugins/src/test/resources/test-projects/gson-compile-environment/settings.gradle
 
b/grails-gradle/plugins/src/test/resources/test-projects/gson-compile-environment/settings.gradle
new file mode 100644
index 0000000000..fb481ece2b
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/resources/test-projects/gson-compile-environment/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'gson-compile-environment'
diff --git 
a/grails-gradle/plugins/src/test/resources/test-projects/gsp-compile-environment/build.gradle
 
b/grails-gradle/plugins/src/test/resources/test-projects/gsp-compile-environment/build.gradle
new file mode 100644
index 0000000000..303813c5d1
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/resources/test-projects/gsp-compile-environment/build.gradle
@@ -0,0 +1,16 @@
+// A project whose pages are compiled by a stand-in for the page compiler, 
which the test puts in
+// the compiler directory, so that what the compile task starts the compiler 
with can be read back.
+plugins {
+    id 'groovy'
+    id 'org.apache.grails.gradle.grails-gsp'
+}
+
+dependencies {
+    implementation files('compiler')
+}
+
+// the servlet API the plugin adds for the page compiler is of no use to the 
stand-in, and
+// resolving it would need a repository
+configurations.named('gspCompile') {
+    withDependencies { it.clear() }
+}
diff --git 
a/grails-gradle/plugins/src/test/resources/test-projects/gsp-compile-environment/settings.gradle
 
b/grails-gradle/plugins/src/test/resources/test-projects/gsp-compile-environment/settings.gradle
new file mode 100644
index 0000000000..5b3aa19a51
--- /dev/null
+++ 
b/grails-gradle/plugins/src/test/resources/test-projects/gsp-compile-environment/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'gsp-compile-environment'

Reply via email to