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

jdaugherty pushed a commit to branch feat/forge-grails-composite
in repository https://gitbox.apache.org/repos/asf/grails-core.git

commit 50f0f7975ddfcfdcbf2ee2c751a11778c51c500a
Author: James Daugherty <[email protected]>
AuthorDate: Wed Oct 7 13:00:42 2026 -0400

    Let a GSP page write no line for its template logic
    
    GSP writes the text of a page exactly as it is written, the line breaks 
around its scriptlets,
    directives and comments included. That is harmless in HTML but not in text 
where every line counts,
    such as a source file or a build script. A page declaring 
trimLogicLines="true" now writes nothing for
    a line that holds only page directives, scriptlets and comments: neither 
its indentation nor its line
    break. A line holding text, an expression or a tag is written as it is.
    
    The line break of a removed line is moved inside the line's last construct 
rather than dropped, so the
    lines of the page keep their numbers in the compiled page and in the errors 
reported against it. Every
    page directive of a page is now read when a page is prescanned for the 
directives that change how it
    is parsed, so the directive may be declared in any of them; the first 
directive still wins.
---
 .../theWebLayer/gsp/GSPBasics/pageDirectives.adoc  |  25 +++
 .../org/grails/gsp/compiler/GroovyPageParser.java  |  20 ++-
 .../org/grails/gsp/compiler/LogicLineTrimmer.java  |  94 ++++++++++++
 .../org/grails/gsp/GspTrimLogicLinesSpec.groovy    | 167 +++++++++++++++++++++
 4 files changed, 304 insertions(+), 2 deletions(-)

diff --git 
a/grails-doc/src/en/guide/theWebLayer/gsp/GSPBasics/pageDirectives.adoc 
b/grails-doc/src/en/guide/theWebLayer/gsp/GSPBasics/pageDirectives.adoc
index 70a6ff6ed9..ca455e0e32 100644
--- a/grails-doc/src/en/guide/theWebLayer/gsp/GSPBasics/pageDirectives.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/gsp/GSPBasics/pageDirectives.adoc
@@ -44,3 +44,28 @@ GSP also supports the contentType directive:
 ----
 
 The contentType directive allows using GSP to render other formats.
