Using maven profiles to control build execution

You can achieve your actual goal of enabling the source-jars plugin by default by adding two profiles to your POM. The Maven profiles documentation notes that you can add an element <activeByDefault>true</activeByDefault> to the activation section and states that

This profile will automatically be active for all builds unless another profile in the same POM is activated using one of the previously described methods

So, you can add two profiles, one of which is activeByDefault, which includes the relevant plugin, and another, which can be activated in any of the standard ways (such as -P from the command line) to prevent the default profile from running. The profiles section in your pom.xml (or Maven settings or whatever) might therefore look like this:

<profile>
  <id>source-jars</id>
  <activation>
    <activeByDefault>true</activeByDefault>
  </activation>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        ...
      </plugin>
    </plugins>
  </build>
</profile>
<profile>
   <!-- active this profile to disable the source-jars plugin -->
   <id>no-optional-plugins</id>
</profile>

Unfortunately, I can't see a way to make this method scale well for controlling multiple plugins – I think you need O(n^2) profiles for n plugins, but for this simple case it should work fine.

Another possibly simpler option with Maven ≥ 2.0.10 is to just have the source-jars profile from above (still activeByDefault), and to manually deactivate the profile when you want by prefixing the profile ID with - or ! after -P CLI flag:

$ mvn -P !source-jars

This method doesn't have the same O(n^2) problems with multiple plugins but it is also less flexible, since the deactivation can't be triggered by a system property, environment variable, JDK version etc.


You're thinking about it a bit backwards: have the profile enable the behaviour, not disable it. This is just what profiles are best at, and is exactly your case: you only want the steps to be run in certain circumstances. So you might have something like:

<profile>
  <id>source-jars</id>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        ...

And in fact there's an example just like this on the maven-source-plugin usage page. When you need to generates your artifact, use mvn -P source-jars (or whatever). That's it! If you only need to do this at release time, the release plugin even offers a way to define the profiles to use right in the release plugin configuration.

Tags:

Maven 2