mavenmaven-clean-plugin

Maven Clean: excluding directory inside target from being deleted


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?


Solution

  • 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 folder 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 folder from being deleted using a direct approach:

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