+
+GSP writes the text of a page exactly as it is written, including the line 
breaks around scriptlets, directives and comments. That does not matter for 
HTML, but it does for text in which every line counts, such as a source file or 
a build script. The `trimLogicLines` directive makes a line holding only page 
directives, scriptlets (`<% %>` or `%{ }%`) and comments (`%{-- --}%` or `<%-- 
--%>`) write nothing, neither its indentation nor its line break:
+
+[,xml]
+----
+<%@ page trimLogicLines="true" expressionCodec="none" %>
+<%@ model="List<String> pluginIds" %>
+plugins {
+    <% for (String pluginId : pluginIds) { %>
+    id '${pluginId}'
+    <% } %>
+}
+----
+
+renders, with `pluginIds` holding `java` and `groovy`:
+
+[,groovy]
+----
+plugins {
+    id 'java'
+    id 'groovy'
+}
+----
+
+A line holding text, an expression (`${}` or `<%= %>`) or a tag besides the 
logic is written as it is. The lines of the page keep their numbers in the 
errors reported against it.
diff --git 
a/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/GroovyPageParser.java 
b/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/GroovyPageParser.java
index 4c8d46ebce..adb6823c53 100644
--- 
a/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/GroovyPageParser.java
+++ 
b/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/GroovyPageParser.java
@@ -220,6 +220,11 @@ public class GroovyPageParser implements Tokens {
     private static final String OUT_CODEC_DIRECTIVE = 
OutputEncodingSettings.OUT_CODEC_NAME + CODEC_DIRECTIVE_POSTFIX;
     private static final String TAGLIB_CODEC_DIRECTIVE = 
OutputEncodingSettings.TAGLIB_CODEC_NAME + CODEC_DIRECTIVE_POSTFIX;
     private static final String GRAILS_LAYOUT_PREPROCESS_DIRECTIVE = 
"grailsLayoutPreprocess";
+    /**
+     * The page directive by which a page asks that the lines holding only 
directives, scriptlets and
+     * comments write nothing, for a page rendering text in which every line 
break counts.
+     */
+    public static final String TRIM_LOGIC_LINES_DIRECTIVE = "trimLogicLines";
 
     private String pluginAnnotation;
     public static final String GROOVY_SOURCE_CHAR_ENCODING = "UTF-8";
@@ -320,6 +325,9 @@ public class GroovyPageParser implements Tokens {
         applyCompileStaticSystemProperty();
 
         Map<String, String> directives = parseDirectives(gspSource);
+        if 
(GrailsStringUtils.toBoolean(directives.get(TRIM_LOGIC_LINES_DIRECTIVE))) {
+            gspSource = LogicLineTrimmer.trim(gspSource);
+        }
         if 
(isGrailsLayoutPreprocessingEnabled(directives.get(GRAILS_LAYOUT_PREPROCESS_DIRECTIVE)))
 {
             // GSP preprocessing for direct grails layout integration: replace 
head -> g:captureHead, title -> g:captureTitle, meta -> g:captureMeta, body -> 
g:captureBody
             gspSource = 
grailsLayoutPreprocessor.addGspGrailsLayoutCapturing(gspSource);
@@ -423,13 +431,21 @@ public class GroovyPageParser implements Tokens {
         String input = 
PRESCAN_COMMENT_PATTERN.matcher(gspSource).replaceAll("");
         // find page directives
         Matcher m = PRESCAN_PAGE_DIRECTIVE_PATTERN.matcher(input);
-        if (m.find()) {
+        boolean first = true;
+        while (m.find()) {
             Matcher mat = PAGE_DIRECTIVE_PATTERN.matcher(m.group(1));
             while (mat.find()) {
                 String name = mat.group(1);
                 String value = mat.group(3);
-                result.put(name, value);
+                // the first page directive is read as it always was, a later 
one only adds what it
+                // names that the ones before it do not
+                if (first) {
+                    result.put(name, value);
+                } else {
+                    result.putIfAbsent(name, value);
+                }
             }
+            first = false;
         }
         return result;
     }
diff --git 
a/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/LogicLineTrimmer.java 
b/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/LogicLineTrimmer.java
new file mode 100644
index 0000000000..1f9275ed09
--- /dev/null
+++ 
b/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/LogicLineTrimmer.java
@@ -0,0 +1,94 @@
+/*
+ *  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.gsp.compiler;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Removes the lines of a page that hold only template logic, for a page 
declaring
+ * {@code trimLogicLines="true"}: a line holding nothing but page directives, 
scriptlets and comments,
+ * besides spaces and tabs, writes neither its indentation nor its line break. 
A line holding text, an
+ * expression or a tag is left as it is.
+ *
+ * <p>The line break of a removed line is moved inside the line's last 
construct, just after its
+ * opening delimiter, rather than dropped, so that every line of the page 
keeps its number in the
+ * compiled page and in the errors reported against it.</p>
+ */
+final class LogicLineTrimmer {
+
+    private static final String CONSTRUCT = "(?:" +
+            "<%--(?:(?!--%>).)*--%>" +          // <%-- comment --%>
+            "|%\\{--(?:(?!--\\}%).)*--\\}%" +   // %{-- comment --}%
+            "|<%@(?:(?!%>).)*%>" +              // <%@ directive %>
+            "|<%(?![=@]|--)(?:(?!%>).)*%>" +    // <% scriptlet %>
+            "|%\\{(?!--)(?:(?!\\}%).)*\\}%" +   // %{ scriptlet }%
+            ")";
+
+    private static final Pattern CONSTRUCT_PATTERN = 
Pattern.compile(CONSTRUCT, Pattern.DOTALL);
+
+    private static final Pattern LOGIC_LINE_PATTERN = Pattern.compile(
+            "^[ \\t]*(" + CONSTRUCT + "(?:[ \\t]*" + CONSTRUCT + ")*)[ 
\\t]*(\\r?\\n|\\z)",
+            Pattern.MULTILINE | Pattern.DOTALL);
+
+    private LogicLineTrimmer() {
+    }
+
+    static String trim(String gspSource) {
+        Matcher line = LOGIC_LINE_PATTERN.matcher(gspSource);
+        StringBuilder result = new StringBuilder(gspSource.length());
+        int copied = 0;
+        while (line.find()) {
+            result.append(gspSource, copied, line.start());
+            appendConstructs(result, line.group(1), line.group(2));
+            copied = line.end();
+        }
+        result.append(gspSource, copied, gspSource.length());
+        return result.toString();
+    }
+
+    /**
+     * Appends the constructs of a logic line without the spaces between them, 
the line break going
+     * just after the opening delimiter of the last one.
+     */
+    private static void appendConstructs(StringBuilder result, String 
constructs, String lineBreak) {
+        Matcher construct = CONSTRUCT_PATTERN.matcher(constructs);
+        String previous = null;
+        while (construct.find()) {
+            if (previous != null) {
+                result.append(previous);
+            }
+            previous = construct.group();
+        }
+        if (previous != null) {
+            int opening = openingDelimiterLength(previous);
+            result.append(previous, 0, 
opening).append(lineBreak).append(previous, opening, previous.length());
+        }
+    }
+
+    private static int openingDelimiterLength(String construct) {
+        if (construct.startsWith("<%--") || construct.startsWith("%{--")) {
+            return 4;
+        }
+        if (construct.startsWith("<%@")) {
+            return 3;
+        }
+        return 2;
+    }
+}
diff --git 
a/grails-gsp/core/src/test/groovy/org/grails/gsp/GspTrimLogicLinesSpec.groovy 
b/grails-gsp/core/src/test/groovy/org/grails/gsp/GspTrimLogicLinesSpec.groovy
new file mode 100644
index 0000000000..b7dabb1bba
--- /dev/null
+++ 
b/grails-gsp/core/src/test/groovy/org/grails/gsp/GspTrimLogicLinesSpec.groovy
@@ -0,0 +1,167 @@
+/*
+ *  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.gsp
+
+import spock.lang.Specification
+import spock.lang.Unroll
+
+class GspTrimLogicLinesSpec extends Specification {
+
+    GroovyPagesTemplateEngine engine
+
+    void setup() {
+        engine = new GroovyPagesTemplateEngine()
+        engine.afterPropertiesSet()
+    }
+
+    void "a line holding only a scriptlet writes nothing"() {
+        expect:
+        render('''<%@ page trimLogicLines="true" %>
+plugins {
+<% for (String id : ids) { %>
+    id '${id}'
+<% } %>
+}
+''', [ids: ['a', 'b']]) == '''plugins {
+    id 'a'
+    id 'b'
+}
+'''
+    }
+
+    void "the indentation of a line holding only logic is removed with it"() {
+        expect:
+        render('''<%@ page trimLogicLines="true" %>
+repositories {
+    <% if (central) { %>
+    mavenCentral()
+    <% } else { %>
+    mavenLocal()
+    <% } %>
+}
+''', [central: central]) == """repositories {
+    ${expected}
+}
+"""
+
+        where:
+        central | expected
+        true    | 'mavenCentral()'
+        false   | 'mavenLocal()'
+    }
+
+    void "a line holding text, an expression or an output scriptlet beside the 
logic is written as it is"() {
+        expect:
+        render('''<%@ page trimLogicLines="true" %>
+<% if (true) { %>text <% } %>
+<% if (true) { %>${'expression'}<% } %>
+<% if (true) { %><%= 'output' %><% } %>
+''', [:]) == '''text 
+expression
+output
+'''
+    }
+
+    void "directives, comments and several constructs on one line write 
nothing"() {
+        expect:
+        render('''%{--
+  A comment over several lines
+--}%
+<%@ page trimLogicLines="true" %>
+<%@ page import="java.time.DayOfWeek" %>
+<%-- a JSP comment --%>
+  <% String day = DayOfWeek.MONDAY.name() %> %{ day = day.toLowerCase() }%  
<%-- trailing --%>  
+${day}
+''', [:]) == 'monday\n'
+    }
+
+    @Unroll
+    void "a page ending with a logic line #description"() {
+        expect:
+        render('<%@ page trimLogicLines="true" %>\nline\n<% if (true) { %>' + 
ending, [:]) == 'line\n'
+
+        where:
+        description               | ending
+        'without a line break'    | '<% } %>'
+        'with a line break'       | '<% } %>\n'
+        'with Windows line breaks' | '<% } %>\r\n'
+    }
+
+    void "Windows line breaks are removed with the logic line"() {
+        expect:
+        render('<%@ page trimLogicLines="true" %>\r\n<% if (true) { 
%>\r\none\r\n<% } %>\r\ntwo\r\n', [:]) == 'one\r\ntwo\r\n'
+    }
+
+    void "the directive may be declared by a later page directive"() {
+        expect:
+        render('''<%@ page import="java.time.DayOfWeek" %>
+<%@ page trimLogicLines="true" %>
+<% if (true) { %>
+${DayOfWeek.FRIDAY}
+<% } %>
+''', [:]) == 'FRIDAY\n'
+    }
+
+    void "without the directive every line is written as it always was"() {
+        expect:
+        render('''<% if (true) { %>
+one
+<% } %>
+''', [:]) == '\none\n\n'
+    }
+
+    void "the lines of a page keep their numbers in the errors reported 
against them"() {
+        given:
+        String source = '''<%@ page trimLogicLines="true" %>
+<% if (true) { %>
+    <% if (true) { %>
+${'fine'}
+<% } %>
+<% } %>
+<% throw new IllegalStateException('line 7') %>
+'''
+
+        GroovyPageTemplate template = (GroovyPageTemplate) 
engine.createTemplate(source, 'lines_page')
+
+        when:
+        template.make([:]).writeTo(new StringWriter())
+
+        then:
+        IllegalStateException e = thrown()
+        StackTraceElement frame = e.stackTrace.find { StackTraceElement 
element -> element.className == 'lines_page' }
+        template.metaInfo.lineNumbers[frame.lineNumber - 1] == 7
+    }
+
+    void "a statically compiled page declaring its model trims its logic lines 
too"() {
+        expect:
+        render('''<%@ page trimLogicLines="true" %>
+<%@ model="List<String> names" %>
+<% for (String name : names) { %>
+- ${name.toUpperCase()}
+<% } %>
+''', [names: ['x', 'y']]) == '- X\n- Y\n'
+    }
+
+    private String render(String source, Map model) {
+        StringWriter out = new StringWriter()
+        engine.createTemplate(source, 
"trim${source.hashCode().abs()}").make(model).writeTo(out)
+        out.toString()
+    }
+}

Reply via email to