Saturday, August 08, 2009

Easy license headers with maven

If you are like me you probably hate trying to maintain license headers on your source code files. It has to be done for pretty much all of my projects (since I deal in open source 99% of the time) but it is pure drudgery. I found a great plugin for maven 2 which makes this a piece of cake (very easy). The maven-license-plugin can (optionally) check your source files for headers (you control which ones or just use the defaults) and add in or replace the headers for you. Forget about doing this manually anymore; those days are over. You just specify a license header template like this (i.e. create a file, I use LICENSE_HEADER):

Copyright (C) ${year} ${holder} <${contact}>

This file is part of ${name}.

Licensed 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.

Then add something like this to your project pom.xml (in the build section under plugins):

<plugin>
<groupId>com.google.code.maven-license-plugin</groupId>
<artifactId>maven-license-plugin</artifactId>
<configuration>
<header>${basedir}/LICENSE_HEADER</header>
<excludes>
<exclude>target/**</exclude>
<exclude>m2-target/**</exclude>
<exclude>**/*.properties</exclude>
</excludes>
<properties>
<name>${project.name}</name>
<year>${project.inceptionYear}</year>
<holder>Aaron Zeckoski</holder>
<contact>azeckoski@gmail.com</contact>
</properties>
<encoding>UTF-8</encoding>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>

You need to add in the plugin repo in the pluginRepositories section:

<pluginRepository>
<id>mc-release</id>
<url>http://mc-repo.googlecode.com/svn/maven2/releases</url>
</pluginRepository>

That config will cause the check to run on every build (ignoring properties files is a good idea since the plugin has trouble with them). Files with a missing license header will cause the build to fail ensuring you remember to run the command to format them. The properties you set there will fill in the ${field} vars in the license header template.

Now run the maven command to check for license headers:
mvn license:check
or simply do a build (which will also run the check):
mvn clean install
You should get a report about the files missing license headers.
Run this command and all the license headers will be added or updated to match your template:
mvn license:format
One final note, you can remove all the license headers using "mvn license:remove". Very cool.

No comments: