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


The following commit(s) were added to refs/heads/master by this push:
     new 5ebfb4d  Fix shaded artifact placement when outputDirectory is 
customized
5ebfb4d is described below

commit 5ebfb4dbcddf1e4a6932e6f510d45e98929d9d90
Author: Arturo Bernal <[email protected]>
AuthorDate: Thu Oct 29 11:50:53 2026 +0100

    Fix shaded artifact placement when outputDirectory is customized
    
    When outputDirectory is set to something other than the default build
    directory and finalName is left at its default, ShadeMojo replaced the
    project's main artifact in place at its original (default) location
    instead of the configured outputDirectory. This left the shaded jar in
    target/ while only the pre-shade backup ended up under outputDirectory.
    
    Route the main artifact replacement through a helper that places the
    shaded jar in outputDirectory, matching how the sources/test/test-sources
    artifacts already behave, and update the project artifact's file so
    downstream plugins pick up the right jar.
    
    Claude-Session: https://claude.ai/code/session_0153qyh22xBMN1vPfWGz3jSH
---
 src/it/projects/MSHADE-354/pom.xml                 | 56 +++++++++++++++++
 .../org/apache/maven/its/shade/mshade354/App.java  | 25 ++++++++
 src/it/projects/MSHADE-354/verify.groovy           | 48 +++++++++++++++
 .../apache/maven/plugins/shade/mojo/ShadeMojo.java | 43 ++++++++++---
 .../maven/plugins/shade/mojo/ShadeMojoTest.java    | 72 ++++++++++++++++++++++
 5 files changed, 235 insertions(+), 9 deletions(-)

