user1974753
user1974753

Reputation: 1457

Unzip and re zip a file using Maven?

Question: is there any way in Maven (without resorting to an ant plugin) to unzip a file, cd into the directory, remove the file, and the rezip it, all as part of the build?

This is necessary as it is a complex build and also do not want to have to use gradle to accomplish this task.

Upvotes: 4

Views: 2990

Answers (1)

A_Di-Matteo
A_Di-Matteo

Reputation: 27862

The requirement of unzipping, removing file and zipping again can also be met in one single step by the truezip-maven-plugin and its remove goal which:

Remove a set of files from an existing archive.

The official examples also cover this scenario.

Given the following snippet:

<properties>
    <archive>${project.basedir}/sample.zip</archive>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>truezip-maven-plugin</artifactId>
            <version>1.2</version>
            <executions>
                <execution>
                    <id>remove-a-file</id>
                    <goals>
                        <goal>remove</goal>
                    </goals>
                    <phase>package</phase>
                    <configuration>
                        <fileset>
                            <!-- note how the archive is treated as a normal file directory -->
                            <directory>${archive}</directory>
                            <includes>
                                <include>hello.txt</include>
                            </includes>
                        </fileset>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

And executing:

mvn clean package

The build will process the ${archive} file (in this case a sample.zip at the same level of the pom.xml file, that is, in the project.basedir directory) and remove from it the hello.txt file. Then rezip everything.

I just tested it successfully, you can even skip the properties section if not required. However, you should also carefully know that:

  • The zip file should not be under version control, otherwise it would create conflicts at each build
  • The behavior most probably should not be part of the default Maven build, hence good candidate for a Maven profile
  • the plugin replaces the original file, so if that was an issue you could firstly copy it to another location and then process it as above. To copy it, you could use the maven-resources-plugin and its copy-resources goal.

Upvotes: 2

Related Questions