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

slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-shade-plugin.git

commit 98f3a0a9976e660b1857dd63370fec4fd17a96b6
Author: Vaclav Haisman <[email protected]>
AuthorDate: Wed Aug 26 20:31:59 2026 +0200

    [MSHADE-265] Allow overriding the shaded module name
---
 src/it/projects/module-info-merge/app/pom.xml      |  1 +
 src/it/projects/module-info-merge/verify.groovy    | 24 ++++---
 .../apache/maven/plugins/shade/DefaultShader.java  |  2 +-
 .../plugins/shade/ModuleInfoConfiguration.java     | 24 +++++++
 .../maven/plugins/shade/ModuleInfoProcessor.java   | 47 ++++++++----
 .../apache/maven/plugins/shade/mojo/ShadeMojo.java |  5 +-
 .../markdown/examples/module-info-merging.md.vm    | 29 ++++----
 .../maven/plugins/shade/DefaultShaderTest.java     | 14 ++--
 .../plugins/shade/ModuleInfoConfigurationTest.java | 83 +++++++++++++++++++++-
 9 files changed, 182 insertions(+), 47 deletions(-)

diff --git a/src/it/projects/module-info-merge/app/pom.xml 
b/src/it/projects/module-info-merge/app/pom.xml
index 24ad1ce1..9ef29860 100644
--- a/src/it/projects/module-info-merge/app/pom.xml
+++ b/src/it/projects/module-info-merge/app/pom.xml
@@ -55,6 +55,7 @@ under the License.
               <createDependencyReducedPom>false</createDependencyReducedPom>
               <moduleInfoMode>merge</moduleInfoMode>
               <moduleInfo>
+                <moduleName>shaded.app.module</moduleName>
                 <publicBoundary>merge</publicBoundary>
                 <additionalRequires>
                   <requirement>
diff --git a/src/it/projects/module-info-merge/verify.groovy 
b/src/it/projects/module-info-merge/verify.groovy
index f3b92085..0b97f62d 100644
--- a/src/it/projects/module-info-merge/verify.groovy
+++ b/src/it/projects/module-info-merge/verify.groovy
@@ -24,12 +24,14 @@ import java.util.jar.JarFile
 def shaded = new File( basedir, "app/target/app-1.0.jar" )
 assert shaded.isFile()
 
-def reference = ModuleFinder.of( shaded.toPath() ).find( "app.module" 
).orElseThrow {
-    new AssertionError( "The shaded JAR is not the app.module module" )
+def shadedFinder = ModuleFinder.of( shaded.toPath() )
+assert !shadedFinder.find( "app.module" ).isPresent()
+def reference = shadedFinder.find( "shaded.app.module" ).orElseThrow {
+    new AssertionError( "The shaded JAR is not the shaded.app.module module" )
 }
 def descriptor = reference.descriptor()
 
-assert descriptor.name() == "app.module"
+assert descriptor.name() == "shaded.app.module"
 assert descriptor.requires()*.name().contains( "external.module" )
 assert descriptor.requires()*.name().contains( "java.sql" )
 assert !descriptor.requires()*.name().contains( "automatic.module" )
@@ -62,20 +64,20 @@ assert external.isFile()
 
 def finder = ModuleFinder.of( shaded.toPath(), external.toPath() )
 def configuration = ModuleLayer.boot().configuration()
-        .resolve( finder, ModuleFinder.of(), [ "app.module" ] as Set )
+        .resolve( finder, ModuleFinder.of(), [ "shaded.app.module" ] as Set )
 def layer = ModuleLayer.boot().defineModulesWithOneLoader(
         configuration, ClassLoader.getSystemClassLoader() )
-def library = layer.findLoader( "app.module" ).loadClass( 
"shaded.library.Library" )
-assert library.module.name == "app.module"
+def library = layer.findLoader( "shaded.app.module" ).loadClass( 
"shaded.library.Library" )
+assert library.module.name == "shaded.app.module"
 def automaticLibrary =
-        Class.forName( "shaded.automatic.AutomaticLibrary", true, 
layer.findLoader( "app.module" ) )
-assert automaticLibrary.module.name == "app.module"
-def application = layer.findLoader( "app.module" ).loadClass( 
"app.api.Application" )
+        Class.forName( "shaded.automatic.AutomaticLibrary", true, 
layer.findLoader( "shaded.app.module" ) )
+assert automaticLibrary.module.name == "shaded.app.module"
+def application = layer.findLoader( "shaded.app.module" ).loadClass( 
"app.api.Application" )
 def thread = Thread.currentThread()
 def contextLoader = thread.contextClassLoader
 try
 {
-    thread.contextClassLoader = layer.findLoader( "app.module" )
+    thread.contextClassLoader = layer.findLoader( "shaded.app.module" )
     assert application.getMethod( "loadAutomaticService" ).invoke( null ) == 
"automatic"
 }
 finally
@@ -96,7 +98,7 @@ try
     assert jar.getJarEntry( "embedded/api/Library.class" ) == null
     assert jar.getJarEntry( "embedded/internal/Provider.class" ) == null
     assert jar.getJarEntry( "automatic/library/AutomaticLibrary.class" ) == 
null
-    assert jar.manifest.mainAttributes.getValue( "Automatic-Module-Name" ) == 
"app.module"
+    assert jar.manifest.mainAttributes.getValue( "Automatic-Module-Name" ) == 
"shaded.app.module"
     assert jar.manifest.mainAttributes.getValue( "Multi-Release" ) == "true"
 }
 finally
