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 21955e7a537552b1736743454db9479184ffdf63 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. 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, so a production build after a development one would keep development's pages and store them in the cache under production's key. The task now takes InputChanges, with the pages as its one incremental input: Gradle removes the earlier output before any execution that is not incremental - an environment, classpath or configuration change - and every page is compiled again, while an edit to a page alone is incremental and the compiler keeps the others. The source directory is internal rather than an input directory, since the pages are fingerprinted through the source and an incremental task validates its inputs before the no-source skip, where a project without src/main/webapp would fail. Fixes #16711 --- grails-doc/src/en/guide/conf/environments.adoc | 18 ++ .../views/AbstractGroovyTemplateCompileTask.groovy | 34 ++++ .../plugin/views/ViewCompileEnvironment.groovy | 105 ++++++++++ .../views/gsp/GroovyPageForkCompileTask.groovy | 65 +++++- .../grails/plugin/json/view/JsonViewCompiler.java | 58 ++++++ .../plugin/views/ViewCompileEnvironmentSpec.groovy | 119 +++++++++++ ...oovyPageCompileEnvironmentFunctionalSpec.groovy | 218 +++++++++++++++++++++ ...GsonViewCompileEnvironmentFunctionalSpec.groovy | 178 +++++++++++++++++ .../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 + 13 files changed, 879 insertions(+), 4 deletions(-) diff --git a/grails-doc/src/en/guide/conf/environments.adoc b/grails-doc/src/en/guide/conf/environments.adoc index 472d809c1c..0a486487c8 100644 --- a/grails-doc/src/en/guide/conf/environments.adoc +++ b/grails-doc/src/en/guide/conf/environments.adoc @@ -139,6 +139,24 @@ 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` task, JSON views by `compileGsonViews` and markup views by `compileGmlViews`. The compiler reads `application.yml` and `application.groovy` 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 environment it is run with, given as `-Dgrails.env` to Gradle or as the `GRAILS_E [...] + +[source,bash] +---- +./gradlew bootJar -Dgrails.env=UAT +---- + +A build can state the environment on a compile task instead: + +[source,groovy] +---- +tasks.named('compileGroovyPages') { + 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..3b9f480d95 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 @@ -19,6 +19,8 @@ package org.grails.gradle.plugin.views +import java.util.concurrent.Callable + import javax.inject.Inject import groovy.transform.CompileDynamic @@ -46,9 +48,16 @@ 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> + * * @author Graeme Rocher * @since 1.0 */ @@ -83,6 +92,27 @@ abstract class AbstractGroovyTemplateCompileTask extends AbstractCompile { @Input final SetProperty<String> projectPackageNames + /** + * The Grails environment the views are compiled for. + * + * <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 to the environment the build runs with - the {@code grails.env} system property + * given to Gradle, else {@code GRAILS_ENV} - and to {@code production} where neither is set, + * which is what the archive the views are packaged into is built for. A build that gave the + * compiler an environment itself, as a {@code -Dgrails.env} JVM argument among the fork options of + * {@link #getCompileOptions()}, keeps it: that argument is the default where it is present. Stated + * to the forked compiler as the {@code grails.env} system property, so that the environment it + * happens to inherit does not decide.</p> + * + * @since 7.0.18 + */ + @Input + final Property<String> grailsEnvironment + @PathSensitive(PathSensitivity.RELATIVE) @Override FileTree getSource() { @@ -100,6 +130,9 @@ 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( + project.providers.provider({ -> ViewCompileEnvironment.statedIn(compileOptions.forkOptions.jvmArgs) } as Callable<String>) + .orElse(ViewCompileEnvironment.ofBuild(project.providers))) grailsConfigurationPaths = objectFactory.fileCollection() grailsConfigurationPaths.from( //TODO: historically this only used .yml, should it explore all configuration paths? @@ -136,6 +169,7 @@ abstract class AbstractGroovyTemplateCompileTask extends AbstractCompile { } javaExecSpec.maxHeapSize = compileOptions.forkOptions.memoryMaximumSize javaExecSpec.minHeapSize = compileOptions.forkOptions.memoryInitialSize + javaExecSpec.systemProperty(Environment.KEY, grailsEnvironment.get()) String packageImports = projectPackageNames.get().join(',') ?: packageName.get() 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..fff68b8deb --- /dev/null +++ b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironment.groovy @@ -0,0 +1,105 @@ +/* + * 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 groovy.transform.CompileStatic + +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, and this is where the default comes from.</p> + * + * @since 7.0.18 + */ +@CompileStatic +final class ViewCompileEnvironment { + + private ViewCompileEnvironment() { + } + + /** + * 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. A short name such as {@code prod} resolves to the environment it names, and a name + * Grails does not know is kept as a custom environment. + * + * @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 build gave the compiler itself, as a {@code -Dgrails.env} JVM argument among + * the fork options of its compile task, which is how a build chose the environment before the + * task had an input for it. 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 prefix = "-D${Environment.KEY}=" + String argument = jvmArgs?.reverse()?.find { String arg -> arg.startsWith(prefix) } + argument == null ? null : canonicalName(argument.substring(prefix.length())) + } + + /** + * The full name of the environment {@code name} refers to, or {@code name} itself where Grails + * knows no environment by it; {@code null} where it is blank, so that a blank setting counts as + * none. + * + * @param name the name as stated, possibly a short one such as {@code prod} + * @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 + } + Environment.getEnvironment(trimmed)?.name ?: 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..e90175b667 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 @@ -21,6 +21,7 @@ package org.grails.gradle.plugin.views.gsp import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths +import java.util.concurrent.Callable import javax.inject.Inject @@ -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 @@ -49,7 +50,11 @@ import org.gradle.api.tasks.compile.AbstractCompile import org.gradle.process.ExecOperations import org.gradle.process.ExecResult import org.gradle.process.JavaExecSpec +import org.gradle.work.Incremental +import org.gradle.work.InputChanges +import grails.util.Environment +import org.grails.gradle.plugin.views.ViewCompileEnvironment import org.grails.gradle.plugin.views.ViewCompileOptions /** @@ -57,6 +62,19 @@ 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>Incremental in the pages alone. The compiler leaves a page alone whose class is newer than its + * source, which is right after an edit to another page and wrong after a change to anything else, + * since the environment, the classpath and the configuration change what every page compiles to. + * The pages are the one incremental input, so an execution after any other change is not + * incremental, and Gradle removes what the earlier execution compiled before it: every page is + * compiled again, and what the build cache keeps under the new key is what the new inputs + * produced.</p> + * * @author David Estes * @since 4.0 */ @@ -72,8 +90,13 @@ 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()}, the one incremental + * input, and it need not exist - a project without {@code src/main/webapp} has no webapp pages, + * and an input directory that does not exist fails validation. + */ + @Internal final DirectoryProperty srcDir @Nested @@ -86,6 +109,28 @@ abstract class GroovyPageForkCompileTask extends AbstractCompile { @Optional final Property<String> serverpath + /** + * The Grails environment the pages are compiled for. + * + * <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 to the environment the build runs with - the {@code grails.env} system property + * given to Gradle, else {@code GRAILS_ENV} - and to {@code production} where neither is set, + * which is what the archive the pages are packaged into is built for. A build that gave the + * compiler an environment itself, as a {@code -Dgrails.env} JVM argument among the fork options of + * {@link #getCompileOptions()}, keeps it: that argument is the default where it is present. Stated + * to the forked compiler as the {@code grails.env} system property, so that the environment it + * happens to inherit does not decide.</p> + * + * @since 7.0.18 + */ + @Input + final Property<String> grailsEnvironment + private ExecOperations execOperations @OutputDirectory @@ -98,6 +143,9 @@ abstract class GroovyPageForkCompileTask extends AbstractCompile { srcDir = objectFactory.directoryProperty() compileOptions = objectFactory.newInstance(ViewCompileOptions) serverpath = objectFactory.property(String) + grailsEnvironment = objectFactory.property(String).convention( + project.providers.provider({ -> ViewCompileEnvironment.statedIn(compileOptions.forkOptions.jvmArgs) } as Callable<String>) + .orElse(ViewCompileEnvironment.ofBuild(project.providers))) grailsConfigurationPaths = objectFactory.fileCollection() grailsConfigurationPaths.from( project.layout.projectDirectory.file('grails-app/conf/application.yml'), @@ -107,6 +155,7 @@ abstract class GroovyPageForkCompileTask extends AbstractCompile { } @Override + @Incremental @PathSensitive(PathSensitivity.RELATIVE) FileTree getSource() { return super.getSource() @@ -132,8 +181,15 @@ abstract class GroovyPageForkCompileTask extends AbstractCompile { super.setSource(source) } + /** + * Compiles the pages. Takes the changes, which it has no need to read, so that Gradle treats the + * task as incremental and removes the earlier output before an execution that is not; see the + * class comment. + * + * @param inputChanges the changes since the last execution + */ @TaskAction - void execute() { + void execute(InputChanges inputChanges) { compile() } @@ -152,6 +208,7 @@ abstract class GroovyPageForkCompileTask extends AbstractCompile { } javaExecSpec.setMaxHeapSize(compileOptions.forkOptions.memoryMaximumSize) javaExecSpec.setMinHeapSize(compileOptions.forkOptions.memoryInitialSize) + javaExecSpec.systemProperty(Environment.KEY, grailsEnvironment.get()) String configFiles = grailsConfigurationPaths.files.collect { it.canonicalPath }.join(',') 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/ViewCompileEnvironmentSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironmentSpec.groovy new file mode 100644 index 0000000000..c150b5b8cf --- /dev/null +++ b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/ViewCompileEnvironmentSpec.groovy @@ -0,0 +1,119 @@ +/* + * 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.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. 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 { + + ProviderFactory providers = ProjectBuilder.builder().build().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' + } + + @IgnoreIf(value = { env.GRAILS_ENV }, reason = 'the variable stands in for the blank property') + @RestoreSystemProperties + def "a blank property counts as none"() { + given: + System.setProperty('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' + } + + 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 "a name resolves to the environment it is short for"() { + expect: + ViewCompileEnvironment.canonicalName(name) == canonical + + where: + name | canonical + 'prod' | 'production' + 'dev' | 'development' + 'test' | 'test' + 'UAT' | 'UAT' + '' | 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..e77ac36b2b --- /dev/null +++ b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/gsp/GroovyPageCompileEnvironmentFunctionalSpec.groovy @@ -0,0 +1,218 @@ +/* + * 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.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 pages are compiled for. + * + * <p>The forked compiler reads the application's configuration for one environment, so the + * environment is part of what the pages are. The task states it rather than leaving the compiler + * to whatever it inherits, and the build cache keeps pages compiled for one environment away from + * a build for another.</p> + * + * @since 7.0.18 + */ +class GroovyPageCompileEnvironmentFunctionalSpec extends GradleSpecification { + + private GradleRunner runner + private File checkout + + void cleanup() { + runner?.withEnvironment(null) + } + + def "pages are compiled for production unless the build is told otherwise"() { + given: + projectWithPages() + + when: + compilePages() + + then: + compiled().grailsEnvironment == 'production' + } + + def "the environment variable of the build selects the environment"() { + given: + projectWithPages() + + when: + compilePages([GRAILS_ENV: 'development']) + + then: + compiled().grailsEnvironment == 'development' + } + + def "the system property given to Gradle outranks the variable, and a short name is expanded"() { + given: + projectWithPages() + + when: + compilePages([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: + projectWithPages() + + when: + compilePages([GRAILS_ENV: 'development'], ['-Dgrails.env=']) + + then: + compiled().grailsEnvironment == 'development' + } + + def "a build can state the environment on the task"() { + given: + projectWithPages() + new File(checkout, 'build.gradle') << ''' + tasks.named('compileGroovyPages') { grailsEnvironment = 'uat' } + ''' + + when: + compilePages([GRAILS_ENV: 'development']) + + then: + compiled().grailsEnvironment == 'uat' + } + + def "an environment a build gave the compiler as a JVM argument is kept"() { + given: + projectWithPages() + new File(checkout, 'build.gradle') << ''' + tasks.named('compileGroovyPages') { compileOptions.forkOptions.jvmArgs = ['-Dgrails.env=uat'] } + ''' + + when: + compilePages([GRAILS_ENV: 'development'], ['-Dgrails.env=prod']) + + then: + compiled().grailsEnvironment == 'uat' + } + + def "an environment change compiles every page again, even one whose class is newer than its source"() { + given: + projectWithPages() + cached() + + when: 'the environment changes between two builds with no clean in between' + compilePages([GRAILS_ENV: 'development'], ['--build-cache']) + BuildResult production = compilePages([GRAILS_ENV: 'production'], ['--build-cache']) + + then: 'the compiler finds nothing of the earlier build to keep' + production.task(':compileGroovyPages').outcome == TaskOutcome.SUCCESS + lastRun().keptEarlier == 'false' + compiled().grailsEnvironment == 'production' + + when: 'a clean build for production is restored from the cache' + executeTask('clean') + BuildResult restored = compilePages([GRAILS_ENV: 'production'], ['--build-cache']) + + then: 'it gets what production compiled, not what was left of development' + restored.task(':compileGroovyPages').outcome == TaskOutcome.FROM_CACHE + compiled().grailsEnvironment == 'production' + } + + def "an edit to a page alone leaves the classes of the others for the compiler to keep"() { + given: + projectWithPages() + compilePages() + + when: + new File(checkout, 'grails-app/views/book/index.gsp') << '\n${book.author}' + BuildResult edited = compilePages() + + then: + edited.task(':compileGroovyPages').outcome == TaskOutcome.SUCCESS + lastRun().keptEarlier == 'true' + } + + def "pages compiled for one environment are not restored into a build for another"() { + given: + projectWithPages() + cached() + + when: + BuildResult development = compilePages([GRAILS_ENV: 'development'], ['--build-cache']) + executeTask('clean') + BuildResult production = compilePages([GRAILS_ENV: 'production'], ['--build-cache']) + executeTask('clean') + BuildResult developmentAgain = compilePages([GRAILS_ENV: 'development'], ['--build-cache']) + + then: 'each environment compiles its own pages' + development.task(':compileGroovyPages').outcome == TaskOutcome.SUCCESS + production.task(':compileGroovyPages').outcome == TaskOutcome.SUCCESS + + and: 'and gets them back' + developmentAgain.task(':compileGroovyPages').outcome == TaskOutcome.FROM_CACHE + compiled().grailsEnvironment == 'development' + } + + private void projectWithPages() { + runner = setupTestResourceProject('gsp-compile-environment') + checkout = runner.projectDir + // the page compiler comes from grails-web-gsp, which this build cannot depend on + File standIn = new File(checkout, 'compiler/org/grails/web/pages/GroovyPageForkedCompiler.class') + standIn.parentFile.mkdirs() + standIn.bytes = getClass().classLoader.getResource('org/grails/web/pages/GroovyPageForkedCompiler.class').bytes + File page = new File(checkout, 'grails-app/views/book/index.gsp') + page.parentFile.mkdirs() + page.text = '${book.title}' + } + + /** Compiles the pages in a build whose environment carries {@code variables} and no {@code GRAILS_ENV} otherwise. */ + private BuildResult compilePages(Map<String, String> variables = [:], List<String> arguments = []) { + Map<String, String> environment = new HashMap<>(System.getenv()) + environment.remove('GRAILS_ENV') + environment.putAll(variables) + runner.withEnvironment(environment) + executeTask('compileGroovyPages', arguments) + } + + /** 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, 'gsp-build-cache') + new File(checkout, 'settings.gradle') << """ + buildCache { local { directory = file('${cache.absolutePath.replace('\\', '/')}') } } + """ + } + + private Map<String, String> compiled() { + new File(checkout, 'build/gsp-classes/main/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, 'build/gsp-classes/main/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/json/GsonViewCompileEnvironmentFunctionalSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/json/GsonViewCompileEnvironmentFunctionalSpec.groovy new file mode 100644 index 0000000000..fbb2d61f51 --- /dev/null +++ b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/views/json/GsonViewCompileEnvironmentFunctionalSpec.groovy @@ -0,0 +1,178 @@ +/* + * 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.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 JSON views are compiled for, as + * {@code GroovyPageCompileEnvironmentFunctionalSpec} does for pages: the view compiler reads the + * application's configuration for one environment too, from the same kind of forked task. + * + * @since 7.0.18 + */ +class GsonViewCompileEnvironmentFunctionalSpec extends GradleSpecification { + + private GradleRunner runner + private File checkout + + 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 of the build selects the environment, and the compiler is told"() { + given: + projectWithViews() + + when: + compileViews([GRAILS_ENV: 'development'], ['-Dgrails.env=test']) + + then: + compiled().grailsEnvironment == 'test' + compiled().inheritedEnvironment == 'development' + } + + def "a build can state the environment on the task"() { + given: + projectWithViews() + new File(checkout, 'build.gradle') << ''' + tasks.named('compileGsonViews') { grailsEnvironment = 'uat' } + ''' + + when: + compileViews([GRAILS_ENV: 'development']) + + then: + compiled().grailsEnvironment == 'uat' + } + + def "an environment a build gave the compiler as a JVM argument is kept"() { + given: + projectWithViews() + new File(checkout, 'build.gradle') << ''' + tasks.named('compileGsonViews') { compileOptions.forkOptions.jvmArgs = ['-Dgrails.env=uat'] } + ''' + + when: + compileViews([GRAILS_ENV: 'development'], ['-Dgrails.env=prod']) + + then: + compiled().grailsEnvironment == 'uat' + } + + 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: + production.task(':compileGsonViews').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: + restored.task(':compileGsonViews').outcome == TaskOutcome.FROM_CACHE + compiled().grailsEnvironment == 'production' + } + + 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: + development.task(':compileGsonViews').outcome == TaskOutcome.SUCCESS + production.task(':compileGsonViews').outcome == TaskOutcome.SUCCESS + developmentAgain.task(':compileGsonViews').outcome == TaskOutcome.FROM_CACHE + compiled().grailsEnvironment == 'development' + } + + private void projectWithViews() { + runner = setupTestResourceProject('gson-compile-environment') + checkout = runner.projectDir + // the view compiler comes from grails-views-gson, which this build cannot depend on + File standIn = new File(checkout, 'compiler/grails/plugin/json/view/JsonViewCompiler.class') + standIn.parentFile.mkdirs() + standIn.bytes = getClass().classLoader.getResource('grails/plugin/json/view/JsonViewCompiler.class').bytes + // the views plugin insists on the directory of the views when it is applied + File view = new File(checkout, 'grails-app/views/book/index.gson') + view.parentFile.mkdirs() + view.text = 'json { title book.title }' + } + + /** 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 = []) { + Map<String, String> environment = new HashMap<>(System.getenv()) + environment.remove('GRAILS_ENV') + environment.putAll(variables) + runner.withEnvironment(environment) + executeTask('compileGsonViews', arguments) + } + + /** 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, 'gson-build-cache') + new File(checkout, 'settings.gradle') << """ + buildCache { local { directory = file('${cache.absolutePath.replace('\\', '/')}') } } + """ + } + + private Map<String, String> compiled() { + new File(checkout, 'build/gson-classes/main/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, 'build/gson-classes/main/runs.txt').readLines().last().split(' ').collectEntries { String pair -> + pair.split('=', 2) as List + } + } +} 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'
