Maven Clean: excluding directory inside target from being deleted

ftkg picture ftkg · Dec 7, 2016 · Viewed 8.2k times · Source

I have tried many variants but could not make this work. One example (child pom.xml):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-clean-plugin</artifactId>
    <configuration>
        <filesets>
            <fileset>
                <directory>target</directory>
                <useDefaultExcludes>true</useDefaultExcludes>
                <excludes>
                    <exclude>myFolder</exclude>
                </excludes>
            </fileset>
        </filesets>
    </configuration>
</plugin>

Maven always tries to delete my folder. Why?

Answer

Naman picture Naman · Dec 7, 2016

As also suggested by @AR.3 in the answer here, the clean phase and goal would -

By default, it discovers and deletes the directories configured in project.build.directory, project.build.outputDirectory, project.build.testOutputDirectory, and project.reporting.outputDirectory.

Still, if you want to exclude a specific file from being deleted you can follow the inverse approach(a simple hack) to do it as follows -

<plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-clean-plugin</artifactId>
       <version>3.0.0</version>
       <configuration>
           <excludeDefaultDirectories>true</excludeDefaultDirectories>
           <filesets>
                <fileset>
                    <directory>target</directory>
                    <followSymlinks>false</followSymlinks>
                    <useDefaultExcludes>true</useDefaultExcludes>
                    <includes>
                          <include><!--everything other that what you want to exclude--></include>
                    </includes>
                 </fileset>
            </filesets>
        </configuration>
</plugin>

More about excludeDefaultDirectories from a similar link -

Disables the deletion of the default output directories configured for a project. If set to true, only the files/directories selected via the parameter filesets will be deleted.

EDIT

It is indeed possible to exclude a specific file from being deleted using a direct approach:

<configuration>
    <excludeDefaultDirectories>true</excludeDefaultDirectories>
        <filesets>
            <fileset>
                <directory>target</directory>
                <includes>
                    <include>**</include>
                </includes>
                <excludes>
                    <exclude><!-- folder you want to exclude --></exclude>
                </excludes>
            </fileset>
        </filesets>
</configuration>