diff --git a/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java 
b/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java
index 122c1ea3..c7a8fb36 100644
--- a/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java
+++ b/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java
@@ -169,7 +169,7 @@ public class DefaultShader implements Shader {
                 if (manifestTransformer == null) {
                     manifestTransformer = new ManifestResourceTransformer();
                 }
-                forceAutomaticModuleName = 
moduleInfoProcessor.getPrimaryModuleName();
+                forceAutomaticModuleName = 
moduleInfoProcessor.getOutputModuleName();
             }
         }
 
diff --git 
a/src/main/java/org/apache/maven/plugins/shade/ModuleInfoConfiguration.java 
b/src/main/java/org/apache/maven/plugins/shade/ModuleInfoConfiguration.java
index 85b721de..5f7a7a76 100644
--- a/src/main/java/org/apache/maven/plugins/shade/ModuleInfoConfiguration.java
+++ b/src/main/java/org/apache/maven/plugins/shade/ModuleInfoConfiguration.java
@@ -18,6 +18,8 @@
  */
 package org.apache.maven.plugins.shade;
 
+import javax.lang.model.SourceVersion;
+
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -27,6 +29,8 @@ import java.util.Set;
  * Additional choices used while constructing the module descriptor for 
amalgamated shaded contents.
  */
 public class ModuleInfoConfiguration {
+    private String moduleName;
+
     private String publicBoundary = ModuleInfoPublicBoundary.PRIMARY.name();
 
     private Map<String, String> analysisJdkToolchain = Collections.emptyMap();
@@ -41,6 +45,26 @@ public class ModuleInfoConfiguration {
 
     private Set<String> dynamicUses = Collections.emptySet();
 
+    public String getModuleName() {
+        return moduleName;
+    }
+
+    public void setModuleName(String moduleName) {
+        this.moduleName = moduleName;
+    }
+
+    static boolean isValidModuleName(String moduleName) {
+        if (moduleName == null || !SourceVersion.isName(moduleName)) {
+            return false;
+        }
+        for (String identifier : moduleName.split("[.]", -1)) {
+            if ("_".equals(identifier)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
     public ModuleInfoPublicBoundary getPublicBoundary() {
         return ModuleInfoPublicBoundary.fromString(publicBoundary);
     }
diff --git 
a/src/main/java/org/apache/maven/plugins/shade/ModuleInfoProcessor.java 
b/src/main/java/org/apache/maven/plugins/shade/ModuleInfoProcessor.java
index 6860787a..5d274c01 100644
--- a/src/main/java/org/apache/maven/plugins/shade/ModuleInfoProcessor.java
+++ b/src/main/java/org/apache/maven/plugins/shade/ModuleInfoProcessor.java
@@ -112,6 +112,8 @@ final class ModuleInfoProcessor {
 
     private String primaryModuleName;
 
+    private String outputModuleName;
+
     private boolean multiReleaseOutput;
 
     private int modularFloor;
@@ -141,6 +143,7 @@ final class ModuleInfoProcessor {
             }
         }
         determinePrimaryModuleName();
+        determineOutputModuleName();
         multiReleaseOutput |= primaryRootDescriptorRequiresVersionedOutput();
     }
 
@@ -153,8 +156,8 @@ final class ModuleInfoProcessor {
         return SERVICE_CONFIGURATION.matcher(name).matches();
     }
 
-    String getPrimaryModuleName() {
-        return primaryModuleName;
+    String getOutputModuleName() {
+        return outputModuleName;
     }
 
     boolean hasPrimaryModule() {
@@ -287,7 +290,7 @@ final class ModuleInfoProcessor {
         validateConfiguredRequirements(candidates);
         SortedSet<String> allPackages = collectAllPackages(candidates);
         if (allPackages.contains("")) {
-            throw new MojoExecutionException("Cannot create module " + 
primaryModuleName
+            throw new MojoExecutionException("Cannot create module " + 
outputModuleName
                     + ": the shaded JAR contains a class in the unnamed 
package.");
         }
         for (MergedDescriptor descriptor : candidates) {
@@ -534,7 +537,7 @@ final class ModuleInfoProcessor {
     private MergedDescriptor mergeRelease(int release, DescriptorEntry 
primaryEntry) throws MojoExecutionException {
         ModuleDescriptorData primary = primaryEntry.descriptor;
         MergedDescriptor result = new MergedDescriptor(release, primaryEntry);
-        result.name = primary.name;
+        result.name = outputModuleName;
         result.access = primary.access;
         result.version = primary.version;
         result.classVersion = primary.classVersion;
@@ -552,6 +555,7 @@ final class ModuleInfoProcessor {
         }
         embeddedNames.remove(null);
         embeddedNames.add(primaryModuleName);
+        embeddedNames.add(outputModuleName);
 
         for (Export export : primary.exports.values()) {
             String packaze = relocatePackage(export.packaze);
@@ -746,7 +750,7 @@ final class ModuleInfoProcessor {
         if (!owners.isEmpty()) {
             target.uses.add(service);
             String owner = owners.first();
-            if (!"java.base".equals(owner) && 
!primaryModuleName.equals(owner)) {
+            if (!"java.base".equals(owner) && !isAmalgamatedModuleName(owner)) 
{
                 target.requires.merge(owner, new Require(owner, 0, null), 
Require::strongest);
             }
         }
@@ -966,7 +970,7 @@ final class ModuleInfoProcessor {
                             + toClassName(reference) + ", which is owned by 
multiple modules " + owners + '.');
                 }
                 String module = owners.first();
-                if ("java.base".equals(module) || 
primaryModuleName.equals(module)) {
+                if ("java.base".equals(module) || 
isAmalgamatedModuleName(module)) {
                     continue;
                 }
                 target.requires.merge(module, new Require(module, 0, null), 
Require::strongest);
@@ -1133,7 +1137,7 @@ final class ModuleInfoProcessor {
             for (String provider : provides.getValue()) {
                 int available = firstAvailableRelease(provider, candidates);
                 if (available < 0) {
-                    throw new MojoExecutionException("Cannot create module " + 
primaryModuleName + ": provider class "
+                    throw new MojoExecutionException("Cannot create module " + 
outputModuleName + ": provider class "
                             + provider + " is absent.");
                 }
                 if (available > earliestRelease) {
@@ -1149,7 +1153,7 @@ final class ModuleInfoProcessor {
             int available = firstAvailablePackageRelease(packaze, candidates);
             if (available < 0) {
                 throw new MojoExecutionException(
-                        "Cannot export package " + packaze + " from " + 
primaryModuleName + ": the package is absent.");
+                        "Cannot export package " + packaze + " from " + 
outputModuleName + ": the package is absent.");
             }
             if (available > earliestRelease) {
                 reasons.add(FloorReason.exportedPackage(packaze, available));
@@ -1160,7 +1164,7 @@ final class ModuleInfoProcessor {
             int available = firstAvailablePackageRelease(packaze, candidates);
             if (available < 0) {
                 throw new MojoExecutionException(
-                        "Cannot open package " + packaze + " from " + 
primaryModuleName + ": the package is absent.");
+                        "Cannot open package " + packaze + " from " + 
outputModuleName + ": the package is absent.");
             }
             if (available > earliestRelease) {
                 reasons.add(FloorReason.openPackage(packaze, available));
@@ -1190,7 +1194,7 @@ final class ModuleInfoProcessor {
             if (provider.getValue() < floor && 
!hasRootClass(provider.getKey().provider)) {
                 throw new MojoExecutionException("Provider " + 
provider.getKey().provider + " for "
                         + provider.getKey().service + " first available in 
Java " + provider.getValue()
-                        + " cannot be exposed while " + primaryModuleName + " 
is automatic below its Java " + floor
+                        + " cannot be exposed while " + outputModuleName + " 
is automatic below its Java " + floor
                         + " modular floor: META-INF/services cannot be 
versioned.");
             }
         }
@@ -1235,10 +1239,10 @@ final class ModuleInfoProcessor {
         if (modularFloor <= earliestRelease) {
             return;
         }
-        logger.warn("Raising the module descriptor floor for " + 
primaryModuleName + " from Java " + earliestRelease
+        logger.warn("Raising the module descriptor floor for " + 
outputModuleName + " from Java " + earliestRelease
                 + " to Java " + modularFloor + '.');
         logger.warn("No explicit module descriptor will be effective on Java " 
+ earliestRelease + " through "
-                + (modularFloor - 1) + "; the JAR will be the automatic module 
" + primaryModuleName
+                + (modularFloor - 1) + "; the JAR will be the automatic module 
" + outputModuleName
                 + " on those releases.");
         logger.warn("Automatic-Module-Name has been set to keep the module 
name stable.");
         logger.warn("Reasons:");
@@ -1451,6 +1455,25 @@ final class ModuleInfoProcessor {
         }
     }
 
+    private void determineOutputModuleName() throws MojoExecutionException {
+        if (primaryModuleName == null) {
+            return;
+        }
+        String configuredModuleName = configuration.getModuleName();
+        if (configuredModuleName == null) {
+            outputModuleName = primaryModuleName;
+        } else if 
(!ModuleInfoConfiguration.isValidModuleName(configuredModuleName)) {
+            throw new MojoExecutionException(
+                    "Invalid moduleInfo.moduleName '" + configuredModuleName + 
"': expected a qualified Java name.");
+        } else {
+            outputModuleName = configuredModuleName;
+        }
+    }
+
+    private boolean isAmalgamatedModuleName(String moduleName) {
+        return primaryModuleName.equals(moduleName) || 
outputModuleName.equals(moduleName);
+    }
+
     private boolean primaryRootDescriptorRequiresVersionedOutput() {
         if (primaryArtifact == null) {
             return false;
diff --git a/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java 
b/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java
index 3000279f..f2a1e8a1 100644
--- a/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java
+++ b/src/main/java/org/apache/maven/plugins/shade/mojo/ShadeMojo.java
@@ -342,8 +342,9 @@ public class ShadeMojo extends AbstractMojo {
 
     /**
      * Controls how compiled Java module descriptors are handled. The {@code 
discard} mode preserves the historical
-     * behavior. The {@code merge} mode retains the primary artifact's module 
identity and public boundary while
-     * incorporating requirements and service declarations from embedded 
artifacts.
+     * behavior. The {@code merge} mode retains the primary artifact's module 
identity by default and its public
+     * boundary while incorporating requirements and service declarations from 
embedded artifacts. The output module
+     * name can be changed with {@code moduleInfo.moduleName}.
      *
      * @see <a 
href="https://maven.apache.org/plugins/maven-shade-plugin/examples/module-info-merging.html";>Merging
 Java
      * Module Descriptors</a>
diff --git a/src/site/markdown/examples/module-info-merging.md.vm 
b/src/site/markdown/examples/module-info-merging.md.vm
index dc462199..2530d0f9 100644
--- a/src/site/markdown/examples/module-info-merging.md.vm
+++ b/src/site/markdown/examples/module-info-merging.md.vm
@@ -27,7 +27,7 @@ under the License.
 # Merging Java Module Descriptors
 
 By default, the plugin discards every root and versioned `module-info.class` 
from the inputs. This preserves the
-historical behavior: an unmodified descriptor would describe the original 
artifact rather than the contents of the
+historical behavior: an unmodified descriptor describes the original artifact 
rather than the contents of the
 shaded JAR.
 
 Modular projects can opt into descriptor merging:
@@ -50,6 +50,7 @@ Modular projects can opt into descriptor merging:
             <configuration>
               <moduleInfoMode>merge</moduleInfoMode>
               <moduleInfo>
+                <moduleName>com.example.shaded.application</moduleName>
                 <publicBoundary>merge</publicBoundary>
                 <analysisJdkToolchain>
                   <version>21</version>
@@ -72,12 +73,14 @@ Modular projects can opt into descriptor merging:
 ```
 
 Merge mode models the shaded JAR as if the retained, relocated source files 
had been compiled together as one module.
-The primary artifact remains authoritative for the module name, version, main 
class, and, by default, the public
-boundary. Requirements on modules embedded in the shaded JAR are removed. The 
primary descriptor's external
-requirements keep their modifiers. An embedded descriptor's external `requires 
transitive` is changed to an ordinary
-requirement: embedding its implementation does not make its former API part of 
the primary module's API. Embedded
-`static` requirements remain static. Uses and providers are combined. Package 
and class names in all retained
-directives follow the configured relocations.
+The primary artifact supplies the default module name and remains 
authoritative for the version, main class, and, by
+default, the public boundary. `moduleInfo.moduleName` can replace the module 
name in every generated descriptor and in
+the `Automatic-Module-Name` manifest entry; when omitted, the primary module 
name is preserved. Requirements on
+modules embedded in the shaded JAR are removed. The primary descriptor's 
external requirements keep their modifiers.
+An embedded descriptor's external `requires transitive` is changed to an 
ordinary requirement: embedding its
+implementation does not make its former API part of the primary module's API. 
Embedded `static` requirements remain
+static. Uses and providers are combined. Package and class names in all 
retained directives follow the configured
+relocations. The configured module name is not relocated.
 
 `moduleInfo.publicBoundary` controls the public boundary:
 
@@ -174,12 +177,12 @@ valid.
 
 Raising the floor does not raise the bytecode level of ordinary classes. 
Instead, no explicit descriptor is effective
 before that release. On those earlier Java releases the output is an automatic 
module. The plugin writes
-`Automatic-Module-Name` using the primary module name so that the name stays 
stable, and writes a detailed warning
-containing the original and new floors plus every provider or boundary change 
that caused the change. Providers whose
-classes exist in the JAR root are also exposed through `META-INF/services` so 
service loading continues to work while
-the JAR is automatic. A provider that exists only in a versioned directory 
below the new floor cannot be bridged because
-`META-INF/services` cannot be versioned. The build fails with the provider and 
affected releases instead of silently
-dropping it.
+`Automatic-Module-Name` using the effective output module name so that the 
name stays stable, and writes a detailed
+warning containing the original and new floors plus every provider or boundary 
change that caused the change.
+Providers whose classes exist in the JAR root are also exposed through 
`META-INF/services` so service loading continues
+to work while the JAR is automatic. A provider that exists only in a versioned 
directory below the new floor cannot be
+bridged because `META-INF/services` cannot be versioned. The build fails with 
the provider and affected releases instead
+of silently dropping it.
 
 If the primary descriptor itself requires a later class-file release, it is 
likewise placed in that versioned release
 directory. This lets the same JAR remain an automatic module on earlier Java 
releases instead of failing while reading
diff --git 
a/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java 
b/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java
index 4ec60b6a..1283a51e 100644
--- a/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java
+++ b/src/test/java/org/apache/maven/plugins/shade/DefaultShaderTest.java
@@ -1233,6 +1233,9 @@ public class DefaultShaderTest {
                 new SimpleRelocator("app.versioned", "hidden.app.versioned", 
null, null),
                 new SimpleRelocator("dep", "hidden.dep", null, null)));
         request.setResourceTransformers(Collections.emptyList());
+        ModuleInfoConfiguration moduleInfo = new ModuleInfoConfiguration();
+        moduleInfo.setModuleName("shaded.app.module");
+        request.setModuleInfoConfiguration(moduleInfo);
         request.setUberJar(shadedFile);
 
         newShader().shade(request);
@@ -1240,19 +1243,20 @@ public class DefaultShaderTest {
         try (JarFile shadedJar = new JarFile(shadedFile)) {
             assertEquals("true", 
shadedJar.getManifest().getMainAttributes().getValue("Multi-Release"));
             assertEquals(
-                    "app.module", 
shadedJar.getManifest().getMainAttributes().getValue("Automatic-Module-Name"));
+                    "shaded.app.module",
+                    
shadedJar.getManifest().getMainAttributes().getValue("Automatic-Module-Name"));
             assertEquals(
                     Collections.singleton("java.base"),
-                    readModuleRequirements(shadedJar, "module-info.class", 
"app.module"));
+                    readModuleRequirements(shadedJar, "module-info.class", 
"shaded.app.module"));
             assertEquals(
                     new LinkedHashSet<>(Arrays.asList("java.base", 
"jdk.unsupported")),
-                    readModuleRequirements(shadedJar, 
"META-INF/versions/17/module-info.class", "app.module"));
+                    readModuleRequirements(shadedJar, 
"META-INF/versions/17/module-info.class", "shaded.app.module"));
             Set<String> expectedPackages =
                     new LinkedHashSet<>(Arrays.asList("app/api", 
"hidden/app/versioned", "hidden/dep/api"));
-            assertEquals(expectedPackages, readModulePackages(shadedJar, 
"module-info.class", "app.module"));
+            assertEquals(expectedPackages, readModulePackages(shadedJar, 
"module-info.class", "shaded.app.module"));
             assertEquals(
                     expectedPackages,
-                    readModulePackages(shadedJar, 
"META-INF/versions/17/module-info.class", "app.module"));
+                    readModulePackages(shadedJar, 
"META-INF/versions/17/module-info.class", "shaded.app.module"));
             
assertTrue(shadedJar.getJarEntry("META-INF/versions/17/hidden/app/versioned/Feature.class")
 != null);
             
assertTrue(shadedJar.getJarEntry("hidden/dep/api/Dependency.class") != null);
             
assertTrue(shadedJar.getJarEntry("META-INF/versions/17/app/versioned/Feature.class")
 == null);
diff --git 
a/src/test/java/org/apache/maven/plugins/shade/ModuleInfoConfigurationTest.java 
b/src/test/java/org/apache/maven/plugins/shade/ModuleInfoConfigurationTest.java
index 02f79a49..db6431e8 100644
--- 
a/src/test/java/org/apache/maven/plugins/shade/ModuleInfoConfigurationTest.java
+++ 
b/src/test/java/org/apache/maven/plugins/shade/ModuleInfoConfigurationTest.java
@@ -35,6 +35,7 @@ import java.util.jar.JarFile;
 import java.util.jar.JarOutputStream;
 import java.util.jar.Manifest;
 
+import org.apache.maven.plugin.MojoExecutionException;
 import org.apache.maven.plugins.shade.filter.Filter;
 import org.apache.maven.plugins.shade.relocation.SimpleRelocator;
 import org.junit.jupiter.api.Assumptions;
@@ -51,6 +52,7 @@ import org.slf4j.Logger;
 import static java.util.Objects.requireNonNull;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -59,6 +61,49 @@ public class ModuleInfoConfigurationTest {
     @TempDir
     File temporaryFolder;
 
+    @Test
+    public void overridesOutputModuleNameAndRemovesOriginalSelfRequirement() 
throws Exception {
+        File primary = primaryModule("dep.module");
+        File dependency = newFile("dependency.jar");
+        try (JarOutputStream output = new 
JarOutputStream(Files.newOutputStream(dependency.toPath()))) {
+            writeDescriptor(output, "dep.module", new String[] {"app.module"}, 
null);
+        }
+
+        ModuleInfoConfiguration configuration = new ModuleInfoConfiguration();
+        configuration.setModuleName("shaded.app.module");
+        File shadedFile = newFile("shaded.jar");
+        ShadeRequest request = moduleRequest(primary, shadedFile, dependency);
+        request.setModuleInfoConfiguration(configuration);
+
+        shade(request);
+
+        try (JarFile shadedJar = new JarFile(shadedFile)) {
+            assertEquals("shaded.app.module", readModuleName(shadedJar));
+            assertEquals(
+                    "shaded.app.module",
+                    
shadedJar.getManifest().getMainAttributes().getValue("Automatic-Module-Name"));
+            Set<String> requirements =
+                    readRequirementAccess(shadedJar, 
"shaded.app.module").keySet();
+            assertFalse(requirements.contains("app.module"));
+            assertFalse(requirements.contains("dep.module"));
+        }
+    }
+
+    @Test
+    public void rejectsInvalidOutputModuleNames() throws Exception {
+        File primary = primaryModule();
+        int index = 0;
+        for (String invalid : Arrays.asList("", "bad-name", "int.module", 
"_")) {
+            ModuleInfoConfiguration configuration = new 
ModuleInfoConfiguration();
+            configuration.setModuleName(invalid);
+            ShadeRequest request = moduleRequest(primary, newFile("invalid-" + 
index++ + ".jar"));
+            request.setModuleInfoConfiguration(configuration);
+
+            MojoExecutionException exception = 
assertThrows(MojoExecutionException.class, () -> shade(request));
+            assertTrue(exception.getMessage().contains("Invalid 
moduleInfo.moduleName '" + invalid + "'"));
+        }
+    }
+
     @Test
     public void mergesExplicitAndAutomaticModuleBoundariesWhenRequested() 
throws Exception {
         
Assumptions.assumeFalse(System.getProperty("java.specification.version").startsWith("1."));
@@ -513,8 +558,13 @@ public class ModuleInfoConfigurationTest {
     }
 
     private static Map<String, Integer> readRequirementAccess(JarFile jar) 
throws IOException {
+        return readRequirementAccess(jar, "app.module");
+    }
+
+    private static Map<String, Integer> readRequirementAccess(JarFile jar, 
String expectedModuleName)
+            throws IOException {
         Map<String, Integer> requirements = new HashMap<>();
-        readModule(jar, new ModuleVisitor(Opcodes.ASM9) {
+        readModule(jar, expectedModuleName, new ModuleVisitor(Opcodes.ASM9) {
             @Override
             public void visitRequire(String module, int access, String 
version) {
                 requirements.put(module, access);
@@ -524,10 +574,19 @@ public class ModuleInfoConfigurationTest {
     }
 
     private static void readModule(JarFile jar, ModuleVisitor visitor) throws 
IOException {
-        readModule(jar, visitor, null);
+        readModule(jar, "app.module", visitor, null);
     }
 
     private static void readModule(JarFile jar, ModuleVisitor visitor, int[] 
moduleAccess) throws IOException {
+        readModule(jar, "app.module", visitor, moduleAccess);
+    }
+
+    private static void readModule(JarFile jar, String expectedModuleName, 
ModuleVisitor visitor) throws IOException {
+        readModule(jar, expectedModuleName, visitor, null);
+    }
+
+    private static void readModule(JarFile jar, String expectedModuleName, 
ModuleVisitor visitor, int[] moduleAccess)
+            throws IOException {
         JarEntry entry = requireNonNull(jar.getJarEntry("module-info.class"), 
"module-info.class in " + jar.getName());
         try (InputStream input = jar.getInputStream(entry)) {
             new ClassReader(input)
@@ -535,7 +594,7 @@ public class ModuleInfoConfigurationTest {
                             new ClassVisitor(Opcodes.ASM9) {
                                 @Override
                                 public ModuleVisitor visitModule(String name, 
int access, String version) {
-                                    assertEquals("app.module", name);
+                                    assertEquals(expectedModuleName, name);
                                     if (moduleAccess != null) {
                                         moduleAccess[0] = access;
                                     }
@@ -546,6 +605,24 @@ public class ModuleInfoConfigurationTest {
         }
     }
 
+    private static String readModuleName(JarFile jar) throws IOException {
+        String[] moduleName = new String[1];
+        JarEntry entry = requireNonNull(jar.getJarEntry("module-info.class"), 
"module-info.class in " + jar.getName());
+        try (InputStream input = jar.getInputStream(entry)) {
+            new ClassReader(input)
+                    .accept(
+                            new ClassVisitor(Opcodes.ASM9) {
+                                @Override
+                                public ModuleVisitor visitModule(String name, 
int access, String version) {
+                                    moduleName[0] = name;
+                                    return null;
+                                }
+                            },
+                            0);
+        }
+        return moduleName[0];
+    }
+
     private enum Directive {
         EXPORT,
         OPEN

Reply via email to