You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/04/21 11:01:58 UTC

(groovy) branch master updated (73149972f6 -> fd3fcd9c58)

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

paulk-asert pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git


    from 73149972f6 remove dup key
     new cb95d050c3 reuse Groovydoc plugin from Grails
     new fd3fcd9c58 minor tweaks for groovydoc

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../groovy/org.apache.groovy-doc-aggregator.gradle |   5 +
 .../groovy/org.apache.groovy-documented.gradle     |   9 +-
 .../groovy/gradle/GroovydocAntExtension.groovy     |  60 ++++++
 .../apache/groovy/gradle/GroovydocAntPlugin.groovy | 219 +++++++++++++++++++++
 .../groovy/tools/groovydoc/TagRenderer.java        |  77 +++++++-
 .../groovy/tools/groovydoc/GroovyDocToolTest.java  |  64 ++++++
 6 files changed, 430 insertions(+), 4 deletions(-)
 create mode 100644 build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntExtension.groovy
 create mode 100644 build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntPlugin.groovy


(groovy) 01/02: reuse Groovydoc plugin from Grails

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit cb95d050c3ba070008264096fb1b39f2771de121
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 20:38:11 2026 +1000

    reuse Groovydoc plugin from Grails
---
 .../groovy/org.apache.groovy-doc-aggregator.gradle |   5 +
 .../groovy/org.apache.groovy-documented.gradle     |   9 +-
 .../groovy/gradle/GroovydocAntExtension.groovy     |  60 ++++++
 .../apache/groovy/gradle/GroovydocAntPlugin.groovy | 219 +++++++++++++++++++++
 4 files changed, 292 insertions(+), 1 deletion(-)

