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-dependency-plugin.git

commit 1bdd16bb4aefc0d9454b191d24f3029a7ee275ef
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Sat Nov 14 00:57:35 2026 +0100

    [MDEP-480] Add overWriteFiles to keep existing files when unpacking
---
 .../mdep-480-unpack-overwrite-files/pom.xml        | 129 +++++++++++++++++++
 .../mdep-480-unpack-overwrite-files/setup.groovy   |  31 +++++
 .../mdep-480-unpack-overwrite-files/verify.groovy  |  33 +++++
 .../dependency/fromConfiguration/ArtifactItem.java |  28 +++++
 .../dependency/fromConfiguration/UnpackMojo.java   |  30 +++++
 .../fromDependencies/UnpackDependenciesMojo.java   |  28 +++++
 .../maven/plugins/dependency/utils/UnpackUtil.java |  52 +++++++-
 .../markdown/examples/unpacking-artifacts.md.vm    |   1 +
 .../examples/unpacking-project-dependencies.md.vm  |   2 +
 src/site/markdown/faq.md                           |  12 ++
 .../TestUnpackOverWriteFiles.java                  | 136 +++++++++++++++++++++
 .../TestUnpackDependenciesOverWriteFiles.java      | 112 +++++++++++++++++
 12 files changed, 592 insertions(+), 2 deletions(-)

