Author: tchemit Date: 2010-01-21 13:35:36 +0100 (Thu, 21 Jan 2010) New Revision: 1676 Added: trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFileMojo.java trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFileMojo.java trunk/src/main/java/org/nuiton/license/plugin/GeneratorListMojo.java trunk/src/main/java/org/nuiton/license/plugin/LicenseListMojo.java trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderMojo.java trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFileMojoTest.java trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderMojoTest.java trunk/src/test/resources/org/nuiton/license/plugin/addLicenseFileMojoTest/ trunk/src/test/resources/org/nuiton/license/plugin/updateHeaderMojoTest/ Removed: trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFilePlugin.java trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFilePlugin.java trunk/src/main/java/org/nuiton/license/plugin/GeneratorListPlugin.java trunk/src/main/java/org/nuiton/license/plugin/LicenseListPlugin.java trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderPlugin.java trunk/src/main/resources/META-INF/services/org.nuiton.license.header.generator.HeaderGenerator trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFilePluginTest.java trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderPluginTest.java trunk/src/test/resources/org/nuiton/license/plugin/addLicenseFilePluginTest/ trunk/src/test/resources/org/nuiton/license/plugin/updateHeaderPluginTest/ Modified: trunk/src/main/java/org/nuiton/license/plugin/header/generator/XmlLicenseHeaderGeneratorImpl.java Log: - Evolution #248: Rename Mojo classes from Plugin suffix to Mojo suffix - Evolution #249: Remove ServiceLoader mecanism Copied: trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFileMojo.java (from rev 1674, trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFilePlugin.java) =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFileMojo.java (rev 0) +++ trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFileMojo.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -0,0 +1,298 @@ +/* + * *##% + * Maven helper plugin + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.license.plugin; + + +import org.apache.maven.project.MavenProject; +import org.nuiton.license.plugin.repository.License; +import org.nuiton.license.plugin.repository.LicenseRepository; +import org.nuiton.license.plugin.repository.LicenseRepositoryFactory; +import org.nuiton.plugin.AbstractPlugin; +import org.nuiton.plugin.PluginHelper; + +import java.io.File; + +/** + * Le goal pour ajouter le fichier LICENSE.txt dans le classpath (et le generer s'il n'existe pas). + * + * @author chemit + * @goal add-license + * @phase generate-resources + * @requiresProject true + * @requiresDependencyResolution compile + */ +public class AddLicenseFileMojo extends AbstractPlugin { + + /** + * Dependance du projet. + * + * @parameter default-value="${project}" + * @required + * @since 1.0.0 + */ + protected MavenProject project; + /** + * Fichier de la licence du module. + * + * @parameter expression="${helper.licenceFile}" default-value="${basedir}/LICENSE.txt" + * @required + * @since 1.0.0 + */ + protected File licenseFile; + /** + * Le type de license a appliquer. + * <p/> + * Pour obtenir la liste des licenses disponibles, utilisez le goal <b>available-licenses</b> + * <pre> + * mvn helper:available-licenses -Ddetail + * </pre> + * + * @parameter expression="${license.licenseName}" + * @required + * @since 1.0.0 + */ + protected String licenseName; + /** + * Repertoire de sortie des sources. + * + * @parameter expression="${helper.outputDirectory}" default-value="target/generated-sources/license" + * @required + * @since 1.0.0 + */ + protected File outputDirectory; + /** + * Repertoire de sortie des classes (classpath). + * + * @parameter expression="${helper.licenceFilename}" default-value="" + * @since 1.0.0 + */ + protected String licenseFilename; + /** + * Encoding a utiliser pour lire et ecrire les fichiers. + * + * @parameter expression="${helper.encoding}" default-value="${project.build.sourceEncoding}" + * @required + * @since 1.0.0 + */ + protected String encoding; + /** + * Un flag pour conserver un backup des fichiers modifies. + * + * @parameter expression="${helper.keepBackup}" default-value="false" + * @since 1.0.0 + */ + protected boolean keepBackup; + /** + * Un flag pour forcer la generation. + * + * @parameter expression="${helper.force}" default-value="false" + * @since 1.0.0 + */ + protected boolean force; + /** + * Un flag pour activer le mode verbeux. + * + * @parameter expression="${helper.verbose}" default-value="${maven.verbose}" + * @since 1.0.0 + */ + protected boolean verbose; + /** + * Un flag pour faire une copie nommée dans META-INF (prefixe avec le nom de l'artifact). + * <p/> + * Cette option n'est utilisable que sur des modules avec un class-path (pas pour un pom) + * + * @parameter expression="${helper.copyToMETA_INF}" default-value="false" + * @since 1.0.0 + */ + protected boolean copyToMETA_INF; + /** + * La baseURL d'un resolver de license supplementaire + * + * @parameter expression="${helper.extraResolver}" + * @since 1.0.0 + */ + protected String[] extraResolver; + protected License license; + +// public AddLicenseFileMojo() { +// super("all files are up-to-date."); +// } + + protected boolean hasClassPath() { + return rejectPackaging(Packaging.pom); + } +// @Override +// protected boolean ensurePackaging() { + // return false; +//// return project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging())); +// } + boolean doGenerate; + + @Override + protected void init() throws Exception { +// protected boolean init() throws Exception { + + // must generate if file does not exist + doGenerate = true; + + if (!force) { + // regenerate only if file exists and is newer than pom file + doGenerate = !isFileNewerThanPomFile(licenseFile); + } + + // acquire license + + LicenseRepository factory = LicenseRepositoryFactory.newLicenseRepository(true, true, extraResolver); + + license = factory.getLicense(licenseName); + + if (licenseFilename == null || licenseFilename.isEmpty()) { + licenseFilename = licenseName; + } + // always execute the mojo ? +// return true; + } + + @Override + protected void doAction() throws Exception { + getLog().info("using licence [" + licenseName + "]"); + + if (doGenerate) { + if (verbose) { + getLog().info("detail : " + license); + } + + if (licenseFile.exists() && keepBackup) { + if (verbose) { + getLog().info("backup " + licenseFile); + } + // copy it to backup file + backupFile(licenseFile); +// File backup = new File(licenseFile.getAbsolutePath() + "~"); +// licenseFile.renameTo(backup); + } + } + + String licenseContent = license.getLicenseContent(encoding); + + if (doGenerate) { + writeFile(licenseFile, licenseContent, encoding); + } + + if (hasClassPath()) { + // copy LICENSE.txt to classpath + File target = new File(outputDirectory, licenseFile.getName()); + + copyFile(licenseFile, target); + + if (copyToMETA_INF) { + File destFile = PluginHelper.getFile(outputDirectory, "META-INF", project.getArtifactId() + "-" + licenseFile.getName()); + copyFile(licenseFile, destFile); + } + addResourceDir(outputDirectory, "**/*.txt"); +// addResourceDir(outputDirectory.getAbsolutePath()); + } + } + + public File getLicenseFile() { + return licenseFile; + } + + public String getLicenseName() { + return licenseName; + } + + public org.nuiton.license.plugin.repository.License getLicense() { + return license; + } + + public String[] getExtraResolver() { + return extraResolver; + } + + public String getEncoding() { + return encoding; + } + + public boolean isKeepBackup() { + return keepBackup; + } + + public boolean isForce() { + return force; + } + + public File getOutputDirectory() { + return outputDirectory; + } + + public void setLicenseFile(File licenseFile) { + this.licenseFile = licenseFile; + } + + public void setLicenseName(String licenseName) { + this.licenseName = licenseName; + } + + public void setExtraResolver(String[] extraResolver) { + this.extraResolver = extraResolver; + } + + public void setLicense(org.nuiton.license.plugin.repository.License license) { + this.license = license; + } + + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + public void setKeepBackup(boolean keepBackup) { + this.keepBackup = keepBackup; + } + + public void setOutputDirectory(File outputDirectory) { + this.outputDirectory = outputDirectory; + } + + public void setForce(boolean force) { + this.force = force; + } + + @Override + public boolean isVerbose() { + return verbose; + } + + @Override + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + @Override + public MavenProject getProject() { + return project; + } + + @Override + public void setProject(MavenProject project) { + this.project = project; + } +} Property changes on: trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFileMojo.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFilePlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFilePlugin.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/main/java/org/nuiton/license/plugin/AddLicenseFilePlugin.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,298 +0,0 @@ -/* - * *##% - * Maven helper plugin - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.license.plugin; - - -import org.apache.maven.project.MavenProject; -import org.nuiton.license.plugin.repository.License; -import org.nuiton.license.plugin.repository.LicenseRepository; -import org.nuiton.license.plugin.repository.LicenseRepositoryFactory; -import org.nuiton.plugin.AbstractPlugin; -import org.nuiton.plugin.PluginHelper; - -import java.io.File; - -/** - * Le goal pour ajouter le fichier LICENSE.txt dans le classpath (et le generer s'il n'existe pas). - * - * @author chemit - * @goal add-license - * @phase generate-resources - * @requiresProject true - * @requiresDependencyResolution compile - */ -public class AddLicenseFilePlugin extends AbstractPlugin { - - /** - * Dependance du projet. - * - * @parameter default-value="${project}" - * @required - * @since 1.0.0 - */ - protected MavenProject project; - /** - * Fichier de la licence du module. - * - * @parameter expression="${helper.licenceFile}" default-value="${basedir}/LICENSE.txt" - * @required - * @since 1.0.0 - */ - protected File licenseFile; - /** - * Le type de license a appliquer. - * <p/> - * Pour obtenir la liste des licenses disponibles, utilisez le goal <b>available-licenses</b> - * <pre> - * mvn helper:available-licenses -Ddetail - * </pre> - * - * @parameter expression="${license.licenseName}" - * @required - * @since 1.0.0 - */ - protected String licenseName; - /** - * Repertoire de sortie des sources. - * - * @parameter expression="${helper.outputDirectory}" default-value="target/generated-sources/license" - * @required - * @since 1.0.0 - */ - protected File outputDirectory; - /** - * Repertoire de sortie des classes (classpath). - * - * @parameter expression="${helper.licenceFilename}" default-value="" - * @since 1.0.0 - */ - protected String licenseFilename; - /** - * Encoding a utiliser pour lire et ecrire les fichiers. - * - * @parameter expression="${helper.encoding}" default-value="${project.build.sourceEncoding}" - * @required - * @since 1.0.0 - */ - protected String encoding; - /** - * Un flag pour conserver un backup des fichiers modifies. - * - * @parameter expression="${helper.keepBackup}" default-value="false" - * @since 1.0.0 - */ - protected boolean keepBackup; - /** - * Un flag pour forcer la generation. - * - * @parameter expression="${helper.force}" default-value="false" - * @since 1.0.0 - */ - protected boolean force; - /** - * Un flag pour activer le mode verbeux. - * - * @parameter expression="${helper.verbose}" default-value="${maven.verbose}" - * @since 1.0.0 - */ - protected boolean verbose; - /** - * Un flag pour faire une copie nommée dans META-INF (prefixe avec le nom de l'artifact). - * <p/> - * Cette option n'est utilisable que sur des modules avec un class-path (pas pour un pom) - * - * @parameter expression="${helper.copyToMETA_INF}" default-value="false" - * @since 1.0.0 - */ - protected boolean copyToMETA_INF; - /** - * La baseURL d'un resolver de license supplementaire - * - * @parameter expression="${helper.extraResolver}" - * @since 1.0.0 - */ - protected String[] extraResolver; - protected License license; - -// public AddLicenseFilePlugin() { -// super("all files are up-to-date."); -// } - - protected boolean hasClassPath() { - return rejectPackaging(Packaging.pom); - } -// @Override -// protected boolean ensurePackaging() { - // return false; -//// return project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging())); -// } - boolean doGenerate; - - @Override - protected void init() throws Exception { -// protected boolean init() throws Exception { - - // must generate if file does not exist - doGenerate = true; - - if (!force) { - // regenerate only if file exists and is newer than pom file - doGenerate = !isFileNewerThanPomFile(licenseFile); - } - - // acquire license - - LicenseRepository factory = LicenseRepositoryFactory.newLicenseRepository(true, true, extraResolver); - - license = factory.getLicense(licenseName); - - if (licenseFilename == null || licenseFilename.isEmpty()) { - licenseFilename = licenseName; - } - // always execute the mojo ? -// return true; - } - - @Override - protected void doAction() throws Exception { - getLog().info("using licence [" + licenseName + "]"); - - if (doGenerate) { - if (verbose) { - getLog().info("detail : " + license); - } - - if (licenseFile.exists() && keepBackup) { - if (verbose) { - getLog().info("backup " + licenseFile); - } - // copy it to backup file - backupFile(licenseFile); -// File backup = new File(licenseFile.getAbsolutePath() + "~"); -// licenseFile.renameTo(backup); - } - } - - String licenseContent = license.getLicenseContent(encoding); - - if (doGenerate) { - writeFile(licenseFile, licenseContent, encoding); - } - - if (hasClassPath()) { - // copy LICENSE.txt to classpath - File target = new File(outputDirectory, licenseFile.getName()); - - copyFile(licenseFile, target); - - if (copyToMETA_INF) { - File destFile = PluginHelper.getFile(outputDirectory, "META-INF", project.getArtifactId() + "-" + licenseFile.getName()); - copyFile(licenseFile, destFile); - } - addResourceDir(outputDirectory, "**/*.txt"); -// addResourceDir(outputDirectory.getAbsolutePath()); - } - } - - public File getLicenseFile() { - return licenseFile; - } - - public String getLicenseName() { - return licenseName; - } - - public org.nuiton.license.plugin.repository.License getLicense() { - return license; - } - - public String[] getExtraResolver() { - return extraResolver; - } - - public String getEncoding() { - return encoding; - } - - public boolean isKeepBackup() { - return keepBackup; - } - - public boolean isForce() { - return force; - } - - public File getOutputDirectory() { - return outputDirectory; - } - - public void setLicenseFile(File licenseFile) { - this.licenseFile = licenseFile; - } - - public void setLicenseName(String licenseName) { - this.licenseName = licenseName; - } - - public void setExtraResolver(String[] extraResolver) { - this.extraResolver = extraResolver; - } - - public void setLicense(org.nuiton.license.plugin.repository.License license) { - this.license = license; - } - - public void setEncoding(String encoding) { - this.encoding = encoding; - } - - public void setKeepBackup(boolean keepBackup) { - this.keepBackup = keepBackup; - } - - public void setOutputDirectory(File outputDirectory) { - this.outputDirectory = outputDirectory; - } - - public void setForce(boolean force) { - this.force = force; - } - - @Override - public boolean isVerbose() { - return verbose; - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - @Override - public MavenProject getProject() { - return project; - } - - @Override - public void setProject(MavenProject project) { - this.project = project; - } -} Copied: trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFileMojo.java (from rev 1675, trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFilePlugin.java) =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFileMojo.java (rev 0) +++ trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFileMojo.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -0,0 +1,394 @@ +/* + * *##% + * Maven helper plugin + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.license.plugin; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.resolver.ArtifactCollector; +import org.apache.maven.artifact.resolver.filter.ArtifactFilter; +import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; +import org.apache.maven.model.License; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.MavenProjectBuilder; +import org.apache.maven.project.ProjectBuildingException; +import org.apache.maven.shared.dependency.tree.DependencyNode; +import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder; +import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException; + +import java.io.File; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; +import org.nuiton.plugin.AbstractPlugin; +import org.nuiton.plugin.PluginHelper; + +/** + * Le goal pour copier le fichier THIRD-PARTY.txt (contenant les licenses de toutes les dependances du projet) + * dans le classpath (et le generer s'il n'existe pas). + * + * @author chemit + * @goal add-third-party + * @phase generate-resources + * @requiresDependencyResolution test + * @requiresProject true + */ +public class AddThirdPartyFileMojo extends AbstractPlugin { + + private static final String unknownLicenseMessage = "Unknown license"; + /** + * Dependance du projet. + * + * @parameter default-value="${project}" + * @required + * @readonly + * @since 1.0.0 + */ + protected MavenProject project; + /** + * Fichier ou ecrire les licences des dependances. + * + * @parameter expression="${helper.thirdPartyFilename}" default-value="THIRD-PARTY.txt" + * @required + * @since 1.0.0 + */ + protected String thirdPartyFilename; + /** + * Repertoire de sortie des classes (classpath). + * + * @parameter expression="${helper.outputDirectory}" default-value="target/generated-sources/license" + * @required + * @since 1.0.0 + */ + protected File outputDirectory; + /** + * Encoding a utiliser pour lire et ecrire les fichiers. + * + * @parameter expression="${helper.encoding}" default-value="${project.build.sourceEncoding}" + * @required + * @since 1.0.0 + */ + protected String encoding; + /** + * Un flag pour forcer la generation. + * + * @parameter expression="${helper.force}" default-value="false" + * @since 1.0.0 + */ + protected boolean force; + /** + * Un flag pour conserver un backup des fichiers modifies. + * + * @parameter expression="${helper.keepBackup}" default-value="false" + * @since 1.0.0 + */ + protected boolean keepBackup; + /** + * Un flag pour faire une copie nommé dans META-INF (prefixe avec le nom de l'artifact). + * + * @parameter expression="${helper.copyToMETA_INF}" default-value="false" + * @since 1.0.0 + */ + protected boolean copyToMETA_INF; + /** + * Un flag pour activer le mode verbeux. + * + * @parameter expression="${helper.verbose}" default-value="${maven.verbose}" + * @since 1.0.0 + */ + protected boolean verbose; + /** + * Local Repository. + * + * @parameter expression="${localRepository}" + * @required + * @readonly + * @since 1.0.0 + */ + protected ArtifactRepository localRepository; + /** + * Remote repositories used for the project. + * + * @parameter expression="${project.remoteArtifactRepositories}" + * @required + * @readonly + * @since 1.0.0 + */ + protected List<?> remoteRepositories; + /** + * Dependency tree builder component. + * + * @component + */ + protected DependencyTreeBuilder dependencyTreeBuilder; + /** + * Artifact Factory component. + * + * @component + */ + protected ArtifactFactory factory; + /** + * Artifact metadata source component. + * + * @component + */ + protected ArtifactMetadataSource artifactMetadataSource; + /** + * Artifact collector component. + * + * @component + */ + protected ArtifactCollector collector; + /** + * Maven Project Builder component. + * + * @component + */ + protected MavenProjectBuilder mavenProjectBuilder; + /** + * content of third party file (only computed if {@link #force} is active or the + * {@link #thirdPartyFile} does not exist, or is not up-to-date. + */ + protected String thirdPartyFileContent; + protected File thirdPartyFile; + + @Override + protected boolean checkPackaging() { + return rejectPackaging(Packaging.pom); + } + boolean doGenerate; + + @Override + protected void init() throws Exception { + + doGenerate = true; + thirdPartyFile = new File(outputDirectory, thirdPartyFilename); + + if (!force) { + // regenerate only if file exists and is newer than pom file + doGenerate = !isFileNewerThanPomFile(thirdPartyFile); + } + + if (doGenerate) { + + // prepare thirdPartyFileContent + + DependencyNode dependencyTreeNode = resolveProject(); + + LicenseMap licenseMap = new LicenseMap(); + + for (Object o : dependencyTreeNode.getChildren()) { + + buildLicenseMap((DependencyNode) o, licenseMap); + } + + thirdPartyFileContent = buildGroupedLicenses(licenseMap); + + // log dependencies with no license + SortedSet<String> dependenciesWithNoLicense = licenseMap.get(unknownLicenseMessage); + if (dependenciesWithNoLicense != null) { + for (String dep : dependenciesWithNoLicense) { + // no license found for the dependency + getLog().warn("no license found for dependency " + dep); + } + } + } else { + thirdPartyFileContent = PluginHelper.readAsString(thirdPartyFile, encoding); + } + } + + @Override + protected void doAction() throws Exception { + if (doGenerate) { + if (verbose) { + getLog().info("writing third-party file : " + thirdPartyFile); + } + if (keepBackup && thirdPartyFile.exists()) { + if (verbose) { + getLog().info("backup " + thirdPartyFile); + } + backupFile(thirdPartyFile); + } + writeFile(thirdPartyFile, thirdPartyFileContent, encoding); + } + if (copyToMETA_INF) { + copyFile(thirdPartyFile, new File(outputDirectory, "META-INF" + File.separator + project.getArtifactId() + "-" + thirdPartyFile.getName())); + } + addResourceDir(outputDirectory,"**/*.txt"); + } + + /** @return resolve the dependency tree */ + protected DependencyNode resolveProject() { + try { + ArtifactFilter artifactFilter = new ScopeArtifactFilter(Artifact.SCOPE_TEST); + return dependencyTreeBuilder.buildDependencyTree(project, localRepository, factory, + artifactMetadataSource, artifactFilter, collector); + } catch (DependencyTreeBuilderException e) { + getLog().error("Unable to build dependency tree.", e); + return null; + } + } + + protected void buildLicenseMap(DependencyNode node, LicenseMap licenseMap) { + if (node.getState() != DependencyNode.INCLUDED) { + // this dependency is not included, so do not treate it + if (verbose) { + getLog().info("do not include this dependency " + node.toNodeString()); + } + return; + } + Artifact artifact = node.getArtifact(); + + if (verbose && getLog().isDebugEnabled()) { + getLog().debug("treate node " + node.toNodeString()); + } + + if (!Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { + try { + MavenProject artifactProject = getMavenProjectFromRepository(artifact); + String artifactName = getArtifactName(artifactProject); + + List<?> licenses = artifactProject.getLicenses(); + + if (licenses.isEmpty()) { + // no license found for the dependency + licenseMap.put(unknownLicenseMessage, artifactName); + + } else { + for (Object o : licenses) { + if (o == null) { + getLog().warn("could not acquire the license for " + artifactName); + continue; + } + License license = (License) o; + String licenseKey = license.getName(); + if (license.getName() == null) { + licenseKey = license.getUrl(); + } + licenseMap.put(licenseKey, artifactName); + } + } + } catch (ProjectBuildingException e) { + getLog().error("ProjectBuildingException error : ", e); + } + } + if (!node.getChildren().isEmpty()) { + for (Object o : node.getChildren()) { + buildLicenseMap((DependencyNode) o, licenseMap); + } + } + } + + protected String buildGroupedLicenses(LicenseMap licenseMap) { + StringBuilder sb = new StringBuilder(); + sb.append("List of third-party dependencies grouped by their license type."); + for (String licenseName : licenseMap.keySet()) { + sb.append("\n\n").append(licenseName).append(" : "); + + SortedSet<String> projects = licenseMap.get(licenseName); + + for (String projectName : projects) { + sb.append("\n * ").append(projectName); + } + } + return sb.toString(); + } + + protected String getArtifactName(MavenProject artifactProject) { + StringBuilder sb = new StringBuilder(); + + sb.append(artifactProject.getName()); + sb.append(" ("); + sb.append(artifactProject.getGroupId()); + sb.append(":"); + sb.append(artifactProject.getArtifactId()); + sb.append(":"); + sb.append(artifactProject.getVersion()); + sb.append(" - "); + String url = artifactProject.getUrl(); + sb.append(url == null ? "no url defined" : url); + sb.append(")"); + + return sb.toString(); + } + + /** + * Get the <code>Maven project</code> from the repository depending the <code>Artifact</code> given. + * + * @param artifact an artifact + * @return the Maven project for the given artifact + * @throws ProjectBuildingException if any + */ + protected MavenProject getMavenProjectFromRepository(Artifact artifact) + throws ProjectBuildingException { + + boolean allowStubModel = false; + + if (!"pom".equals(artifact.getType())) { + artifact = factory.createProjectArtifact(artifact.getGroupId(), artifact.getArtifactId(), + artifact.getVersion(), artifact.getScope()); + allowStubModel = true; + } + + // TODO: we should use the MavenMetadataSource instead + return mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository, + allowStubModel); + } + + protected class LicenseMap extends java.util.TreeMap<String, SortedSet<String>> { + + private static final long serialVersionUID = 864199843545688069L; + + public SortedSet<String> put(String key, String value) { + // handle multiple values as a set to avoid duplicates + SortedSet<String> valueList = get(key); + if (valueList == null) { + valueList = new TreeSet<String>(); + } + if (getLog().isDebugEnabled()) { + getLog().debug("key:" + key + ",value: " + value); + } + valueList.add(value); + return put(key, valueList); + } + } + + @Override + public boolean isVerbose() { + return verbose; + } + + @Override + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + @Override + public MavenProject getProject() { + return project; + } + + @Override + public void setProject(MavenProject project) { + this.project = project; + } +} Property changes on: trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFileMojo.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFilePlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFilePlugin.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/main/java/org/nuiton/license/plugin/AddThirdPartyFilePlugin.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,394 +0,0 @@ -/* - * *##% - * Maven helper plugin - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.license.plugin; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.metadata.ArtifactMetadataSource; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.resolver.ArtifactCollector; -import org.apache.maven.artifact.resolver.filter.ArtifactFilter; -import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; -import org.apache.maven.model.License; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.MavenProjectBuilder; -import org.apache.maven.project.ProjectBuildingException; -import org.apache.maven.shared.dependency.tree.DependencyNode; -import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder; -import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException; - -import java.io.File; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; -import org.nuiton.plugin.AbstractPlugin; -import org.nuiton.plugin.PluginHelper; - -/** - * Le goal pour copier le fichier THIRD-PARTY.txt (contenant les licenses de toutes les dependances du projet) - * dans le classpath (et le generer s'il n'existe pas). - * - * @author chemit - * @goal add-third-party - * @phase generate-resources - * @requiresDependencyResolution test - * @requiresProject true - */ -public class AddThirdPartyFilePlugin extends AbstractPlugin { - - private static final String unknownLicenseMessage = "Unknown license"; - /** - * Dependance du projet. - * - * @parameter default-value="${project}" - * @required - * @readonly - * @since 1.0.0 - */ - protected MavenProject project; - /** - * Fichier ou ecrire les licences des dependances. - * - * @parameter expression="${helper.thirdPartyFilename}" default-value="THIRD-PARTY.txt" - * @required - * @since 1.0.0 - */ - protected String thirdPartyFilename; - /** - * Repertoire de sortie des classes (classpath). - * - * @parameter expression="${helper.outputDirectory}" default-value="target/generated-sources/license" - * @required - * @since 1.0.0 - */ - protected File outputDirectory; - /** - * Encoding a utiliser pour lire et ecrire les fichiers. - * - * @parameter expression="${helper.encoding}" default-value="${project.build.sourceEncoding}" - * @required - * @since 1.0.0 - */ - protected String encoding; - /** - * Un flag pour forcer la generation. - * - * @parameter expression="${helper.force}" default-value="false" - * @since 1.0.0 - */ - protected boolean force; - /** - * Un flag pour conserver un backup des fichiers modifies. - * - * @parameter expression="${helper.keepBackup}" default-value="false" - * @since 1.0.0 - */ - protected boolean keepBackup; - /** - * Un flag pour faire une copie nommé dans META-INF (prefixe avec le nom de l'artifact). - * - * @parameter expression="${helper.copyToMETA_INF}" default-value="false" - * @since 1.0.0 - */ - protected boolean copyToMETA_INF; - /** - * Un flag pour activer le mode verbeux. - * - * @parameter expression="${helper.verbose}" default-value="${maven.verbose}" - * @since 1.0.0 - */ - protected boolean verbose; - /** - * Local Repository. - * - * @parameter expression="${localRepository}" - * @required - * @readonly - * @since 1.0.0 - */ - protected ArtifactRepository localRepository; - /** - * Remote repositories used for the project. - * - * @parameter expression="${project.remoteArtifactRepositories}" - * @required - * @readonly - * @since 1.0.0 - */ - protected List<?> remoteRepositories; - /** - * Dependency tree builder component. - * - * @component - */ - protected DependencyTreeBuilder dependencyTreeBuilder; - /** - * Artifact Factory component. - * - * @component - */ - protected ArtifactFactory factory; - /** - * Artifact metadata source component. - * - * @component - */ - protected ArtifactMetadataSource artifactMetadataSource; - /** - * Artifact collector component. - * - * @component - */ - protected ArtifactCollector collector; - /** - * Maven Project Builder component. - * - * @component - */ - protected MavenProjectBuilder mavenProjectBuilder; - /** - * content of third party file (only computed if {@link #force} is active or the - * {@link #thirdPartyFile} does not exist, or is not up-to-date. - */ - protected String thirdPartyFileContent; - protected File thirdPartyFile; - - @Override - protected boolean checkPackaging() { - return rejectPackaging(Packaging.pom); - } - boolean doGenerate; - - @Override - protected void init() throws Exception { - - doGenerate = true; - thirdPartyFile = new File(outputDirectory, thirdPartyFilename); - - if (!force) { - // regenerate only if file exists and is newer than pom file - doGenerate = !isFileNewerThanPomFile(thirdPartyFile); - } - - if (doGenerate) { - - // prepare thirdPartyFileContent - - DependencyNode dependencyTreeNode = resolveProject(); - - LicenseMap licenseMap = new LicenseMap(); - - for (Object o : dependencyTreeNode.getChildren()) { - - buildLicenseMap((DependencyNode) o, licenseMap); - } - - thirdPartyFileContent = buildGroupedLicenses(licenseMap); - - // log dependencies with no license - SortedSet<String> dependenciesWithNoLicense = licenseMap.get(unknownLicenseMessage); - if (dependenciesWithNoLicense != null) { - for (String dep : dependenciesWithNoLicense) { - // no license found for the dependency - getLog().warn("no license found for dependency " + dep); - } - } - } else { - thirdPartyFileContent = PluginHelper.readAsString(thirdPartyFile, encoding); - } - } - - @Override - protected void doAction() throws Exception { - if (doGenerate) { - if (verbose) { - getLog().info("writing third-party file : " + thirdPartyFile); - } - if (keepBackup && thirdPartyFile.exists()) { - if (verbose) { - getLog().info("backup " + thirdPartyFile); - } - backupFile(thirdPartyFile); - } - writeFile(thirdPartyFile, thirdPartyFileContent, encoding); - } - if (copyToMETA_INF) { - copyFile(thirdPartyFile, new File(outputDirectory, "META-INF" + File.separator + project.getArtifactId() + "-" + thirdPartyFile.getName())); - } - addResourceDir(outputDirectory,"**/*.txt"); - } - - /** @return resolve the dependency tree */ - protected DependencyNode resolveProject() { - try { - ArtifactFilter artifactFilter = new ScopeArtifactFilter(Artifact.SCOPE_TEST); - return dependencyTreeBuilder.buildDependencyTree(project, localRepository, factory, - artifactMetadataSource, artifactFilter, collector); - } catch (DependencyTreeBuilderException e) { - getLog().error("Unable to build dependency tree.", e); - return null; - } - } - - protected void buildLicenseMap(DependencyNode node, LicenseMap licenseMap) { - if (node.getState() != DependencyNode.INCLUDED) { - // this dependency is not included, so do not treate it - if (verbose) { - getLog().info("do not include this dependency " + node.toNodeString()); - } - return; - } - Artifact artifact = node.getArtifact(); - - if (verbose && getLog().isDebugEnabled()) { - getLog().debug("treate node " + node.toNodeString()); - } - - if (!Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { - try { - MavenProject artifactProject = getMavenProjectFromRepository(artifact); - String artifactName = getArtifactName(artifactProject); - - List<?> licenses = artifactProject.getLicenses(); - - if (licenses.isEmpty()) { - // no license found for the dependency - licenseMap.put(unknownLicenseMessage, artifactName); - - } else { - for (Object o : licenses) { - if (o == null) { - getLog().warn("could not acquire the license for " + artifactName); - continue; - } - License license = (License) o; - String licenseKey = license.getName(); - if (license.getName() == null) { - licenseKey = license.getUrl(); - } - licenseMap.put(licenseKey, artifactName); - } - } - } catch (ProjectBuildingException e) { - getLog().error("ProjectBuildingException error : ", e); - } - } - if (!node.getChildren().isEmpty()) { - for (Object o : node.getChildren()) { - buildLicenseMap((DependencyNode) o, licenseMap); - } - } - } - - protected String buildGroupedLicenses(LicenseMap licenseMap) { - StringBuilder sb = new StringBuilder(); - sb.append("List of third-party dependencies grouped by their license type."); - for (String licenseName : licenseMap.keySet()) { - sb.append("\n\n").append(licenseName).append(" : "); - - SortedSet<String> projects = licenseMap.get(licenseName); - - for (String projectName : projects) { - sb.append("\n * ").append(projectName); - } - } - return sb.toString(); - } - - protected String getArtifactName(MavenProject artifactProject) { - StringBuilder sb = new StringBuilder(); - - sb.append(artifactProject.getName()); - sb.append(" ("); - sb.append(artifactProject.getGroupId()); - sb.append(":"); - sb.append(artifactProject.getArtifactId()); - sb.append(":"); - sb.append(artifactProject.getVersion()); - sb.append(" - "); - String url = artifactProject.getUrl(); - sb.append(url == null ? "no url defined" : url); - sb.append(")"); - - return sb.toString(); - } - - /** - * Get the <code>Maven project</code> from the repository depending the <code>Artifact</code> given. - * - * @param artifact an artifact - * @return the Maven project for the given artifact - * @throws ProjectBuildingException if any - */ - protected MavenProject getMavenProjectFromRepository(Artifact artifact) - throws ProjectBuildingException { - - boolean allowStubModel = false; - - if (!"pom".equals(artifact.getType())) { - artifact = factory.createProjectArtifact(artifact.getGroupId(), artifact.getArtifactId(), - artifact.getVersion(), artifact.getScope()); - allowStubModel = true; - } - - // TODO: we should use the MavenMetadataSource instead - return mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository, - allowStubModel); - } - - protected class LicenseMap extends java.util.TreeMap<String, SortedSet<String>> { - - private static final long serialVersionUID = 864199843545688069L; - - public SortedSet<String> put(String key, String value) { - // handle multiple values as a set to avoid duplicates - SortedSet<String> valueList = get(key); - if (valueList == null) { - valueList = new TreeSet<String>(); - } - if (getLog().isDebugEnabled()) { - getLog().debug("key:" + key + ",value: " + value); - } - valueList.add(value); - return put(key, valueList); - } - } - - @Override - public boolean isVerbose() { - return verbose; - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - @Override - public MavenProject getProject() { - return project; - } - - @Override - public void setProject(MavenProject project) { - this.project = project; - } -} Copied: trunk/src/main/java/org/nuiton/license/plugin/GeneratorListMojo.java (from rev 1675, trunk/src/main/java/org/nuiton/license/plugin/GeneratorListPlugin.java) =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/GeneratorListMojo.java (rev 0) +++ trunk/src/main/java/org/nuiton/license/plugin/GeneratorListMojo.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -0,0 +1,82 @@ +/* + * *##% + * Maven License Plugin + * Copyright (C) 2008 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.license.plugin; + +import java.util.Map; +import java.util.Map.Entry; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.nuiton.license.plugin.header.generator.HeaderGenerator; + +/** + * Displays all the available generators. + * + * @author chemit + * + * @requiresProject false + * @requiresDirectInvocation + * @goal generator-list + * + * @since 1.0.1 + * + */ +public class GeneratorListMojo extends AbstractMojo { + + /** + * Un drapeau pour afficher aussi le contenu des license. + * + * @parameter expression="${detail}" + * @since 1.0.1 + */ + protected boolean detail; + /** + * All available generators + * + * @component role="org.nuiton.license.header.generator.HeaderGenerator" + */ + protected Map<String, HeaderGenerator> _generators; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + + // display it + StringBuilder buffer = new StringBuilder("\n"); + buffer.append("\n\n-------------------------------------------------------------------------------\n"); + buffer.append(" maven-license-plugin\n"); + buffer.append("-------------------------------------------------------------------------------\n\n"); + if (_generators == null || _generators.isEmpty()) { + buffer.append("No generator found.\n\n"); + } else { + buffer.append("List of available generators :\n\n"); + for (Entry<String, HeaderGenerator> stringHeaderGeneratorEntry : _generators.entrySet()) { + Entry<String, HeaderGenerator> e = stringHeaderGeneratorEntry; + HeaderGenerator generator = e.getValue(); + buffer.append(" - ").append(e.getKey()).append(" : ").append(generator.getDescription()); + buffer.append("\n"); + if (detail) { + buffer.append("\n example : \n").append(generator.getHeader("content ")).append('\n'); + } + } + } + getLog().info(buffer.toString()); + } +} Property changes on: trunk/src/main/java/org/nuiton/license/plugin/GeneratorListMojo.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Added: svn:mergeinfo + Deleted: trunk/src/main/java/org/nuiton/license/plugin/GeneratorListPlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/GeneratorListPlugin.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/main/java/org/nuiton/license/plugin/GeneratorListPlugin.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,82 +0,0 @@ -/* - * *##% - * Maven License Plugin - * Copyright (C) 2008 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.license.plugin; - -import java.util.Map; -import java.util.Map.Entry; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.nuiton.license.plugin.header.generator.HeaderGenerator; - -/** - * Displays all the available generators. - * - * @author chemit - * - * @requiresProject false - * @requiresDirectInvocation - * @goal generator-list - * - * @since 1.0.1 - * - */ -public class GeneratorListPlugin extends AbstractMojo { - - /** - * Un drapeau pour afficher aussi le contenu des license. - * - * @parameter expression="${detail}" - * @since 1.0.1 - */ - protected boolean detail; - /** - * All available generators - * - * @component role="org.nuiton.license.header.generator.HeaderGenerator" - */ - protected Map<String, HeaderGenerator> _generators; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - - // display it - StringBuilder buffer = new StringBuilder("\n"); - buffer.append("\n\n-------------------------------------------------------------------------------\n"); - buffer.append(" maven-license-plugin\n"); - buffer.append("-------------------------------------------------------------------------------\n\n"); - if (_generators == null || _generators.isEmpty()) { - buffer.append("No generator found.\n\n"); - } else { - buffer.append("List of available generators :\n\n"); - for (Entry<String, HeaderGenerator> stringHeaderGeneratorEntry : _generators.entrySet()) { - Entry<String, HeaderGenerator> e = stringHeaderGeneratorEntry; - HeaderGenerator generator = e.getValue(); - buffer.append(" - ").append(e.getKey()).append(" : ").append(generator.getDescription()); - buffer.append("\n"); - if (detail) { - buffer.append("\n example : \n").append(generator.getHeader("content ")).append('\n'); - } - } - } - getLog().info(buffer.toString()); - } -} Copied: trunk/src/main/java/org/nuiton/license/plugin/LicenseListMojo.java (from rev 1674, trunk/src/main/java/org/nuiton/license/plugin/LicenseListPlugin.java) =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/LicenseListMojo.java (rev 0) +++ trunk/src/main/java/org/nuiton/license/plugin/LicenseListMojo.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -0,0 +1,100 @@ +/* + * *##% + * Maven License Plugin + * Copyright (C) 2008 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.license.plugin; + +import java.io.IOException; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import org.nuiton.license.plugin.repository.License; +import org.nuiton.license.plugin.repository.LicenseDefinition; +import org.nuiton.license.plugin.repository.LicenseRepository; +import org.nuiton.license.plugin.repository.LicenseRepositoryFactory; + +/** + * Display all available licenses. + * + * @author chemit + * @goal license-list + * @requiresProject false + * @requiresDirectInvocation + * + * @since 1.0.1 + */ +public class LicenseListMojo extends AbstractMojo { + + /** + * La baseURL d'un resolver de license supplementaire + * + * @parameter expression="${extraResolver}" + * @since 1.0.1 + */ + protected String extraResolver; + /** + * Encoding a utiliser pour lire et ecrire les fichiers. + * + * @parameter expression="${encoding}" default-value="UTF-8" + * @required + * @since 1.0.0 + */ + protected String encoding; + /** + * Un drapeau pour afficher aussi le contenu des license. + * + * @parameter expression="${detail}" + * @since 1.0.1 + */ + protected boolean detail; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + StringBuilder buffer = new StringBuilder(); + buffer.append("\n\n-------------------------------------------------------------------------------\n"); + buffer.append(" maven-license-plugin\n"); + buffer.append("-------------------------------------------------------------------------------\n\n"); + buffer.append("Available licenses :\n\n"); + + LicenseRepository factory; + try { + factory = LicenseRepositoryFactory.newLicenseRepository(true, true, extraResolver); + } catch (IllegalArgumentException ex) { + throw new MojoExecutionException("could not obtain the license repository", ex); + } catch (IOException ex) { + throw new MojoExecutionException("could not obtain the license repository", ex); + } + + for (LicenseDefinition entry : factory.getDefinitions()) { + String licenseName = entry.getName(); + buffer.append(" * ").append(licenseName).append(" : ").append(entry.getDescription()).append('\n'); + if (detail) { + try { + + License license = factory.getLicense(licenseName); + buffer.append("\n").append(license.getHeaderContent(encoding)).append("\n\n"); + } catch (IOException ex) { + throw new MojoExecutionException("could not instanciate license with name " + licenseName + " for reason " + ex.getMessage(), ex); + } + } + } + getLog().info(buffer.toString()); + } +} Property changes on: trunk/src/main/java/org/nuiton/license/plugin/LicenseListMojo.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Added: svn:mergeinfo + Deleted: trunk/src/main/java/org/nuiton/license/plugin/LicenseListPlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/LicenseListPlugin.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/main/java/org/nuiton/license/plugin/LicenseListPlugin.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,100 +0,0 @@ -/* - * *##% - * Maven License Plugin - * Copyright (C) 2008 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.license.plugin; - -import java.io.IOException; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; - -import org.nuiton.license.plugin.repository.License; -import org.nuiton.license.plugin.repository.LicenseDefinition; -import org.nuiton.license.plugin.repository.LicenseRepository; -import org.nuiton.license.plugin.repository.LicenseRepositoryFactory; - -/** - * Display all available licenses. - * - * @author chemit - * @goal license-list - * @requiresProject false - * @requiresDirectInvocation - * - * @since 1.0.1 - */ -public class LicenseListPlugin extends AbstractMojo { - - /** - * La baseURL d'un resolver de license supplementaire - * - * @parameter expression="${extraResolver}" - * @since 1.0.1 - */ - protected String extraResolver; - /** - * Encoding a utiliser pour lire et ecrire les fichiers. - * - * @parameter expression="${encoding}" default-value="UTF-8" - * @required - * @since 1.0.0 - */ - protected String encoding; - /** - * Un drapeau pour afficher aussi le contenu des license. - * - * @parameter expression="${detail}" - * @since 1.0.1 - */ - protected boolean detail; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - StringBuilder buffer = new StringBuilder(); - buffer.append("\n\n-------------------------------------------------------------------------------\n"); - buffer.append(" maven-license-plugin\n"); - buffer.append("-------------------------------------------------------------------------------\n\n"); - buffer.append("Available licenses :\n\n"); - - LicenseRepository factory; - try { - factory = LicenseRepositoryFactory.newLicenseRepository(true, true, extraResolver); - } catch (IllegalArgumentException ex) { - throw new MojoExecutionException("could not obtain the license repository", ex); - } catch (IOException ex) { - throw new MojoExecutionException("could not obtain the license repository", ex); - } - - for (LicenseDefinition entry : factory.getDefinitions()) { - String licenseName = entry.getName(); - buffer.append(" * ").append(licenseName).append(" : ").append(entry.getDescription()).append('\n'); - if (detail) { - try { - - License license = factory.getLicense(licenseName); - buffer.append("\n").append(license.getHeaderContent(encoding)).append("\n\n"); - } catch (IOException ex) { - throw new MojoExecutionException("could not instanciate license with name " + licenseName + " for reason " + ex.getMessage(), ex); - } - } - } - getLog().info(buffer.toString()); - } -} Copied: trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderMojo.java (from rev 1675, trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderPlugin.java) =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderMojo.java (rev 0) +++ trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderMojo.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -0,0 +1,467 @@ +/* + * *##% + * Maven License Plugin + * Copyright (C) 2008 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.license.plugin; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.project.MavenProject; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.context.Context; +import org.codehaus.plexus.velocity.VelocityComponent; +import org.nuiton.license.plugin.header.generator.HeaderGenerator; +import org.nuiton.license.plugin.repository.License; +import org.nuiton.license.plugin.repository.LicenseRepository; +import org.nuiton.license.plugin.repository.LicenseRepositoryFactory; +import org.nuiton.plugin.AbstractPlugin; +import org.nuiton.plugin.PluginHelper; +import org.nuiton.processor.LicenseProcessor; + +import java.io.File; +import java.io.StringWriter; +import java.util.*; +import java.util.Map.Entry; + +/** + * The goal to update (or add) the licence header on some files. + * + * @author chemit + * @requiresProject true + * @goal update-header + * @since 1.0.1 + */ +public class UpdateHeaderMojo extends AbstractPlugin { + + /** + * Dependance du projet. + * + * @parameter default-value="${project}" + * @required + * @since 1.0.0 + */ + protected MavenProject project; + /** + * Encoding a utiliser pour lire et ecrire les fichiers. + * + * @parameter expression="${license.encoding}" default-value="${project.build.sourceEncoding}" + * @required + * @since 1.0.0 + */ + protected String encoding; + /** + * l'annee de creation du module (sera place dans le header) + * + * @parameter expression="${license.inceptionYear}" default-value="${project.inceptionYear}" + * @required + * @since 1.0.0 + */ + protected String inceptionYear; + /** + * le nom de l'organisation (sera place dans le header) + * + * @parameter expression="${license.organizationName}" default-value="${project.organization.name}" + * @required + * @since 1.0.0 + */ + protected String organizationName; + /** + * le nom du projet (sera place dans le header) + * + * @parameter expression="${license.projectName}" default-value="${project.name}" + * @required + * @since 1.0.0 + */ + protected String projectName; + /** + * Le type de license a appliquer. + * + * @parameter expression="${license.licenseName}" + * @required + * @since 1.0.0 + */ + protected String licenseName; + /** + * Le type de générateur a utiliser pour encapsuler le header. + * <p/> + * Par défaut, on veut utiliser le plugin sur des fichiers sources java. + * + * @parameter expression="${license.generatorName}" default-value="license-java" + * @required + * @since 1.0.1 + */ + protected String generatorName; + /** + * La liste des patterns de fichiers à inclure (séparés par des virgules). + * <p/> + * Exemple : <code>**\/*.java,**\/*.properties</code> + * <p/> + * On recherchera alors les fichiers respectant l'un des patterns dans + * tous les répertoires de sources et de tests. + * <p/> + * Par défaut, on veut utiliser le plugin sur des fichiers sources java. + * + * @parameter expression="${license.includes}" default-value="**\/*.java" + * @required + * @since 1.0.1 + */ + protected String includes = "**/*.java"; + /** + * La liste des patterns de fichiers à exclure (séparés par des virgules). + * <p/> + * Exemple : <code>**\/*.java,**\/*.properties</code> + * <p/> + * On recherchera alors les fichiers respectant l'un des patterns dans + * tous les répertoires de sources et de tests. + * <p/> + * Par défaut, on n'exclue rien. + * + * @parameter expression="${license.excludes}" + * @since 1.0.1 + */ + protected String excludes; + /** + * Repertoires des fichiers sources a traiter. + * + * @parameter expression="${license.compileSourceRoots}" default-value="${project.compileSourceRoots}" + * @required + * @since 1.0.0 + */ + protected List<String> compileSourceRoots; + /** + * Repertoires des fichiers sources de test a traiter. + * + * @parameter expression="${license.testCompileSourceRoots}" default-value="${project.testCompileSourceRoots}" + * @required + * @since 1.0.0 + */ + protected List<String> testCompileSourceRoots; + /** + * Un resolver externe + * + * @parameter expression="${license.licenseResolver}" + * @since 1.0.0 + */ + protected String licenseResolver; + /** + * La template (velocity) a utiliser pour construire le header. + * <p/> + * Cette template doit être dans le class-path ou être un fichier existant + * + * @parameter expression="${license.template}" default-value="/license/defaultHeader.vm" + * @since 1.0.1 + */ + protected String template; + /** + * Des paramètres supplémentaires à utiliser dans la template du header. + * + * @parameter + * @since 1.0.1 + */ + protected Map<String, String> templateParameters; + /** + * Un flag pour conserver un backup des fichiers modifies. + * + * @parameter expression="${license.keepBackup}" default-value="false" + * @since 1.0.0 + */ + protected boolean keepBackup; + /** + * Un flag pour activer le mode verbeux. + * + * @parameter expression="${license.verbose}" default-value="${maven.verbose}" + * @since 1.0.0 + */ + protected boolean verbose; + /** + * A flag to skip the goal. + * + * @parameter expression="${skipUpdateHeader}" default-value="false" + * @since 1.0.3 + */ + protected boolean skipUpdateHeader; + /** + * A flag to test plugin but modify no file. + * + * @parameter expression="${dryRun}" default-value="false" + * @since 1.0.3 + */ + protected boolean dryRun; + /** + * Velocity Component. + * + * @component roleHint="maven-license-plugin" + * @since 2.0.0 + */ + protected VelocityComponent velocity; + /** + * All available generators + * + * @component role="org.nuiton.license.plugin.header.generator.HeaderGenerator" + */ + protected Map<String, HeaderGenerator> _generators; + /** + * le header a ajouter dans chaque fichier source java + */ + protected String licenseHeaderContent; + /** + * le header complet (avec les balises de commentaires) + */ + protected String boxedLicenseHeaderContent; + /** + * la liste des chemin relatifs des sources java a traiter pour chaque repertoire contenant des sources + */ + protected Map<File, String[]> filesToTreate; + /** + * le timestamp utilise pour la generation + */ + protected long timestamp; + + @Override + public boolean isVerbose() { + return verbose; + } + + @Override + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + @Override + public MavenProject getProject() { + return project; + } + + @Override + public void setProject(MavenProject project) { + this.project = project; + } + + @Override + public boolean checkPackaging() { + return true; + } + + @Override + protected boolean checkSkip() { + if (skipUpdateHeader) { + getLog().info("skip flag is on, will skip goal."); + return false; + } + if (filesToTreate == null || filesToTreate.isEmpty()) { + getLog().info("No file to treate, will skip goal."); + return false; + } + return super.checkSkip(); + } + + @Override + public void init() throws Exception { + + if (skipUpdateHeader) { + return; + } + timestamp = System.nanoTime(); + + if (_generators == null) { + // should never happen... + throw new MojoExecutionException("no header generator found"); + } + if (verbose) { + for (Entry<String, HeaderGenerator> stringHeaderGeneratorEntry : _generators.entrySet()) { + Entry<String, HeaderGenerator> next = stringHeaderGeneratorEntry; + getLog().info("config - available generator : " + next.getKey()); + } + } + + if (!_generators.containsKey(generatorName.trim())) { + throw new MojoExecutionException("the generator named '" + generatorName + "' is unknown (use generator-list goal to see all of them)"); + } + HeaderGenerator generator = _generators.get(generatorName); + + // obtain all files to be treated + + filesToTreate = new HashMap<File, String[]>(); + String[] in = includes.split(","); + String[] ex = excludes == null ? null : excludes.split(","); + getFilesToTreateForRoots(in, ex, compileSourceRoots, filesToTreate, null); + getFilesToTreateForRoots(in, ex, testCompileSourceRoots, filesToTreate, null); + + if (filesToTreate.isEmpty()) { + return; + } + + File templateFile = new File(template); + + // verifie que la template existe (dans le class-path ou en tant que fichier) + checkResource(templateFile); + + // recuperation de la license a utiliser + LicenseRepository factory = LicenseRepositoryFactory.newLicenseRepository(true, true, licenseResolver); + License license = factory.getLicense(licenseName); + + if (verbose) { + getLog().info("config - use license " + license.getName()); + getLog().info("config - use generator " + generator.getName()); + getLog().info("config - use template " + template); + } + // obtain content of license header + licenseHeaderContent = computeHeader(license, generator); + + // build the comment boxed header content + boxedLicenseHeaderContent = generator.getHeader(licenseHeaderContent); + if (verbose) { + getLog().info("config - header to use\n" + boxedLicenseHeaderContent); + } + + } + + @Override + protected void doAction() throws Exception { + + // create a licence processor with given header + LicenseProcessor p = new LicenseProcessor(licenseHeaderContent); + + for (Entry<File, String[]> entry : filesToTreate.entrySet()) { + File src = entry.getKey(); + for (String javaRelativePath : entry.getValue()) { + File file = new File(src, javaRelativePath); + + if (verbose) { + getLog().info("process file " + file); + } + + // file where to writeFile result + File processFile = new File(file.getAbsolutePath() + "_" + timestamp); + + try { + p.process(file, processFile); + boolean foundLicenseHeader = p.getLicenceFilter().wasTouched(); + + if (!foundLicenseHeader) { + if (p.getLicenceFilter().isDetectHeader()) { + getLog().warn("skip file " + file + " (no license footer tag found : '##%*' !)"); + } else { + // no license header found in file, add it + getLog().info("adding license header on file " + file); + String content = PluginHelper.readAsString(file, encoding); + content = boxedLicenseHeaderContent + content; + if (!dryRun) { + writeFile(processFile, content, encoding); + } + } + } + + if (keepBackup && !dryRun) { + File backupFile = new File(file.getAbsolutePath() + "~"); + if (verbose) { + getLog().debug("backup original file " + file); + } + renameFile(file, backupFile); + } + if (dryRun) { + deleteFile(processFile); + } else { + renameFile(processFile, file); + + } + + } catch (Exception e) { + getLog().warn("skip file " + file + " (could not process for reason : " + e.getMessage() + ")"); + deleteFile(processFile); + } finally { + // toujours cleaner les états du filtre du processeur + p.getLicenceFilter().reset(); + } + } + } + } + + /** + * Construction du header a utiliser. + * <p/> + * Le header est généré à partir de la template velocity donnée et de la + * license donnée. + * + * @param license the license to use to compute header + * @param generator the header generator used to compute header + * @return le header construit + * @throws Exception pour toute erreur pendant la construction du header + */ + protected String computeHeader(License license, HeaderGenerator generator) throws Exception { + + // recuperation de la license a mettre dans le header + String licenseContent = license.getHeaderContent(encoding); + + // defined inceptionYear (if year is older than now suffix with a - thisYear) + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + String thisYear = cal.get(Calendar.YEAR) + ""; + if (!thisYear.equals(inceptionYear)) { + inceptionYear = inceptionYear + " - " + thisYear; + } + + // preparation de l'environnement velocity + + Context context = new VelocityContext(); + + context.put("inceptionYear", inceptionYear); + context.put("projectName", projectName); + context.put("organizationName", organizationName); + context.put("licenseContent", licenseContent); + + if (templateParameters != null) { + for (Entry<String, String> e : templateParameters.entrySet()) { + context.put(e.getKey(), e.getValue()); + } + } + + if (verbose) { + StringBuilder buffer = new StringBuilder(); + + buffer.append("config - parameters for template : "); + for (Object key : context.getKeys()) { + buffer.append("\n * ").append(key).append(" : ").append(context.get(key + "")); + } + getLog().info(buffer.toString()); + } + + // generation du contenu via velocity + VelocityEngine engine = velocity.getEngine(); + + StringWriter writer = new StringWriter(); + + Template velocityTemplate = engine.getTemplate(template, encoding); + + velocityTemplate.merge(context, writer); + + writer.flush(); + + writer.close(); + + // recuperation du contenu du texte genere + String r = writer.getBuffer().toString(); + + // prefixage de toutes les lignes par un " * " + String result = generator.prefixContent(r.trim() + "\n\n"); + + return '\n' + result; + } +} Property changes on: trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderMojo.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Added: svn:mergeinfo + Deleted: trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderPlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderPlugin.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/main/java/org/nuiton/license/plugin/UpdateHeaderPlugin.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,467 +0,0 @@ -/* - * *##% - * Maven License Plugin - * Copyright (C) 2008 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.license.plugin; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.context.Context; -import org.codehaus.plexus.velocity.VelocityComponent; -import org.nuiton.license.plugin.header.generator.HeaderGenerator; -import org.nuiton.license.plugin.repository.License; -import org.nuiton.license.plugin.repository.LicenseRepository; -import org.nuiton.license.plugin.repository.LicenseRepositoryFactory; -import org.nuiton.plugin.AbstractPlugin; -import org.nuiton.plugin.PluginHelper; -import org.nuiton.processor.LicenseProcessor; - -import java.io.File; -import java.io.StringWriter; -import java.util.*; -import java.util.Map.Entry; - -/** - * The goal to update (or add) the licence header on some files. - * - * @author chemit - * @requiresProject true - * @goal update-header - * @since 1.0.1 - */ -public class UpdateHeaderPlugin extends AbstractPlugin { - - /** - * Dependance du projet. - * - * @parameter default-value="${project}" - * @required - * @since 1.0.0 - */ - protected MavenProject project; - /** - * Encoding a utiliser pour lire et ecrire les fichiers. - * - * @parameter expression="${license.encoding}" default-value="${project.build.sourceEncoding}" - * @required - * @since 1.0.0 - */ - protected String encoding; - /** - * l'annee de creation du module (sera place dans le header) - * - * @parameter expression="${license.inceptionYear}" default-value="${project.inceptionYear}" - * @required - * @since 1.0.0 - */ - protected String inceptionYear; - /** - * le nom de l'organisation (sera place dans le header) - * - * @parameter expression="${license.organizationName}" default-value="${project.organization.name}" - * @required - * @since 1.0.0 - */ - protected String organizationName; - /** - * le nom du projet (sera place dans le header) - * - * @parameter expression="${license.projectName}" default-value="${project.name}" - * @required - * @since 1.0.0 - */ - protected String projectName; - /** - * Le type de license a appliquer. - * - * @parameter expression="${license.licenseName}" - * @required - * @since 1.0.0 - */ - protected String licenseName; - /** - * Le type de générateur a utiliser pour encapsuler le header. - * <p/> - * Par défaut, on veut utiliser le plugin sur des fichiers sources java. - * - * @parameter expression="${license.generatorName}" default-value="license-java" - * @required - * @since 1.0.1 - */ - protected String generatorName; - /** - * La liste des patterns de fichiers à inclure (séparés par des virgules). - * <p/> - * Exemple : <code>**\/*.java,**\/*.properties</code> - * <p/> - * On recherchera alors les fichiers respectant l'un des patterns dans - * tous les répertoires de sources et de tests. - * <p/> - * Par défaut, on veut utiliser le plugin sur des fichiers sources java. - * - * @parameter expression="${license.includes}" default-value="**\/*.java" - * @required - * @since 1.0.1 - */ - protected String includes = "**/*.java"; - /** - * La liste des patterns de fichiers à exclure (séparés par des virgules). - * <p/> - * Exemple : <code>**\/*.java,**\/*.properties</code> - * <p/> - * On recherchera alors les fichiers respectant l'un des patterns dans - * tous les répertoires de sources et de tests. - * <p/> - * Par défaut, on n'exclue rien. - * - * @parameter expression="${license.excludes}" - * @since 1.0.1 - */ - protected String excludes; - /** - * Repertoires des fichiers sources a traiter. - * - * @parameter expression="${license.compileSourceRoots}" default-value="${project.compileSourceRoots}" - * @required - * @since 1.0.0 - */ - protected List<String> compileSourceRoots; - /** - * Repertoires des fichiers sources de test a traiter. - * - * @parameter expression="${license.testCompileSourceRoots}" default-value="${project.testCompileSourceRoots}" - * @required - * @since 1.0.0 - */ - protected List<String> testCompileSourceRoots; - /** - * Un resolver externe - * - * @parameter expression="${license.licenseResolver}" - * @since 1.0.0 - */ - protected String licenseResolver; - /** - * La template (velocity) a utiliser pour construire le header. - * <p/> - * Cette template doit être dans le class-path ou être un fichier existant - * - * @parameter expression="${license.template}" default-value="/license/defaultHeader.vm" - * @since 1.0.1 - */ - protected String template; - /** - * Des paramètres supplémentaires à utiliser dans la template du header. - * - * @parameter - * @since 1.0.1 - */ - protected Map<String, String> templateParameters; - /** - * Un flag pour conserver un backup des fichiers modifies. - * - * @parameter expression="${license.keepBackup}" default-value="false" - * @since 1.0.0 - */ - protected boolean keepBackup; - /** - * Un flag pour activer le mode verbeux. - * - * @parameter expression="${license.verbose}" default-value="${maven.verbose}" - * @since 1.0.0 - */ - protected boolean verbose; - /** - * A flag to skip the goal. - * - * @parameter expression="${skipUpdateHeader}" default-value="false" - * @since 1.0.3 - */ - protected boolean skipUpdateHeader; - /** - * A flag to test plugin but modify no file. - * - * @parameter expression="${dryRun}" default-value="false" - * @since 1.0.3 - */ - protected boolean dryRun; - /** - * Velocity Component. - * - * @component roleHint="maven-license-plugin" - * @since 2.0.0 - */ - protected VelocityComponent velocity; - /** - * All available generators - * - * @component role="org.nuiton.license.plugin.header.generator.HeaderGenerator" - */ - protected Map<String, HeaderGenerator> _generators; - /** - * le header a ajouter dans chaque fichier source java - */ - protected String licenseHeaderContent; - /** - * le header complet (avec les balises de commentaires) - */ - protected String boxedLicenseHeaderContent; - /** - * la liste des chemin relatifs des sources java a traiter pour chaque repertoire contenant des sources - */ - protected Map<File, String[]> filesToTreate; - /** - * le timestamp utilise pour la generation - */ - protected long timestamp; - - @Override - public boolean isVerbose() { - return verbose; - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - @Override - public MavenProject getProject() { - return project; - } - - @Override - public void setProject(MavenProject project) { - this.project = project; - } - - @Override - public boolean checkPackaging() { - return true; - } - - @Override - protected boolean checkSkip() { - if (skipUpdateHeader) { - getLog().info("skip flag is on, will skip goal."); - return false; - } - if (filesToTreate == null || filesToTreate.isEmpty()) { - getLog().info("No file to treate, will skip goal."); - return false; - } - return super.checkSkip(); - } - - @Override - public void init() throws Exception { - - if (skipUpdateHeader) { - return; - } - timestamp = System.nanoTime(); - - if (_generators == null) { - // should never happen... - throw new MojoExecutionException("no header generator found"); - } - if (verbose) { - for (Entry<String, HeaderGenerator> stringHeaderGeneratorEntry : _generators.entrySet()) { - Entry<String, HeaderGenerator> next = stringHeaderGeneratorEntry; - getLog().info("config - available generator : " + next.getKey()); - } - } - - if (!_generators.containsKey(generatorName.trim())) { - throw new MojoExecutionException("the generator named '" + generatorName + "' is unknown (use generator-list goal to see all of them)"); - } - HeaderGenerator generator = _generators.get(generatorName); - - // obtain all files to be treated - - filesToTreate = new HashMap<File, String[]>(); - String[] in = includes.split(","); - String[] ex = excludes == null ? null : excludes.split(","); - getFilesToTreateForRoots(in, ex, compileSourceRoots, filesToTreate, null); - getFilesToTreateForRoots(in, ex, testCompileSourceRoots, filesToTreate, null); - - if (filesToTreate.isEmpty()) { - return; - } - - File templateFile = new File(template); - - // verifie que la template existe (dans le class-path ou en tant que fichier) - checkResource(templateFile); - - // recuperation de la license a utiliser - LicenseRepository factory = LicenseRepositoryFactory.newLicenseRepository(true, true, licenseResolver); - License license = factory.getLicense(licenseName); - - if (verbose) { - getLog().info("config - use license " + license.getName()); - getLog().info("config - use generator " + generator.getName()); - getLog().info("config - use template " + template); - } - // obtain content of license header - licenseHeaderContent = computeHeader(license, generator); - - // build the comment boxed header content - boxedLicenseHeaderContent = generator.getHeader(licenseHeaderContent); - if (verbose) { - getLog().info("config - header to use\n" + boxedLicenseHeaderContent); - } - - } - - @Override - protected void doAction() throws Exception { - - // create a licence processor with given header - LicenseProcessor p = new LicenseProcessor(licenseHeaderContent); - - for (Entry<File, String[]> entry : filesToTreate.entrySet()) { - File src = entry.getKey(); - for (String javaRelativePath : entry.getValue()) { - File file = new File(src, javaRelativePath); - - if (verbose) { - getLog().info("process file " + file); - } - - // file where to writeFile result - File processFile = new File(file.getAbsolutePath() + "_" + timestamp); - - try { - p.process(file, processFile); - boolean foundLicenseHeader = p.getLicenceFilter().wasTouched(); - - if (!foundLicenseHeader) { - if (p.getLicenceFilter().isDetectHeader()) { - getLog().warn("skip file " + file + " (no license footer tag found : '##%*' !)"); - } else { - // no license header found in file, add it - getLog().info("adding license header on file " + file); - String content = PluginHelper.readAsString(file, encoding); - content = boxedLicenseHeaderContent + content; - if (!dryRun) { - writeFile(processFile, content, encoding); - } - } - } - - if (keepBackup && !dryRun) { - File backupFile = new File(file.getAbsolutePath() + "~"); - if (verbose) { - getLog().debug("backup original file " + file); - } - renameFile(file, backupFile); - } - if (dryRun) { - deleteFile(processFile); - } else { - renameFile(processFile, file); - - } - - } catch (Exception e) { - getLog().warn("skip file " + file + " (could not process for reason : " + e.getMessage() + ")"); - deleteFile(processFile); - } finally { - // toujours cleaner les états du filtre du processeur - p.getLicenceFilter().reset(); - } - } - } - } - - /** - * Construction du header a utiliser. - * <p/> - * Le header est généré à partir de la template velocity donnée et de la - * license donnée. - * - * @param license the license to use to compute header - * @param generator the header generator used to compute header - * @return le header construit - * @throws Exception pour toute erreur pendant la construction du header - */ - protected String computeHeader(License license, HeaderGenerator generator) throws Exception { - - // recuperation de la license a mettre dans le header - String licenseContent = license.getHeaderContent(encoding); - - // defined inceptionYear (if year is older than now suffix with a - thisYear) - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date()); - String thisYear = cal.get(Calendar.YEAR) + ""; - if (!thisYear.equals(inceptionYear)) { - inceptionYear = inceptionYear + " - " + thisYear; - } - - // preparation de l'environnement velocity - - Context context = new VelocityContext(); - - context.put("inceptionYear", inceptionYear); - context.put("projectName", projectName); - context.put("organizationName", organizationName); - context.put("licenseContent", licenseContent); - - if (templateParameters != null) { - for (Entry<String, String> e : templateParameters.entrySet()) { - context.put(e.getKey(), e.getValue()); - } - } - - if (verbose) { - StringBuilder buffer = new StringBuilder(); - - buffer.append("config - parameters for template : "); - for (Object key : context.getKeys()) { - buffer.append("\n * ").append(key).append(" : ").append(context.get(key + "")); - } - getLog().info(buffer.toString()); - } - - // generation du contenu via velocity - VelocityEngine engine = velocity.getEngine(); - - StringWriter writer = new StringWriter(); - - Template velocityTemplate = engine.getTemplate(template, encoding); - - velocityTemplate.merge(context, writer); - - writer.flush(); - - writer.close(); - - // recuperation du contenu du texte genere - String r = writer.getBuffer().toString(); - - // prefixage de toutes les lignes par un " * " - String result = generator.prefixContent(r.trim() + "\n\n"); - - return '\n' + result; - } -} Modified: trunk/src/main/java/org/nuiton/license/plugin/header/generator/XmlLicenseHeaderGeneratorImpl.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/header/generator/XmlLicenseHeaderGeneratorImpl.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/main/java/org/nuiton/license/plugin/header/generator/XmlLicenseHeaderGeneratorImpl.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -23,7 +23,7 @@ import org.nuiton.processor.filters.LicenseFilter; /** - * Le header pour les fichiers xml. + * Le generateur de header pour des fichiers xml. * * @author chemit * @since 1.0.1 Deleted: trunk/src/main/resources/META-INF/services/org.nuiton.license.header.generator.HeaderGenerator =================================================================== --- trunk/src/main/resources/META-INF/services/org.nuiton.license.header.generator.HeaderGenerator 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/main/resources/META-INF/services/org.nuiton.license.header.generator.HeaderGenerator 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,3 +0,0 @@ -org.nuiton.license.header.generator.impl.JavaHeaderGenerator -org.nuiton.license.header.generator.impl.XmlHeaderGenerator -org.nuiton.license.header.generator.impl.PropertiesHeaderGenerator Copied: trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFileMojoTest.java (from rev 1674, trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFilePluginTest.java) =================================================================== --- trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFileMojoTest.java (rev 0) +++ trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFileMojoTest.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -0,0 +1,107 @@ +/* + * *##% + * Maven helper plugin + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.license.plugin; + +import static org.junit.Assert.*; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import org.nuiton.plugin.AbstractMojoTest; + +public class AddLicenseFileMojoTest extends AbstractMojoTest<AddLicenseFileMojo> { + + @Override + protected String getGoalName(String methodName) { + return "add-license"; + } + + @Override + protected void setUpMojo(AddLicenseFileMojo mojo, File pomFile) throws Exception { + super.setUpMojo(mojo, pomFile); + // license is where the pom is + File outputDirectory = pomFile.getParentFile(); + mojo.setOutputDirectory(outputDirectory); + if (!outputDirectory.exists()) { + if (!outputDirectory.mkdirs()) { + throw new IOException("could not create directory : " + outputDirectory); + } + } + mojo.setLicenseFile(new File(pomFile.getParentFile(), mojo.getLicenseFile().toString())); + log.info("pom : " + getRelativePathFromBasedir(mojo.getProject().getFile())); + log.info("outputDirectory : " + getRelativePathFromBasedir(mojo.getOutputDirectory())); + log.info("licenseFile : " + getRelativePathFromBasedir(mojo.getLicenseFile())); + } + + @Test + public void testOne() throws Exception { + + AddLicenseFileMojo mojo = getMojo(); + + long t0 = mojo.getLicenseFile().lastModified(); + + // always assume pom is older than any file + // since we can not ensure order of copy test resources + mojo.getProject().getFile().setLastModified(0); + + // then executing the mojo, will do NOT change the licence file + mojo.execute(); + + long t1 = mojo.getLicenseFile().lastModified(); + + assertEquals(t0, t1); + + // force to override the license file + mojo.setForce(true); + + mojo.execute(); + t1 = mojo.getLicenseFile().lastModified(); + + assertTrue(t1 > t0); + } + + @Test + public void testTwo() throws Exception { + + AddLicenseFileMojo mojo = getMojo(); + + long t0 = mojo.getLicenseFile().lastModified(); + + // always assume pom is older than any file + // since we can not ensure order of copy test resources + mojo.getProject().getFile().setLastModified(0); + + // then executing the mojo, will do NOT change the licence file + mojo.execute(); + + long t1 = mojo.getLicenseFile().lastModified(); + + assertEquals(t0, t1); + + // force to override the license file + mojo.setForce(true); + + mojo.execute(); + t1 = mojo.getLicenseFile().lastModified(); + + assertTrue(t1 > t0); + } +} Property changes on: trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFileMojoTest.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFilePluginTest.java =================================================================== --- trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFilePluginTest.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/test/java/org/nuiton/license/plugin/AddLicenseFilePluginTest.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,107 +0,0 @@ -/* - * *##% - * Maven helper plugin - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.license.plugin; - -import static org.junit.Assert.*; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import org.nuiton.plugin.AbstractMojoTest; - -public class AddLicenseFilePluginTest extends AbstractMojoTest<AddLicenseFilePlugin> { - - @Override - protected String getGoalName(String methodName) { - return "add-license"; - } - - @Override - protected void setUpMojo(AddLicenseFilePlugin mojo, File pomFile) throws Exception { - super.setUpMojo(mojo, pomFile); - // license is where the pom is - File outputDirectory = pomFile.getParentFile(); - mojo.setOutputDirectory(outputDirectory); - if (!outputDirectory.exists()) { - if (!outputDirectory.mkdirs()) { - throw new IOException("could not create directory : " + outputDirectory); - } - } - mojo.setLicenseFile(new File(pomFile.getParentFile(), mojo.getLicenseFile().toString())); - log.info("pom : " + getRelativePathFromBasedir(mojo.getProject().getFile())); - log.info("outputDirectory : " + getRelativePathFromBasedir(mojo.getOutputDirectory())); - log.info("licenseFile : " + getRelativePathFromBasedir(mojo.getLicenseFile())); - } - - @Test - public void testOne() throws Exception { - - AddLicenseFilePlugin mojo = getMojo(); - - long t0 = mojo.getLicenseFile().lastModified(); - - // always assume pom is older than any file - // since we can not ensure order of copy test resources - mojo.getProject().getFile().setLastModified(0); - - // then executing the mojo, will do NOT change the licence file - mojo.execute(); - - long t1 = mojo.getLicenseFile().lastModified(); - - assertEquals(t0, t1); - - // force to override the license file - mojo.setForce(true); - - mojo.execute(); - t1 = mojo.getLicenseFile().lastModified(); - - assertTrue(t1 > t0); - } - - @Test - public void testTwo() throws Exception { - - AddLicenseFilePlugin mojo = getMojo(); - - long t0 = mojo.getLicenseFile().lastModified(); - - // always assume pom is older than any file - // since we can not ensure order of copy test resources - mojo.getProject().getFile().setLastModified(0); - - // then executing the mojo, will do NOT change the licence file - mojo.execute(); - - long t1 = mojo.getLicenseFile().lastModified(); - - assertEquals(t0, t1); - - // force to override the license file - mojo.setForce(true); - - mojo.execute(); - t1 = mojo.getLicenseFile().lastModified(); - - assertTrue(t1 > t0); - } -} Copied: trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderMojoTest.java (from rev 1674, trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderPluginTest.java) =================================================================== --- trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderMojoTest.java (rev 0) +++ trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderMojoTest.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -0,0 +1,101 @@ +/* + * *##% + * Maven License Plugin + * Copyright (C) 2008 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.license.plugin; + +import java.io.File; +import java.io.IOException; +import java.util.Map.Entry; +import static org.junit.Assert.*; +import org.junit.Test; + +import org.nuiton.processor.filters.LicenseFilter; +import org.nuiton.plugin.PluginHelper; +import org.nuiton.plugin.AbstractMojoTest; + +/** @author chemit */ +public class UpdateHeaderMojoTest extends AbstractMojoTest<UpdateHeaderMojo> { + + public static final String _LICENSE_TO_CHANGE_ = LicenseFilter.HEADER + " license to change " + LicenseFilter.FOOTER; + public static final String _MUST_BE_THERE = "// MUST BE THERE!"; + + @Override + protected String getGoalName(String methodName) { + return "update-header"; + } + + @Test + public void bug_28() throws Exception { + + testPom(new String[]{_MUST_BE_THERE}, new String[]{}); + } + + @Test + public void java() throws Exception { + + testPom(new String[]{_MUST_BE_THERE}, new String[]{_LICENSE_TO_CHANGE_}); + } + + @Test + public void xml() throws Exception { + + testPom(new String[]{_MUST_BE_THERE}, new String[]{_LICENSE_TO_CHANGE_}); + } + + @Test + public void properties() throws Exception { + + testPom(new String[]{_MUST_BE_THERE}, new String[]{_LICENSE_TO_CHANGE_}); + } + + public void testPom(String[] mandatoryPatterns, String[] excludePatterns) throws Exception { + + UpdateHeaderMojo mojo = getMojo(); + + mojo.execute(); + + for (Entry<File, String[]> entry : mojo.filesToTreate.entrySet()) { + File src = entry.getKey(); + for (String javaRelativePath : entry.getValue()) { + File f = new File(src, javaRelativePath); + + assertTrue("generated file " + f + " was not found...", f.exists()); + + String content = PluginHelper.readAsString(f, "utf-8"); + + if (mojo.isVerbose()) { + mojo.getLog().info("check generated file " + f); + } + for (String p : mandatoryPatterns) { + checkPattern(content, p, true, f); + } + for (String p : excludePatterns) { + checkPattern(content, p, false, f); + } + } + } + } + + protected void checkPattern(String content, String pattern, boolean required, File f) throws IOException { + + String errorMessage = required ? "could not find the pattern : " : "should not have found pattern :"; + assertEquals(errorMessage + pattern + " in file " + f, required, content.contains(pattern)); + } +} Property changes on: trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderMojoTest.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Added: svn:mergeinfo + Deleted: trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderPluginTest.java =================================================================== --- trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderPluginTest.java 2010-01-21 12:14:14 UTC (rev 1675) +++ trunk/src/test/java/org/nuiton/license/plugin/UpdateHeaderPluginTest.java 2010-01-21 12:35:36 UTC (rev 1676) @@ -1,105 +0,0 @@ -/* - * *##% - * Maven License Plugin - * Copyright (C) 2008 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.license.plugin; - -import java.io.File; -import java.io.IOException; -import java.util.Map.Entry; -import static org.junit.Assert.*; -import org.junit.Test; - -import org.nuiton.processor.filters.LicenseFilter; -import org.nuiton.plugin.PluginHelper; -import org.nuiton.plugin.AbstractMojoTest; - -/** @author chemit */ -public class UpdateHeaderPluginTest extends AbstractMojoTest<UpdateHeaderPlugin> { - - public static final String _LICENSE_TO_CHANGE_ = LicenseFilter.HEADER + " license to change " + LicenseFilter.FOOTER; - public static final String _MUST_BE_THERE = "// MUST BE THERE!"; - - @Override - protected String getGoalName(String methodName) { - return "update-header"; - } - - @Test - public void bug_28() throws Exception { - - testPom(new String[]{_MUST_BE_THERE}, new String[]{}); - - } - - @Test - public void java() throws Exception { - - testPom(new String[]{_MUST_BE_THERE}, new String[]{_LICENSE_TO_CHANGE_}); - - } - - @Test - public void xml() throws Exception { - - testPom(new String[]{_MUST_BE_THERE}, new String[]{_LICENSE_TO_CHANGE_}); - - } - - @Test - public void properties() throws Exception { - - testPom(new String[]{_MUST_BE_THERE}, new String[]{_LICENSE_TO_CHANGE_}); - - } - - public void testPom(String[] mandatoryPatterns, String[] excludePatterns) throws Exception { - - UpdateHeaderPlugin mojo = getMojo(); - - mojo.execute(); - - for (Entry<File, String[]> entry : mojo.filesToTreate.entrySet()) { - File src = entry.getKey(); - for (String javaRelativePath : entry.getValue()) { - File f = new File(src, javaRelativePath); - - assertTrue("generated file " + f + " was not found...", f.exists()); - - String content = PluginHelper.readAsString(f, "utf-8"); - - if (mojo.isVerbose()) { - mojo.getLog().info("check generated file " + f); - } - for (String p : mandatoryPatterns) { - checkPattern(content, p, true, f); - } - for (String p : excludePatterns) { - checkPattern(content, p, false, f); - } - } - } - } - - protected void checkPattern(String content, String pattern, boolean required, File f) throws IOException { - - String errorMessage = required ? "could not find the pattern : " : "should not have found pattern :"; - assertEquals(errorMessage + pattern + " in file " + f, required, content.contains(pattern)); - } -}