diff --git a/build-logic/src/main/groovy/org.apache.groovy-doc-aggregator.gradle b/build-logic/src/main/groovy/org.apache.groovy-doc-aggregator.gradle
index d72ec835a4..5723d7d653 100644
--- a/build-logic/src/main/groovy/org.apache.groovy-doc-aggregator.gradle
+++ b/build-logic/src/main/groovy/org.apache.groovy-doc-aggregator.gradle
@@ -91,6 +91,11 @@ def groovydocAll = tasks.register("groovydocAll", Groovydoc) {
     includeAuthor = false
     processScripts = false
     includeMainForScripts = false
+    // GroovydocAntPlugin consumes this to produce the Ant task's sourcepath:
+    // configurations.allSources resolves to source directories (see
+    // sourcesForAggregation in groovy-core.gradle), so we pass the directories
+    // rather than the flattened file tree Gradle would otherwise infer.
+    ext.groovydocSourceDirs = configurations.allSources
 }
 
 def groovydocAllJar = tasks.register("groovydocAllJar", Jar) {
diff --git a/build-logic/src/main/groovy/org.apache.groovy-documented.gradle b/build-logic/src/main/groovy/org.apache.groovy-documented.gradle
index 789002e7e6..99a141be35 100644
--- a/build-logic/src/main/groovy/org.apache.groovy-documented.gradle
+++ b/build-logic/src/main/groovy/org.apache.groovy-documented.gradle
@@ -17,6 +17,14 @@
  *  under the License.
  */
 
+import org.apache.groovy.gradle.GroovydocAntPlugin
+
+pluginManager.apply(GroovydocAntPlugin)
+
+groovydocAnt {
+    syntaxHighlighter = 'prism'
+}
+
 configurations {
     /*
      * This setup is very specific to the Groovy project:
@@ -73,7 +81,6 @@ tasks.withType(Groovydoc).configureEach {
         source = sourceSets.main.groovy.srcDirs + sourceSets.main.java.srcDirs
     }
     groovyClasspath = configurations.groovydocClasspath
-    use = true
     windowTitle = "Groovy ${versions.groovy}"
     docTitle = "Groovy ${versions.groovy}"
     header = "Groovy ${versions.groovy}"
diff --git a/build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntExtension.groovy b/build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntExtension.groovy
new file mode 100644
index 0000000000..9253718984
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntExtension.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
+ *
+ *    http://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.apache.groovy.gradle
+
+import javax.inject.Inject
+
+import groovy.transform.CompileStatic
+
+import org.gradle.api.file.ConfigurableFileCollection
+import org.gradle.api.model.ObjectFactory
+import org.gradle.api.provider.Property
+
+/**
+ * Configures the {@link GroovydocAntPlugin}. Exposes Ant-task-only Groovydoc
+ * options that Gradle's built-in {@code Groovydoc} task type doesn't surface,
+ * plus a {@link #useAntBuilder} kill-switch for reverting to Gradle's native
+ * execution per project.
+ */
+@CompileStatic
+class GroovydocAntExtension {
+
+    final Property<Boolean> useAntBuilder
+    final Property<String> javaVersion
+    final Property<Boolean> showInternal
+    final Property<Boolean> noIndex
+    final Property<Boolean> noDeprecatedList
+    final Property<Boolean> noHelp
+    final Property<String> syntaxHighlighter
+    final Property<String> theme
+    final ConfigurableFileCollection additionalStylesheets
+
+    @Inject
+    GroovydocAntExtension(ObjectFactory objects) {
+        useAntBuilder = objects.property(Boolean).convention(true)
+        javaVersion = objects.property(String)
+        showInternal = objects.property(Boolean).convention(false)
+        noIndex = objects.property(Boolean).convention(false)
+        noDeprecatedList = objects.property(Boolean).convention(false)
+        noHelp = objects.property(Boolean).convention(false)
+        syntaxHighlighter = objects.property(String).convention('none')
+        theme = objects.property(String).convention('auto')
+        additionalStylesheets = objects.fileCollection()
+    }
+}
diff --git a/build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntPlugin.groovy b/build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntPlugin.groovy
new file mode 100644
index 0000000000..357456bb8b
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/groovy/gradle/GroovydocAntPlugin.groovy
@@ -0,0 +1,219 @@
+/*
+ *  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
+ *
+ *    http://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.apache.groovy.gradle
+
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.GradleException
+import org.gradle.api.Plugin
+import org.gradle.api.Project
+import org.gradle.api.file.FileCollection
+import org.gradle.api.provider.Provider
+import org.gradle.api.tasks.SourceSetContainer
+import org.gradle.api.tasks.javadoc.Groovydoc
+
+/**
+ * Replaces Gradle's built-in {@code Groovydoc} task execution with a direct
+ * {@code AntBuilder} invocation of Groovy's {@code org.codehaus.groovy.ant.Groovydoc}
+ * Ant task. This exposes properties not available on the Gradle task type:
+ * {@code javaVersion}, {@code showInternal}, {@code noIndex}, {@code noDeprecatedList},
+ * {@code noHelp}, {@code syntaxHighlighter}, {@code theme}, and additional stylesheets.
+ *
+ * <p>The Gradle task is retained as the configuration surface (source, classpath,
+ * titles, links, access, etc.). Only the execution action is swapped. Set
+ * {@code groovydocAnt.useAntBuilder = false} before task realization to revert
+ * to Gradle's native execution for the project.
+ *
+ * <p>For aggregator tasks whose source is a resolvable {@code Configuration}
+ * of source directories (not a {@code SourceSet}), set
+ * {@code task.ext.groovydocSourceDirs} to the {@code FileCollection} of
+ * directories to pass as {@code sourcepath}.
+ */
+@CompileStatic
+class GroovydocAntPlugin implements Plugin<Project> {
+
+    @Override
+    void apply(Project project) {
+        GroovydocAntExtension extension = project.extensions.create(
+                'groovydocAnt', GroovydocAntExtension)
+        configureJavaVersionDefault(project, extension)
+        configureGroovydocTasks(project, extension)
+    }
+
+    @CompileDynamic
+    private static void configureJavaVersionDefault(Project project, GroovydocAntExtension extension) {
+        def shared = project.extensions.findByName('sharedConfiguration')
+        if (shared != null && shared.hasProperty('targetJavaVersion')) {
+            extension.javaVersion.convention(
+                    shared.targetJavaVersion.map { "JAVA_${it}" as String }
+            )
+        }
+    }
+
+    @CompileDynamic
+    private static void configureGroovydocTasks(Project project, GroovydocAntExtension extension) {
+        project.tasks.withType(Groovydoc).configureEach { gdoc ->
+            gdoc.inputs.property('antJavaVersion', extension.javaVersion.orElse(''))
+            gdoc.inputs.property('antShowInternal', extension.showInternal)
+            gdoc.inputs.property('antNoIndex', extension.noIndex)
+            gdoc.inputs.property('antNoDeprecatedList', extension.noDeprecatedList)
+            gdoc.inputs.property('antNoHelp', extension.noHelp)
+            gdoc.inputs.property('antSyntaxHighlighter', extension.syntaxHighlighter)
+            gdoc.inputs.property('antTheme', extension.theme)
+            gdoc.inputs.files(extension.additionalStylesheets)
+                    .withPropertyName('antAdditionalStylesheets')
+                    .optional(true)
+
+            if (!extension.useAntBuilder.get()) {
+                return
+            }
+
+            gdoc.actions.clear()
+            gdoc.doLast {
+                executeGroovydoc(gdoc, extension, project)
+            }
+        }
+    }
+
+    @CompileDynamic
+    private static void executeGroovydoc(Groovydoc gdoc, GroovydocAntExtension extension, Project project) {
+        File destDir = resolveFile(gdoc.destinationDir)
+        destDir.mkdirs()
+
+        List<File> sourceDirs = resolveSourceDirectories(gdoc, project)
+        if (sourceDirs.isEmpty()) {
+            throw new GradleException(
+                    "Groovydoc task '${gdoc.name}': no source directories found. " +
+                    "Every published module must produce a groovydoc jar for Maven Central."
+            )
+        }
+
+        FileCollection classpath = gdoc.groovyClasspath
+        if (!classpath || classpath.empty) {
+            throw new GradleException(
+                    "Groovydoc task '${gdoc.name}': groovyClasspath is empty."
+            )
+        }
+
+        project.ant.taskdef(
+                name: 'groovydoc',
+                classname: 'org.codehaus.groovy.ant.Groovydoc',
+                classpath: classpath.asPath
+        )
+
+        Map<String, String> antArgs = [
+                destdir: destDir.absolutePath,
+                sourcepath: sourceDirs.collect { it.absolutePath }.join(File.pathSeparator),
+                packagenames: '**.*',
+                windowtitle: gdoc.windowTitle ?: '',
+                doctitle: gdoc.docTitle ?: '',
+                header: gdoc.header ?: '',
+                footer: gdoc.footer ?: '',
+                access: resolveAccess(gdoc),
+                author: String.valueOf(unwrap(gdoc.includeAuthor, false)),
+                noTimestamp: String.valueOf(unwrap(gdoc.noTimestamp, false)),
+                noVersionStamp: String.valueOf(unwrap(gdoc.noVersionStamp, false)),
+                processScripts: String.valueOf(unwrap(gdoc.processScripts, true)),
+                includeMainForScripts: String.valueOf(unwrap(gdoc.includeMainForScripts, true)),
+                showInternal: String.valueOf(extension.showInternal.get()),
+                noIndex: String.valueOf(extension.noIndex.get()),
+                noDeprecatedList: String.valueOf(extension.noDeprecatedList.get()),
+                noHelp: String.valueOf(extension.noHelp.get()),
+                syntaxHighlighter: extension.syntaxHighlighter.get(),
+                theme: extension.theme.get()
+        ]
+
+        String jv = extension.javaVersion.getOrNull()
+        if (jv) antArgs.put('javaVersion', jv)
+
+        def overviewText = gdoc.overviewText
+        if (overviewText != null) {
+            File overviewTmp = new File(
+                    project.layout.buildDirectory.get().asFile,
+                    "tmp/${gdoc.name}/overview.html"
+            )
+            overviewTmp.parentFile.mkdirs()
+            overviewTmp.text = overviewText.asString()
+            antArgs.put('overview', overviewTmp.absolutePath)
+        }
+
+        def links = gdoc.links ?: []
+        def extraStylesheets = extension.additionalStylesheets.files
+
+        project.ant.groovydoc(antArgs) {
+            links.each { l ->
+                link(packages: (l.packages ?: []).join(','), href: l.url ?: '')
+            }
+            extraStylesheets.each { f ->
+                addStylesheet(file: f.absolutePath)
+            }
+        }
+    }
+
+    @CompileDynamic
+    private static List<File> resolveSourceDirectories(Groovydoc gdoc, Project project) {
+        def override = gdoc.ext.has('groovydocSourceDirs') ? gdoc.ext.groovydocSourceDirs : null
+        if (override != null) {
+            Collection<File> files
+            if (override instanceof FileCollection) {
+                files = ((FileCollection) override).files
+            } else if (override instanceof Collection) {
+                files = (Collection<File>) override
+            } else {
+                files = project.files(override).files
+            }
+            return files.findAll { it.exists() }.unique() as List<File>
+        }
+
+        SourceSetContainer sourceSets = project.extensions.findByType(SourceSetContainer)
+        if (sourceSets != null) {
+            def main = sourceSets.findByName('main')
+            if (main != null) {
+                List<File> dirs = []
+                dirs.addAll(main.groovy.srcDirs.findAll { it.exists() })
+                dirs.addAll(main.java.srcDirs.findAll { it.exists() })
+                return dirs.unique()
+            }
+        }
+        []
+    }
+
+    @CompileDynamic
+    private static String resolveAccess(Groovydoc gdoc) {
+        def access = gdoc.access
+        if (access instanceof Provider) access = ((Provider) access).getOrNull()
+        if (access == null) return 'protected'
+        access.toString().toLowerCase()
+    }
+
+    @CompileDynamic
+    private static Object unwrap(Object value, Object defaultValue) {
+        if (value instanceof Provider) return ((Provider) value).getOrElse(defaultValue)
+        value == null ? defaultValue : value
+    }
+
+    @CompileDynamic
+    private static File resolveFile(Object value) {
+        if (value instanceof Provider) value = ((Provider) value).get()
+        if (value instanceof File) return value
+        if (value.hasProperty('asFile')) return value.asFile as File
+        new File(value.toString())
+    }
+}


(groovy) 02/02: minor tweaks for groovydoc

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit fd3fcd9c5874c2b6b037cd345f45a802d8d45930
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 21:01:47 2026 +1000

    minor tweaks for groovydoc
---
 .../groovy/tools/groovydoc/TagRenderer.java        | 77 +++++++++++++++++++++-
 .../groovy/tools/groovydoc/GroovyDocToolTest.java  | 64 ++++++++++++++++++
 2 files changed, 138 insertions(+), 3 deletions(-)

diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index ad9083f171..c288ec30af 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -33,6 +33,7 @@ import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
 import java.util.regex.Matcher;
@@ -371,7 +372,8 @@ final class TagRenderer {
             // GROOVY-5986's resource-copy pass).
             String fileName = attrs.get("file");
             if (fileName == null || fileName.isEmpty()) return 0;
-            String loaded = loadSnippetFile(fileName, rootDoc, classDoc);
+            boolean keepHeader = "true".equalsIgnoreCase(attrs.getOrDefault("keepHeader", ""));
+            String loaded = loadSnippetFile(fileName, rootDoc, classDoc, keepHeader);
             if (loaded == null) return 0;
             String region = attrs.get("region");
             if (region != null && !region.isEmpty()) {
@@ -385,6 +387,10 @@ final class TagRenderer {
         }
 
         String langClass = attrs.getOrDefault("lang", "");
+        if (langClass.isEmpty()) {
+            String inferSource = attrs.get("file");
+            if (inferSource != null) langClass = inferLangFromFilename(inferSource);
+        }
         String extraClass = attrs.getOrDefault("class", "");
         String combined = (langClass.isEmpty() ? "" : "language-" + langClass)
                 + (extraClass.isEmpty() ? "" : (langClass.isEmpty() ? extraClass : " " + extraClass));
@@ -408,7 +414,7 @@ final class TagRenderer {
      * {@code snippet-files/} directory under any configured sourcepath and
      * return its contents, or {@code null} if not found.
      */
-    private static String loadSnippetFile(String fileName, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
+    private static String loadSnippetFile(String fileName, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc, boolean keepHeader) {
         if (classDoc == null || !(rootDoc instanceof SimpleGroovyRootDoc)) return null;
         String[] sourcepaths = ((SimpleGroovyRootDoc) rootDoc).getSourcepaths();
         if (sourcepaths == null || sourcepaths.length == 0) return null;
@@ -421,7 +427,8 @@ final class TagRenderer {
             Path path = Paths.get(sourcepath, pkgPath, "snippet-files", fileName);
             if (Files.isRegularFile(path)) {
                 try {
-                    return Files.readString(path);
+                    String text = Files.readString(path);
+                    return keepHeader ? text : stripLicenseHeader(text);
                 } catch (IOException e) {
                     return null;
                 }
@@ -430,6 +437,70 @@ final class TagRenderer {
         return null;
     }
 
+    /**
+     * If the file begins with a C-style block comment whose content contains
+     * {@code "Licensed"} (i.e. the standard ASF header), strip that comment and
+     * any whitespace before the first line of real content. Conservative — only
+     * matches a leading {@code /* ... *}{@code /} whose text looks like a
+     * license.
+     */
+    private static String stripLicenseHeader(String text) {
+        int i = 0;
+        while (i < text.length() && Character.isWhitespace(text.charAt(i))) i++;
+        if (i + 1 >= text.length() || text.charAt(i) != '/' || text.charAt(i + 1) != '*') return text;
+        int close = text.indexOf("*/", i + 2);
+        if (close < 0) return text;
+        String comment = text.substring(i, close + 2);
+        if (!comment.contains("Licensed")) return text;
+        int after = close + 2;
+        while (after < text.length() && Character.isWhitespace(text.charAt(after))) after++;
+        return text.substring(after);
+    }
+
+    /**
+     * Map a snippet file's extension to a Prism language id for
+     * {@code <pre><code class="language-xxx">} output. Returns an empty string
+     * if the extension is unrecognised.
+     */
+    private static String inferLangFromFilename(String fileName) {
+        int dot = fileName.lastIndexOf('.');
+        if (dot < 0) return "";
+        String ext = fileName.substring(dot + 1).toLowerCase(Locale.ROOT);
+        switch (ext) {
+            case "groovy":
+            case "gvy":
+            case "gy":
+            case "gsh":
+                return "groovy";
+            case "java":
+                return "java";
+            case "json":
+                return "json";
+            case "sql":
+                return "sql";
+            case "xml":
+            case "html":
+            case "htm":
+                return "xml-doc";
+            case "md":
+            case "markdown":
+                return "markdown";
+            case "yaml":
+            case "yml":
+                return "yaml";
+            case "toml":
+                return "toml";
+            case "csv":
+                return "csv";
+            case "properties":
+                return "properties";
+            case "js":
+                return "javascript";
+            default:
+                return "";
+        }
+    }
+
     /**
      * GROOVY-11938 stage 2: extract a named region from a snippet file.
      * Regions are bounded by {@code // @start region=NAME} and
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index f9ca1804fd..caa48bc2fc 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -202,6 +202,70 @@ public class GroovyDocToolTest extends GroovyTestCase {
         // Example.groovy's content should appear:
         assertTrue("Expected snippet file content in:\n" + doc,
                 doc.contains("hello from Example"));
+        // ASF license header on Example.groovy should be stripped by default.
+        int snipStart = doc.indexOf("<pre><code class=\"language-groovy\">");
+        int snipEnd = doc.indexOf("</code></pre>", snipStart);
+        String snip = doc.substring(snipStart, snipEnd);
+        assertFalse("ASF header should be stripped from external snippet by default:\n" + snip,
+                snip.contains("Licensed to the Apache"));
+    }
+
+    // Auto-strip opt-out: {@snippet file="X" keepHeader=true} preserves the
+    // file content verbatim, and lang is inferred from the file's extension
+    // when no explicit lang= is given.
+    public void testSnippetTagExternalFormKeepHeaderAndInfersLang() throws Exception {
+        String pkg = "org/codehaus/groovy/tools/groovydoc/testfiles/docfiles";
+        Path tmp = Files.createTempDirectory("snippet-keepheader-");
+        Path pkgDir = tmp.resolve(pkg);
+        Files.createDirectories(pkgDir);
+        Files.writeString(pkgDir.resolve("KeepHeader.groovy"),
+                "package " + pkg.replace('/', '.') + "\n" +
+                "/**\n" +
+                " * {@snippet file=\"Example.groovy\" keepHeader=true}\n" +
+                " */\n" +
+                "class KeepHeader {}\n");
+        Path srcSnippetDir = Paths.get(
+                "src/test/resources/docfiles-fixture", pkg, "snippet-files");
+        Path dstSnippetDir = pkgDir.resolve("snippet-files");
+        Files.createDirectories(dstSnippetDir);
+        try (Stream<Path> s = Files.walk(srcSnippetDir)) {
+            s.filter(Files::isRegularFile).forEach(f -> {
+                try {
+                    Files.copy(f, dstSnippetDir.resolve(f.getFileName()),
+                            StandardCopyOption.REPLACE_EXISTING);
+                } catch (IOException e) { throw new RuntimeException(e); }
+            });
+        }
+        try {
+            GroovyDocTool tool = new GroovyDocTool(
+                    new FileSystemResourceManager("src/main/resources"),
+                    new String[]{tmp.toString()},
+                    GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES,
+                    GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES,
+                    GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES,
+                    new ArrayList<>(), null, new Properties()
+            );
+            tool.add(List.of(pkg + "/KeepHeader.groovy"));
+            MockOutputTool output = new MockOutputTool();
+            tool.renderToOutput(output, MOCK_DIR);
+
+            String doc = output.getText(MOCK_DIR + "/" + pkg + "/KeepHeader.html");
+            assertNotNull(doc);
+            // Lang inferred from .groovy extension even without explicit lang=.
+            assertTrue("Expected inferred language-groovy class in:\n" + doc,
+                    doc.contains("<pre><code class=\"language-groovy\">"));
+            // With keepHeader=true, ASF boilerplate is preserved.
+            int snipStart = doc.indexOf("<pre><code class=\"language-groovy\">");
+            int snipEnd = doc.indexOf("</code></pre>", snipStart);
+            String snip = doc.substring(snipStart, snipEnd);
+            assertTrue("keepHeader=true should preserve ASF header:\n" + snip,
+                    snip.contains("Licensed to the Apache"));
+        } finally {
+            try (Stream<Path> s = Files.walk(tmp)) {
+                s.sorted(Comparator.reverseOrder())
+                        .forEach(p -> { try { Files.delete(p); } catch (IOException ignore) {} });
+            }
+        }
     }
 
     // GROOVY-11938 stage 2: external snippet with region= selects a slice.