diff --git a/src/it/projects/mdep-480-unpack-overwrite-files/pom.xml 
b/src/it/projects/mdep-480-unpack-overwrite-files/pom.xml
new file mode 100644
index 00000000..a7e13272
--- /dev/null
+++ b/src/it/projects/mdep-480-unpack-overwrite-files/pom.xml
@@ -0,0 +1,129 @@
+<?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/maven-v4_0_0.xsd";>
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.apache.maven.plugins.dependency.its</groupId>
+    <artifactId>mdep-480-unpack-overwrite-files</artifactId>
+    <version>1.0-SNAPSHOT</version>
+    <packaging>pom</packaging>
+
+    <description>Unpacking onto an existing file keeps it with 
overWriteFiles=false and replaces it by default</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.maven.its.dependency</groupId>
+            <artifactId>ResourceArtifact</artifactId>
+            <version>1.0</version>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-dependency-plugin</artifactId>
+                <version>@project.version@</version>
+                <executions>
+                    <execution>
+                        <id>unpack-dependencies-default</id>
+                        <phase>process-sources</phase>
+                        <goals>
+                            <goal>unpack-dependencies</goal>
+                        </goals>
+                        <configuration>
+                            
<outputDirectory>${basedir}/dependencies-default</outputDirectory>
+                            
<markersDirectory>${project.build.directory}/markers-dependencies-default</markersDirectory>
+                        </configuration>
+                    </execution>
+                    <execution>
+                        <id>unpack-dependencies-keep</id>
+                        <phase>process-sources</phase>
+                        <goals>
+                            <goal>unpack-dependencies</goal>
+                        </goals>
+                        <configuration>
+                            <overWriteFiles>false</overWriteFiles>
+                            
<outputDirectory>${basedir}/dependencies-keep</outputDirectory>
+                            
<markersDirectory>${project.build.directory}/markers-dependencies-keep</markersDirectory>
+                        </configuration>
+                    </execution>
+                    <execution>
+                        <id>unpack-default</id>
+                        <phase>process-sources</phase>
+                        <goals>
+                            <goal>unpack</goal>
+                        </goals>
+                        <configuration>
+                            <artifactItems>
+                                <artifactItem>
+                                    
<groupId>org.apache.maven.its.dependency</groupId>
+                                    <artifactId>ResourceArtifact</artifactId>
+                                    <version>1.0</version>
+                                </artifactItem>
+                            </artifactItems>
+                            
<outputDirectory>${basedir}/unpack-default</outputDirectory>
+                            
<markersDirectory>${project.build.directory}/markers-unpack-default</markersDirectory>
+                        </configuration>
+                    </execution>
+                    <execution>
+                        <id>unpack-keep</id>
+                        <phase>process-sources</phase>
+                        <goals>
+                            <goal>unpack</goal>
+                        </goals>
+                        <configuration>
+                            <artifactItems>
+                                <artifactItem>
+                                    
<groupId>org.apache.maven.its.dependency</groupId>
+                                    <artifactId>ResourceArtifact</artifactId>
+                                    <version>1.0</version>
+                                </artifactItem>
+                            </artifactItems>
+                            <overWriteFiles>false</overWriteFiles>
+                            
<outputDirectory>${basedir}/unpack-keep</outputDirectory>
+                            
<markersDirectory>${project.build.directory}/markers-unpack-keep</markersDirectory>
+                        </configuration>
+                    </execution>
+                    <execution>
+                        <id>unpack-item-keep</id>
+                        <phase>process-sources</phase>
+                        <goals>
+                            <goal>unpack</goal>
+                        </goals>
+                        <configuration>
+                            <artifactItems>
+                                <artifactItem>
+                                    
<groupId>org.apache.maven.its.dependency</groupId>
+                                    <artifactId>ResourceArtifact</artifactId>
+                                    <version>1.0</version>
+                                    <overWriteFiles>false</overWriteFiles>
+                                </artifactItem>
+                            </artifactItems>
+                            
<outputDirectory>${basedir}/unpack-item-keep</outputDirectory>
+                            
<markersDirectory>${project.build.directory}/markers-unpack-item-keep</markersDirectory>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/src/it/projects/mdep-480-unpack-overwrite-files/setup.groovy 
b/src/it/projects/mdep-480-unpack-overwrite-files/setup.groovy
new file mode 100644
index 00000000..86160b00
--- /dev/null
+++ b/src/it/projects/mdep-480-unpack-overwrite-files/setup.groovy
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+// resource1.txt exists before the plugin runs and is newer than the archive 
entry (a filtered resource, say);
+// the ITs run "clean" first, so the directories are outside of target
+def now = System.currentTimeMillis()
+for ( dir in ["dependencies-default", "dependencies-keep", "unpack-default", 
"unpack-keep", "unpack-item-keep"] )
+{
+    File existing = new File( basedir, dir + "/resource1.txt" )
+    existing.parentFile.mkdirs()
+    existing.text = "existing"
+    existing.setLastModified( now + 24L * 60 * 60 * 1000 )
+}
+
+return true
diff --git a/src/it/projects/mdep-480-unpack-overwrite-files/verify.groovy 
b/src/it/projects/mdep-480-unpack-overwrite-files/verify.groovy
new file mode 100644
index 00000000..babfebc0
--- /dev/null
+++ b/src/it/projects/mdep-480-unpack-overwrite-files/verify.groovy
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+// overWriteFiles decides per file; resource2.txt did not exist and is 
extracted in every case
+for ( dir in ["dependencies-default", "unpack-default"] )
+{
+    assert new File( basedir, dir + "/resource1.txt" ).text.contains( 
"Resource 1" ) : dir + " should be replaced"
+    assert new File( basedir, dir + "/resource2.txt" ).isFile()
+}
+
+for ( dir in ["dependencies-keep", "unpack-keep", "unpack-item-keep"] )
+{
+    assert new File( basedir, dir + "/resource1.txt" ).text == "existing" : 
dir + " should be kept"
+    assert new File( basedir, dir + "/resource2.txt" ).isFile()
+}
+
+return true
diff --git 
a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java
 
b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java
index 5c4742b6..fb38f7ac 100644
--- 
a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java
+++ 
b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/ArtifactItem.java
@@ -98,6 +98,16 @@ public class ArtifactItem {
     @Parameter
     private String encoding;
 
+    /**
+     * Whether unpacking may replace files that already exist in the output 
directory, for this item only. Overrides
+     * the {@code overWriteFiles} parameter of the {@code unpack} goal; {@code 
null} means the goal's value applies.
+     * Used by the {@code unpack} goal only.
+     *
+     * @since 3.12.0
+     */
+    @Parameter
+    private Boolean overWriteFiles;
+
     private boolean needsProcessing;
 
     /**
@@ -382,4 +392,22 @@ public class ArtifactItem {
     public void setFileMappers(FileMapper[] fileMappers) {
         this.fileMappers = fileMappers;
     }
+
+    /**
+     * @return whether files that already exist may be replaced when unpacking 
this item, or {@code null} if the
+     *         {@code unpack} goal's {@code overWriteFiles} applies
+     * @since 3.12.0
+     */
+    public Boolean getOverWriteFiles() {
+        return this.overWriteFiles;
+    }
+
+    /**
+     * @param overWriteFiles whether files that already exist may be replaced 
when unpacking this item, or
+     *                       {@code null} to use the {@code unpack} goal's 
value
+     * @since 3.12.0
+     */
+    public void setOverWriteFiles(Boolean overWriteFiles) {
+        this.overWriteFiles = overWriteFiles;
+    }
 }