diff --git a/src/it/projects/MSHADE-354/pom.xml 
b/src/it/projects/MSHADE-354/pom.xml
new file mode 100644
index 0000000..ffa7555
--- /dev/null
+++ b/src/it/projects/MSHADE-354/pom.xml
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its.shade.mshade354</groupId>
+  <artifactId>mshade354</artifactId>
+  <version>1.0</version>
+  <packaging>jar</packaging>
+
+  <name>MSHADE-354</name>
+  <description>
+    Test that the shaded artifact lands in a custom outputDirectory, and the 
pre-shade artifact
+    is preserved alongside it as original-mshade354-1.0.jar, instead of the 
shaded jar being left
+    behind in the default build directory 
(https://github.com/apache/maven-shade-plugin/issues/354).
+  </description>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-shade-plugin</artifactId>
+        <version>@project.version@</version>
+        <executions>
+          <execution>
+            <phase>package</phase>
+            <goals>
+              <goal>shade</goal>
+            </goals>
+            <configuration>
+              
<outputDirectory>${project.build.directory}/custom</outputDirectory>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git 
a/src/it/projects/MSHADE-354/src/main/java/org/apache/maven/its/shade/mshade354/App.java
 
b/src/it/projects/MSHADE-354/src/main/java/org/apache/maven/its/shade/mshade354/App.java
new file mode 100644
index 0000000..429904d
--- /dev/null
+++ 
b/src/it/projects/MSHADE-354/src/main/java/org/apache/maven/its/shade/mshade354/App.java
@@ -0,0 +1,25 @@
+/*
+ * 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.maven.its.shade.mshade354;
+
+public class App {
+    public static void main(String[] args) {
+        System.out.println("MSHADE-354");
+    }
+}
diff --git a/src/it/projects/MSHADE-354/verify.groovy 
b/src/it/projects/MSHADE-354/verify.groovy
new file mode 100644
index 0000000..3071c63
--- /dev/null
+++ b/src/it/projects/MSHADE-354/verify.groovy
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+import java.io.*;
+
+// the shaded artifact must be in the configured outputDirectory, not the 
default build directory
+File shaded = new File( basedir, "target/custom/mshade354-1.0.jar" );
+System.out.println( "shaded artifact: " + shaded );
+if ( !shaded.isFile() )
+{
+    System.out.println( "shaded artifact does not exist in the configured 
outputDirectory: " + shaded );
+    return false;
+}
+
+// the pre-shade artifact must be preserved alongside it in the same 
outputDirectory
+File original = new File( basedir, "target/custom/original-mshade354-1.0.jar" 
);
+System.out.println( "original artifact: " + original );
+if ( !original.isFile() )
+{
+    System.out.println( "original artifact was not preserved in the configured 
outputDirectory: " + original );
+    return false;
+}
+
+// the shaded artifact must not be left behind in the default build directory
+File defaultLocation = new File( basedir, "target/mshade354-1.0.jar" );
+System.out.println( "default build directory artifact: " + defaultLocation );
+if ( defaultLocation.isFile() )
+{
+    System.out.println( "shaded artifact was incorrectly left in the default 
build directory: " + defaultLocation );
+    return false;
+}
+
+return true;
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 f29b310..c54bb22 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
@@ -719,7 +719,13 @@ public class ShadeMojo extends AbstractMojo {
                     getLog().info("Replacing original artifact with shaded 
artifact.");
                     File originalArtifact = project.getArtifact().getFile();
                     if (originalArtifact != null) {
-                        replaceFile(originalArtifact, outputJar);
+                        // The shaded main artifact always lands in 
outputDirectory, just like the shaded
+                        // sources/test/test-sources artifacts below, even 
though the pre-shade artifact
+                        // produced by an earlier phase (e.g. 
maven-jar-plugin) may live elsewhere, such as
+                        // when outputDirectory differs from the default build 
directory.
+                        File shadedMainArtifactFile = shadedMainArtifactFile();
+                        replaceFile(shadedMainArtifactFile, originalArtifact, 
outputJar);
+                        project.getArtifact().setFile(shadedMainArtifactFile);
 
                         if (createSourcesJar) {
                             getLog().info("Replacing original source artifact 
with shaded source artifact.");
@@ -1017,33 +1023,43 @@ public class ShadeMojo extends AbstractMojo {
     }
 
     private void replaceFile(File oldFile, File newFile) throws 
MojoExecutionException {
-        getLog().debug("Replacing " + oldFile + " with " + newFile);
+        replaceFile(oldFile, oldFile, newFile);
+    }
+
+    /**
+     * Backs up {@code fileToBackup} as {@code original-<destFile.getName()>} 
in {@link #outputDirectory}, then
+     * moves {@code newFile} onto {@code destFile}. {@code fileToBackup} and 
{@code destFile} are the same file in
+     * the common case, but differ when the pre-shade artifact does not 
already live at the location the shaded
+     * artifact belongs at, e.g. when {@link #outputDirectory} differs from 
the default build directory.
+     */
+    private void replaceFile(File destFile, File fileToBackup, File newFile) 
throws MojoExecutionException {
+        getLog().debug("Replacing " + destFile + " with " + newFile);
 
-        File origFile = new File(outputDirectory, "original-" + 
oldFile.getName());
-        if (oldFile.exists() && !oldFile.renameTo(origFile)) {
+        File origFile = new File(outputDirectory, "original-" + 
destFile.getName());
+        if (fileToBackup.exists() && !fileToBackup.renameTo(origFile)) {
             // try a gc to see if an unclosed stream needs garbage collecting
             System.gc();
             System.gc();
 
-            if (!oldFile.renameTo(origFile)) {
+            if (!fileToBackup.renameTo(origFile)) {
                 // Still didn't work. We'll do a copy
                 try {
-                    copyFiles(oldFile, origFile);
+                    copyFiles(fileToBackup, origFile);
                 } catch (IOException ex) {
                     // kind of ignorable here. We're just trying to save the 
original
                     getLog().warn(ex);
                 }
             }
         }
-        if (!newFile.renameTo(oldFile)) {
+        if (!newFile.renameTo(destFile)) {
             // try a gc to see if an unclosed stream needs garbage collecting
             System.gc();
             System.gc();
 
-            if (!newFile.renameTo(oldFile)) {
+            if (!newFile.renameTo(destFile)) {
                 // Still didn't work. We'll do a copy
                 try {
-                    copyFiles(newFile, oldFile);
+                    copyFiles(newFile, destFile);
                 } catch (IOException ex) {
                     throw new MojoExecutionException("Could not replace 
original artifact with shaded artifact!", ex);
                 }
@@ -1239,6 +1255,15 @@ public class ShadeMojo extends AbstractMojo {
         return filters;
     }
 
+    /**
+     * Computes where the shaded main artifact belongs: {@link 
#outputDirectory}, under the same file name as the
+     * pre-shade artifact produced by an earlier phase. This mirrors {@link 
#shadedArtifactFile(String)}, which
+     * already places the shaded sources/test/test-sources artifacts in {@link 
#outputDirectory}.
+     */
+    private File shadedMainArtifactFile() {
+        return new File(outputDirectory, 
project.getArtifact().getFile().getName());
+    }
+
     private File shadedArtifactFileWithClassifier() {
         Artifact artifact = project.getArtifact();
         final String shadedName = shadedArtifactId + "-" + 
artifact.getVersion() + "-" + shadedClassifierName + "."
diff --git 
a/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java 
b/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java
index 8eac7eb..e9295ec 100644
--- a/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/shade/mojo/ShadeMojoTest.java
@@ -26,6 +26,8 @@ import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.net.URL;
 import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -70,6 +72,7 @@ import static java.util.Collections.singletonList;
 import static org.apache.maven.api.plugin.testing.MojoExtension.getBasedir;
 import static 
org.apache.maven.api.plugin.testing.MojoExtension.setVariableValueToObject;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
@@ -316,6 +319,75 @@ class ShadeMojoTest {
         assertTrue(filter.canFilter(new 
File("myfaces-impl-2.0.1-SNAPSHOT-sources.jar"))); // sources jar
     }
 
+    /**
+     * The shaded main artifact must land in {@code outputDirectory}, exactly 
like the shaded sources, test and
+     * test-sources artifacts, even when the pre-shade artifact file lives 
elsewhere.
+     */
+    @Test
+    void testShadedMainArtifactFileUsesOutputDirectory() throws Exception {
+        ShadeMojo mojo = new ShadeMojo();
+
+        File outputDirectory = new File(getBasedir(), 
"target/testShadedMainArtifactFileUsesOutputDirectory/custom");
+        setVariableValueToObject(mojo, "outputDirectory", outputDirectory);
+
+        Artifact artifact = new DefaultArtifact(
+                "org.apache.maven.plugins.shade.test",
+                "test-project",
+                VersionRange.createFromVersion("1.0"),
+                "compile",
+                "jar",
+                null,
+                artifactHandler);
+        artifact.setFile(new File(
+                getBasedir(), 
"target/testShadedMainArtifactFileUsesOutputDirectory/build/test-project-1.0.jar"));
+        project.setArtifact(artifact);
+        setVariableValueToObject(mojo, "project", project);
+
+        Method shadedMainArtifactFile = 
ShadeMojo.class.getDeclaredMethod("shadedMainArtifactFile");
+        shadedMainArtifactFile.setAccessible(true);
+
+        assertEquals(new File(outputDirectory, "test-project-1.0.jar"), 
shadedMainArtifactFile.invoke(mojo));
+    }
+
+    /**
+     * Reproduces MSHADE-354: when the pre-shade artifact does not already 
live where the shaded artifact belongs
+     * (e.g. {@code outputDirectory} differs from the default build 
directory), {@code replaceFile} must still move
+     * the shaded content to the configured destination and back up the 
pre-shade content there, rather than
+     * leaving the shaded jar behind in the pre-shade artifact's original 
directory.
+     */
+    @Test
+    void testReplaceFileMovesShadedJarAcrossDirectories() throws Exception {
+        ShadeMojo mojo = new ShadeMojo();
+
+        File baseDir = new File(getBasedir(), 
"target/testReplaceFileMovesShadedJarAcrossDirectories");
+        File buildDirectory = new File(baseDir, "build");
+        File outputDirectory = new File(baseDir, "custom");
+        buildDirectory.mkdirs();
+        outputDirectory.mkdirs();
+        setVariableValueToObject(mojo, "outputDirectory", outputDirectory);
+
+        File preShadeArtifact = new File(buildDirectory, "app-1.0.jar");
+        Files.write(preShadeArtifact.toPath(), 
"original".getBytes(StandardCharsets.UTF_8));
+
+        File shadedJar = new File(outputDirectory, "app-1.0-shaded.jar");
+        Files.write(shadedJar.toPath(), 
"shaded".getBytes(StandardCharsets.UTF_8));
+
+        File destFile = new File(outputDirectory, "app-1.0.jar");
+
+        Method replaceFile = ShadeMojo.class.getDeclaredMethod("replaceFile", 
File.class, File.class, File.class);
+        replaceFile.setAccessible(true);
+        replaceFile.invoke(mojo, destFile, preShadeArtifact, shadedJar);
+
+        assertFalse(
+                preShadeArtifact.exists(), "the pre-shade artifact must be 
moved out of the default build directory");
+        assertTrue(destFile.exists(), "the shaded artifact must land in the 
configured outputDirectory");
+        assertEquals("shaded", new 
String(Files.readAllBytes(destFile.toPath()), StandardCharsets.UTF_8));
+
+        File backup = new File(outputDirectory, "original-app-1.0.jar");
+        assertTrue(backup.exists(), "the pre-shade artifact must be preserved 
in outputDirectory");
+        assertEquals("original", new 
String(Files.readAllBytes(backup.toPath()), StandardCharsets.UTF_8));
+    }
+
     private void shaderWithPattern(String shadedPattern, File jar) throws 
Exception {
 
         Set<File> set = new LinkedHashSet<>();

Reply via email to