diff --git 
a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java
 
b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java
index 2f23f7d9..955fa902 100644
--- 
a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java
+++ 
b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/UnpackMojo.java
@@ -89,6 +89,27 @@ public class UnpackMojo extends 
AbstractFromConfigurationMojo {
     @Parameter(property = "mdep.unpack.useDefaultExcludes", defaultValue = 
"true")
     private boolean useDefaultExcludes = true;
 
+    /**
+     * Whether unpacking may replace files that already exist in the output 
directory. This is decided for each file,
+     * independently of the per-artifact {@code overWriteReleases}, {@code 
overWriteSnapshots} and
+     * {@code overWriteIfNewer} parameters and of the marker files: those 
decide whether an artifact is unpacked at
+     * all, this one decides what happens to a file that is already there once 
the artifact is unpacked.
+     * <p>
+     * With {@code true} (the default) every archive entry is written, as 
before. With {@code false} the unarchiver
+     * ({@code plexus-archiver}) writes an entry only if there is no file of 
that name yet, or if the existing file's
+     * last modified time is older than the entry's time stored in the 
archive. An existing file that is as new as or
+     * newer than the archive entry is kept. This means that a file created or 
filtered after the archive was built
+     * is kept, whereas an older file is still replaced. Entries are compared 
by the archive's own timestamp, so
+     * archives that carry a reproducible build timestamp are compared against 
that timestamp.
+     * </p>
+     *
+     * Can also be set for a single {@code artifactItem}, which then takes 
precedence.
+     *
+     * @since 3.12.0
+     */
+    @Parameter(property = "mdep.unpack.overWriteFiles", defaultValue = "true")
+    private boolean overWriteFiles = true;
+
     /**
      * Ignore to set file permissions when unpacking a dependency.
      *
@@ -176,6 +197,7 @@ public class UnpackMojo extends 
AbstractFromConfigurationMojo {
                 artifactItem.getIncludes(),
                 artifactItem.getExcludes(),
                 useDefaultExcludes,
+                artifactItem.getOverWriteFiles() != null ? 
artifactItem.getOverWriteFiles() : overWriteFiles,
                 artifactItem.getEncoding(),
                 ignorePermissions,
                 artifactItem.getFileMappers(),
@@ -238,6 +260,14 @@ public class UnpackMojo extends 
AbstractFromConfigurationMojo {
         this.excludes = excludes;
     }
 
+    /**
+     * @param overWriteFiles whether files that already exist in the output 
directory may be replaced
+     * @since 3.12.0
+     */
+    public void setOverWriteFiles(boolean overWriteFiles) {
+        this.overWriteFiles = overWriteFiles;
+    }
+
     /**
      * @param useDefaultExcludes whether the default excludes are applied when 
excludes are set
      */
diff --git 
a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java
 
b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java
index 77ed8cfc..669c9946 100644
--- 
a/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java
+++ 
b/src/main/java/org/apache/maven/plugins/dependency/fromDependencies/UnpackDependenciesMojo.java
@@ -86,6 +86,25 @@ public class UnpackDependenciesMojo extends 
AbstractFromDependenciesMojo {
     @Parameter(property = "mdep.unpack.useDefaultExcludes", defaultValue = 
"true")
     private boolean useDefaultExcludes = true;
 
+    /**
+     * Whether unpacking may replace files that already exist in the output 
directory. This is decided for each file,
+     * independently of the per-artifact {@code overWriteReleases}, {@code 
overWriteSnapshots} and
+     * {@code overWriteIfNewer} parameters and of the marker files: those 
decide whether an artifact is unpacked at
+     * all, this one decides what happens to a file that is already there once 
the artifact is unpacked.
+     * <p>
+     * With {@code true} (the default) every archive entry is written, as 
before. With {@code false} the unarchiver
+     * ({@code plexus-archiver}) writes an entry only if there is no file of 
that name yet, or if the existing file's
+     * last modified time is older than the entry's time stored in the 
archive. An existing file that is as new as or
+     * newer than the archive entry is kept. This means that a file created or 
filtered after the archive was built
+     * is kept, whereas an older file is still replaced. Entries are compared 
by the archive's own timestamp, so
+     * archives that carry a reproducible build timestamp are compared against 
that timestamp.
+     * </p>
+     *
+     * @since 3.12.0
+     */
+    @Parameter(property = "mdep.unpack.overWriteFiles", defaultValue = "true")
+    private boolean overWriteFiles = true;
+
     /**
      * Ignore to set file permissions when unpacking a dependency.
      *
@@ -158,6 +177,7 @@ public class UnpackDependenciesMojo extends 
AbstractFromDependenciesMojo {
                     getIncludes(),
                     getExcludes(),
                     useDefaultExcludes,
+                    overWriteFiles,
                     getEncoding(),
                     ignorePermissions,
                     getFileMappers(),
@@ -194,6 +214,14 @@ public class UnpackDependenciesMojo extends 
AbstractFromDependenciesMojo {
         this.excludes = excludes;
     }
 
+    /**
+     * @param overWriteFiles whether files that already exist in the output 
directory may be replaced
+     * @since 3.12.0
+     */
+    public void setOverWriteFiles(boolean overWriteFiles) {
+        this.overWriteFiles = overWriteFiles;
+    }
+
     /**
      * @param useDefaultExcludes whether the default excludes are applied when 
excludes are set
      */
diff --git 
a/src/main/java/org/apache/maven/plugins/dependency/utils/UnpackUtil.java 
b/src/main/java/org/apache/maven/plugins/dependency/utils/UnpackUtil.java
index 47253334..e3300790 100644
--- a/src/main/java/org/apache/maven/plugins/dependency/utils/UnpackUtil.java
+++ b/src/main/java/org/apache/maven/plugins/dependency/utils/UnpackUtil.java
@@ -94,6 +94,49 @@ public class UnpackUtil {
         unpack(file, type, location, includes, excludes, true, encoding, 
ignorePermissions, fileMappers, logger);
     }
 
+    /**
+     * Unpacks, replacing existing files.
+     *
+     * @param file              file to unpack
+     * @param type              file / artifact type
+     * @param location          the location
+     * @param includes          includes list
+     * @param excludes          excludes list
+     * @param useDefaultExcludes whether the default excludes (such as {@code 
.svn} and {@code .git}) are applied
+     *                          when excludes are set
+     * @param encoding          the encoding
+     * @param ignorePermissions ignore permissions
+     * @param fileMappers       {@link FileMapper}s to be used for rewriting 
each target path, or {@code null} if no
+     *                          rewriting shall happen
+     * @param logger            a Mojo logger
+     * @throws MojoExecutionException in case of an error
+     */
+    public void unpack(
+            File file,
+            String type,
+            File location,
+            String includes,
+            String excludes,
+            boolean useDefaultExcludes,
+            String encoding,
+            boolean ignorePermissions,
+            FileMapper[] fileMappers,
+            Log logger)
+            throws MojoExecutionException {
+        unpack(
+                file,
+                type,
+                location,
+                includes,
+                excludes,
+                useDefaultExcludes,
+                true,
+                encoding,
+                ignorePermissions,
+                fileMappers,
+                logger);
+    }
+
     /**
      * @param file              file to unpack
      * @param type              file / artifact type
@@ -102,13 +145,15 @@ public class UnpackUtil {
      * @param excludes          excludes list
      * @param useDefaultExcludes whether the default excludes (such as {@code 
.svn} and {@code .git}) are applied
      *                          when excludes are set
+     * @param overWriteFiles    {@code false} to keep an existing file that is 
not older than its archive entry, see
+     *                          {@link UnArchiver#setOverwrite(boolean)}
      * @param encoding          the encoding
      * @param ignorePermissions ignore permissions
      * @param fileMappers       {@link FileMapper}s to be used for rewriting 
each target path, or {@code null} if no
-     *                          rewriting
-     *                          shall happen
+     *                          rewriting shall happen
      * @param logger            a Mojo logger
      * @throws MojoExecutionException in case of an error
+     * @since 3.12.0
      */
     public void unpack(
             File file,
@@ -117,6 +162,7 @@ public class UnpackUtil {
             String includes,
             String excludes,
             boolean useDefaultExcludes,
+            boolean overWriteFiles,
             String encoding,
             boolean ignorePermissions,
             FileMapper[] fileMappers,
@@ -154,6 +200,8 @@ public class UnpackUtil {
 
             unArchiver.setIgnorePermissions(ignorePermissions);
 
+            unArchiver.setOverwrite(overWriteFiles);
+
             unArchiver.setSourceFile(file);
 
             unArchiver.setDestDirectory(location);
diff --git a/src/site/markdown/examples/unpacking-artifacts.md.vm 
b/src/site/markdown/examples/unpacking-artifacts.md.vm
index 03f33fed..174766de 100644
--- a/src/site/markdown/examples/unpacking-artifacts.md.vm
+++ b/src/site/markdown/examples/unpacking-artifacts.md.vm
@@ -118,6 +118,7 @@ you must not put the configuration inside the _executions_ 
tag. Your configurati
               <destFileName>[ filename ]</destFileName>
               <includes>[ comma separated list of file filters ]</includes>
               <excludes>[ comma separated list of file filters ]</excludes>
+              <overWriteFiles>[ false to keep existing files that are not 
older than the archive entry ]</overWriteFiles>
             </artifactItem>
           </artifactItems>
           <!-- other configurations here -->
diff --git a/src/site/markdown/examples/unpacking-project-dependencies.md.vm 
b/src/site/markdown/examples/unpacking-project-dependencies.md.vm
index 1c932932..21266320 100644
--- a/src/site/markdown/examples/unpacking-project-dependencies.md.vm
+++ b/src/site/markdown/examples/unpacking-project-dependencies.md.vm
@@ -55,6 +55,8 @@ To unpack the artifacts, use the 
`dependency:unpack-dependencies` mojo and confi
               
<outputDirectory>${esc.d}{project.build.directory}/alternateLocation</outputDirectory>
               <overWriteReleases>false</overWriteReleases>
               <overWriteSnapshots>true</overWriteSnapshots>
+              <!-- per file: keep existing files that are not older than the 
archive entry -->
+              <overWriteFiles>false</overWriteFiles>
             </configuration>
           </execution>
         </executions>
diff --git a/src/site/markdown/faq.md b/src/site/markdown/faq.md
index 2cfc901d..b0f6e289 100644
--- a/src/site/markdown/faq.md
+++ b/src/site/markdown/faq.md
@@ -87,6 +87,18 @@ unpack uses the following code to determine which files to 
unpack:
 When excludes are set, the default excludes of the file selector (for example 
`.svn`, `CVS` and `.git`) apply as well.
 Set `useDefaultExcludes` to `false` to unpack those files too.
 
+<a id="overwritefiles"></a>
+
+### How do I keep files that already exist in the output directory when 
unpacking?
+
+`overWriteReleases`, `overWriteSnapshots`, `overWriteIfNewer` and the marker 
files decide whether an artifact is
+unpacked at all. Once it is, `unpack` and `unpack-dependencies` write every 
entry of the archive. Set
+`overWriteFiles` (user property `mdep.unpack.overWriteFiles`) to `false` to 
decide per file instead: an entry is
+written only if no file of that name exists yet, or if the existing file is 
older than the entry's timestamp in the
+archive. A file that is as new as or newer than the archive entry is kept, for 
example a resource that was filtered
+into the output directory after the archive was built. Because an older 
existing file is still replaced, this is not
+a guarantee that no file is ever touched. For `unpack`, the parameter can also 
be set on a single `artifactItem`.
+
 <a id="unused"></a>
 
 ### Why does my dependency analysis report `Unused declared dependencies`?
diff --git 
a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackOverWriteFiles.java
 
b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackOverWriteFiles.java
new file mode 100644
index 00000000..ca865cfa
--- /dev/null
+++ 
b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackOverWriteFiles.java
@@ -0,0 +1,136 @@
+/*
+ * 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.plugins.dependency.fromConfiguration;
+
+import javax.inject.Inject;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.Collections;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.maven.api.plugin.testing.Basedir;
+import org.apache.maven.api.plugin.testing.InjectMojo;
+import org.apache.maven.api.plugin.testing.MojoParameter;
+import org.apache.maven.api.plugin.testing.MojoTest;
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenSession;
+import 
org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory;
+import org.apache.maven.project.MavenProject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * MDEP-480: existing files can be kept when unpacking.
+ */
+@MojoTest(realRepositorySession = true)
+@Basedir("/unit/unpack-dependencies-test")
+@MojoParameter(name = "artifact", value = "test:test:1.0")
+class TestUnpackOverWriteFiles {
+    private static final long ENTRY_TIME = 1_000_000_000_000L;
+
+    private static final String EXISTING = "existing";
+
+    @TempDir
+    private File tempDir;
+
+    @Inject
+    private MavenSession session;
+
+    @Inject
+    private MavenProject project;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        File zip = new File(tempDir, "entries.zip");
+        try (ZipOutputStream out = new ZipOutputStream(new 
FileOutputStream(zip))) {
+            for (String name : new String[] {"existing.txt", "old.txt", 
"added.txt"}) {
+                ZipEntry entry = new ZipEntry(name);
+                entry.setTime(ENTRY_TIME);
+                out.putNextEntry(entry);
+                out.write("from archive".getBytes(StandardCharsets.UTF_8));
+                out.closeEntry();
+            }
+        }
+        DependencyArtifactStubFactory stubFactory = new 
DependencyArtifactStubFactory(tempDir, true, false);
+        stubFactory.setSrcFile(zip);
+        stubFactory.createArtifact("test", "test", "1.0", 
Artifact.SCOPE_COMPILE, "jar", null);
+        session.getRequest().setLocalRepositoryPath(new File(tempDir, 
"localTestRepo"));
+        project.getBuild().setDirectory(new File(tempDir, 
"target").getAbsolutePath());
+    }
+
+    private static void createExisting(File dir) throws Exception {
+        dir.mkdirs();
+        File newer = new File(dir, "existing.txt");
+        Files.write(newer.toPath(), EXISTING.getBytes(StandardCharsets.UTF_8));
+        newer.setLastModified(ENTRY_TIME + 86_400_000L);
+        File older = new File(dir, "old.txt");
+        Files.write(older.toPath(), EXISTING.getBytes(StandardCharsets.UTF_8));
+        older.setLastModified(ENTRY_TIME - 86_400_000L);
+    }
+
+    private static String read(File dir, String name) throws Exception {
+        return new String(Files.readAllBytes(new File(dir, name).toPath()), 
StandardCharsets.UTF_8);
+    }
+
+    @Test
+    @InjectMojo(goal = "unpack")
+    void testExistingFilesAreReplacedByDefault(UnpackMojo mojo) throws 
Exception {
+        createExisting(mojo.getOutputDirectory());
+        mojo.execute();
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"existing.txt"));
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"old.txt"));
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"added.txt"));
+    }
+
+    @Test
+    @InjectMojo(goal = "unpack")
+    void testNewerExistingFileIsKept(UnpackMojo mojo) throws Exception {
+        createExisting(mojo.getOutputDirectory());
+        mojo.setOverWriteFiles(false);
+        mojo.execute();
+        assertEquals(EXISTING, read(mojo.getOutputDirectory(), 
"existing.txt"));
+        // the per file rule of plexus-archiver still replaces a file that is 
older than its archive entry
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"old.txt"));
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"added.txt"));
+    }
+
+    @Test
+    @InjectMojo(goal = "unpack")
+    void testArtifactItemOverridesMojo(UnpackMojo mojo) throws Exception {
+        ArtifactItem item = new ArtifactItem();
+        item.setGroupId("test");
+        item.setArtifactId("test");
+        item.setVersion("1.0");
+        item.setType("jar");
+        item.setOverWriteFiles(false);
+        mojo.setArtifactItems(Collections.singletonList(item));
+        createExisting(mojo.getOutputDirectory());
+        // mojo level stays at the default of true
+        mojo.execute();
+        assertEquals(EXISTING, read(mojo.getOutputDirectory(), 
"existing.txt"));
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"added.txt"));
+    }
+}
diff --git 
a/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesOverWriteFiles.java
 
b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesOverWriteFiles.java
new file mode 100644
index 00000000..6871e7d1
--- /dev/null
+++ 
b/src/test/java/org/apache/maven/plugins/dependency/fromDependencies/TestUnpackDependenciesOverWriteFiles.java
@@ -0,0 +1,112 @@
+/*
+ * 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.plugins.dependency.fromDependencies;
+
+import javax.inject.Inject;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.maven.api.plugin.testing.Basedir;
+import org.apache.maven.api.plugin.testing.InjectMojo;
+import org.apache.maven.api.plugin.testing.MojoTest;
+import org.apache.maven.artifact.Artifact;
+import 
org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory;
+import org.apache.maven.project.MavenProject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * MDEP-480: existing files can be kept when unpacking.
+ */
+@MojoTest
+@Basedir("/unit/unpack-dependencies-test")
+class TestUnpackDependenciesOverWriteFiles {
+    private static final long ENTRY_TIME = 1_000_000_000_000L;
+
+    private static final String EXISTING = "existing";
+
+    @TempDir
+    private File tempDir;
+
+    @Inject
+    private MavenProject project;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        File zip = new File(tempDir, "entries.zip");
+        try (ZipOutputStream out = new ZipOutputStream(new 
FileOutputStream(zip))) {
+            for (String name : new String[] {"existing.txt", "old.txt", 
"added.txt"}) {
+                ZipEntry entry = new ZipEntry(name);
+                entry.setTime(ENTRY_TIME);
+                out.putNextEntry(entry);
+                out.write("from archive".getBytes(StandardCharsets.UTF_8));
+                out.closeEntry();
+            }
+        }
+        DependencyArtifactStubFactory stubFactory = new 
DependencyArtifactStubFactory(tempDir, true, false);
+        stubFactory.setSrcFile(zip);
+        project.getBuild().setDirectory(new File(tempDir, 
"target").getAbsolutePath());
+        Set<Artifact> artifacts = stubFactory.getScopedArtifacts();
+        project.setArtifacts(artifacts);
+    }
+
+    private static void createExisting(File dir) throws Exception {
+        dir.mkdirs();
+        File newer = new File(dir, "existing.txt");
+        Files.write(newer.toPath(), EXISTING.getBytes(StandardCharsets.UTF_8));
+        newer.setLastModified(ENTRY_TIME + 86_400_000L);
+        File older = new File(dir, "old.txt");
+        Files.write(older.toPath(), EXISTING.getBytes(StandardCharsets.UTF_8));
+        older.setLastModified(ENTRY_TIME - 86_400_000L);
+    }
+
+    private static String read(File dir, String name) throws Exception {
+        return new String(Files.readAllBytes(new File(dir, name).toPath()), 
StandardCharsets.UTF_8);
+    }
+
+    @Test
+    @InjectMojo(goal = "unpack-dependencies")
+    void testExistingFilesAreReplacedByDefault(UnpackDependenciesMojo mojo) 
throws Exception {
+        createExisting(mojo.getOutputDirectory());
+        mojo.execute();
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"existing.txt"));
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"old.txt"));
+    }
+
+    @Test
+    @InjectMojo(goal = "unpack-dependencies")
+    void testNewerExistingFileIsKept(UnpackDependenciesMojo mojo) throws 
Exception {
+        createExisting(mojo.getOutputDirectory());
+        mojo.setOverWriteFiles(false);
+        mojo.execute();
+        assertEquals(EXISTING, read(mojo.getOutputDirectory(), 
"existing.txt"));
+        // the per file rule of plexus-archiver still replaces a file that is 
older than its archive entry
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"old.txt"));
+        assertEquals("from archive", read(mojo.getOutputDirectory(), 
"added.txt"));
+    }
+}

Reply via email to