You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by jd...@apache.org on 2006/08/15 01:37:51 UTC

svn commit: r431471 - in /maven/plugins/trunk/maven-dependency-plugin: ./ src/main/java/org/apache/maven/plugin/dependency/ src/site/apt/

Author: jdcasey
Date: Mon Aug 14 16:37:50 2006
New Revision: 431471

URL: http://svn.apache.org/viewvc?rev=431471&view=rev
Log:
Adding purge-local-repository mojo, and removing unused ArtifactItem copy, to satisfy PMD. Also added some documentation for the purge mojo.

Added:
    maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/PurgeLocalRepositoryMojo.java   (with props)
Removed:
    maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/ArtifactItem.java
Modified:
    maven/plugins/trunk/maven-dependency-plugin/pom.xml
    maven/plugins/trunk/maven-dependency-plugin/src/site/apt/index.apt
    maven/plugins/trunk/maven-dependency-plugin/src/site/apt/introduction.apt
    maven/plugins/trunk/maven-dependency-plugin/src/site/apt/usage.apt

Modified: maven/plugins/trunk/maven-dependency-plugin/pom.xml
URL: http://svn.apache.org/viewvc/maven/plugins/trunk/maven-dependency-plugin/pom.xml?rev=431471&r1=431470&r2=431471&view=diff
==============================================================================
--- maven/plugins/trunk/maven-dependency-plugin/pom.xml (original)
+++ maven/plugins/trunk/maven-dependency-plugin/pom.xml Mon Aug 14 16:37:50 2006
@@ -86,6 +86,15 @@
         <role>Developer</role>
       </roles>
     </developer>
+    <developer>
+      <id>jdcasey</id>
+      <name>John Casey</name>
+      <email>casey.john.d@gmail.com</email>
+      <organization></organization>
+      <roles>
+        <role>Developer</role>
+      </roles>
+    </developer>
   </developers>
   <licenses>
     <license>
@@ -142,4 +151,4 @@
       </plugin>
     </plugins>
   </reporting-->
-</project>
\ No newline at end of file
+</project>

Added: maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/PurgeLocalRepositoryMojo.java
URL: http://svn.apache.org/viewvc/maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/PurgeLocalRepositoryMojo.java?rev=431471&view=auto
==============================================================================
--- maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/PurgeLocalRepositoryMojo.java (added)
+++ maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/PurgeLocalRepositoryMojo.java Mon Aug 14 16:37:50 2006
@@ -0,0 +1,416 @@
+package org.apache.maven.plugin.dependency;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.artifact.ArtifactUtils;
+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.ArtifactNotFoundException;
+import org.apache.maven.artifact.resolver.ArtifactResolutionException;
+import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
+import org.apache.maven.artifact.resolver.ArtifactResolver;
+import org.apache.maven.artifact.versioning.VersionRange;
+import org.apache.maven.model.Dependency;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.project.MavenProject;
+import org.codehaus.plexus.util.FileUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Remove the project dependencies from the local repository, and optionally
+ * re-resolve them.
+ * 
+ * @author jdcasey
+ * 
+ * @goal purge-local-repository
+ * @aggregator
+ *
+ */
+public class PurgeLocalRepositoryMojo
+    extends AbstractMojo
+{
+
+    public static final String FILE_FUZZINESS = "file";
+    
+    public static final String VERSION_FUZZINESS = "version";
+
+    public static final String ARTIFACT_ID_FUZZINESS = "artifactId";
+
+    public static final String GROUP_ID_FUZZINESS = "groupId";
+
+    /**
+     * The projects in the current build. Each of these is subject to refreshing.
+     * 
+     * @parameter default-value="${reactorProjects}"
+     * @required
+     * @readonly
+     */
+    private List projects;
+
+    /**
+     * The list of dependencies in the form of groupId:artifactId which should
+     * NOT be deleted/refreshed. This is useful for third-party artifacts.
+     * 
+     * @parameter
+     */
+    private List excludes;
+    
+    /**
+     * Comma-separated list of groupId:artifactId entries, which should be used to exclude artifacts
+     * from deletion/refresh. This is a command-line alternative to the <code>excludes</code>
+     * parameter, since List parameters are not currently compatible with CLI specification.
+     * 
+     * @parameter expression="${exclude}"
+     */
+    private String exclude;
+
+    /**
+     * Whether to re-resolve the artifacts once they have been deleted from the
+     * local repository. If you are running this mojo from the command-line, 
+     * you may want to disable this. By default, artifacts will be re-resolved.
+     * 
+     * @parameter expression="${reResolve}" default-value="true"
+     */
+    private boolean reResolve;
+
+    /**
+     * The local repository, from which to delete artifacts.
+     * 
+     * @parameter default-value="${localRepository}"
+     * @required
+     * @readonly
+     */
+    private ArtifactRepository localRepository;
+
+    /**
+     * The artifact resolver used to re-resolve dependencies, if that option is
+     * enabled.
+     * 
+     * @component
+     */
+    private ArtifactResolver resolver;
+
+    /**
+     * The artifact metadata source used to resolve dependencies
+     * 
+     * @component
+     */
+    private ArtifactMetadataSource source;
+
+    /**
+     * Determines how liberally the plugin will delete an artifact from the local repository.
+     * Values are:
+     * <br/>
+     * <ul>
+     *   <li><b>file</b> <i>(default)</i> - Eliminate only the artifact's file.</li>
+     *   <li><b>version</b> - Eliminate all files associated with the artifact's version.</li>
+     *   <li><b>artifactId</b> - Eliminate all files associated with the artifact's artifactId.</li>
+     *   <li><b>groupId</b> - Eliminate all files associated with the artifact's groupId.</li>
+     * </ul>
+     * 
+     * @parameter expression="${resolutionFuzziness}" default-value="file"
+     */
+    private String resolutionFuzziness;
+
+    /**
+     * Whether this mojo should act on all transitive dependencies. Default value is true.
+     * 
+     * @parameter expression="${actTransitively}" default-value="true"
+     */
+    private boolean actTransitively;
+
+    /**
+     * Used to construct artifacts for deletion/resolution...
+     * @component
+     */
+    private ArtifactFactory factory;
+
+    /**
+     * Whether this plugin should output verbose messages. Default is false.
+     * 
+     * @parameter expression="${verbose}" default-value="false"
+     */
+    private boolean verbose;
+
+    public void execute()
+        throws MojoExecutionException, MojoFailureException
+    {
+        List exclusionPatterns = buildExclusionPatternsList();
+        
+        for ( Iterator it = projects.iterator(); it.hasNext(); )
+        {
+            MavenProject project = (MavenProject) it.next();
+
+            try
+            {
+                refreshDependenciesForProject( project, exclusionPatterns );
+            }
+            catch ( ArtifactResolutionException e )
+            {
+                MojoFailureException failure = new MojoFailureException( this,
+                                                                         "Failed to refresh project dependencies for: "
+                                                                             + project.getId(),
+                                                                         "Artifact resolution failed for project: "
+                                                                             + project.getId() );
+                failure.initCause( e );
+
+                throw failure;
+            }
+        }
+    }
+
+    private List buildExclusionPatternsList()
+    {
+        List patterns = new ArrayList();
+        
+        if ( exclude != null )
+        {
+            String[] elements = exclude.split( " ?, ?" );
+            
+            patterns.addAll( Arrays.asList( elements ) );
+        }
+        else if ( excludes != null && !excludes.isEmpty() )
+        {
+            patterns.addAll( excludes );
+        }
+        
+        return patterns;
+    }
+
+    private Map createArtifactMap( MavenProject project )
+    {
+        Map artifactMap = Collections.EMPTY_MAP;
+        
+        List dependencies = project.getDependencies();
+        
+        List remoteRepositories = Collections.EMPTY_LIST;
+        
+        Set dependencyArtifacts = new HashSet();
+
+        for ( Iterator it = dependencies.iterator(); it.hasNext(); )
+        {
+            Dependency dependency = (Dependency) it.next();
+
+            VersionRange vr = VersionRange.createFromVersion( dependency.getVersion() );
+            
+            Artifact artifact = factory.createDependencyArtifact( dependency.getGroupId(), dependency.getArtifactId(),
+                                                                  vr, dependency.getType(), dependency.getClassifier(),
+                                                                  dependency.getScope() );
+            dependencyArtifacts.add( artifact );
+        }
+            
+        if ( actTransitively )
+        {
+            try
+            {
+                ArtifactResolutionResult result = resolver.resolveTransitively( dependencyArtifacts, project.getArtifact(), remoteRepositories,
+                                              localRepository, source );
+                
+                artifactMap = ArtifactUtils.artifactMapByVersionlessId( result.getArtifacts() );
+            }
+            catch ( ArtifactResolutionException e )
+            {
+                verbose( "Skipping: " + e.getArtifactId() + ". It cannot be resolved." );
+            }
+            catch ( ArtifactNotFoundException e )
+            {
+                verbose( "Skipping: " + e.getArtifactId() + ". It cannot be resolved." );
+            }
+        }
+        else
+        {
+            artifactMap = new HashMap();
+            for ( Iterator it = dependencyArtifacts.iterator(); it.hasNext(); )
+            {
+                Artifact artifact = (Artifact) it.next();
+                
+                try
+                {
+                    resolver.resolve( artifact, remoteRepositories, localRepository );
+
+                    artifactMap.put( ArtifactUtils.versionlessKey( artifact ), artifact );
+                }
+                catch ( ArtifactResolutionException e )
+                {
+                    verbose( "Skipping: " + e.getArtifactId() + ". It cannot be resolved." );
+                }
+                catch ( ArtifactNotFoundException e )
+                {
+                    verbose( "Skipping: " + e.getArtifactId() + ". It cannot be resolved." );
+                }
+            }
+        }
+        
+        return artifactMap;
+    }
+
+    private void verbose( String message )
+    {
+        if ( verbose || getLog().isDebugEnabled() )
+        {
+            getLog().info( message );
+        }
+    }
+
+    private void refreshDependenciesForProject( MavenProject project, List exclusionPatterns )
+        throws ArtifactResolutionException, MojoFailureException
+    {
+        Map deps = createArtifactMap( project );
+        
+        if ( deps.isEmpty() )
+        {
+            getLog().info( "Nothing to do for project: " + project.getId() );
+            return;
+        }
+
+        if ( !exclusionPatterns.isEmpty() )
+        {
+            for ( Iterator it = exclusionPatterns.iterator(); it.hasNext(); )
+            {
+                String excludedKey = (String) it.next();
+
+                verbose( "Excluding: " + excludedKey + " from refresh operation for project: " + project.getId() );
+                
+                deps.remove( excludedKey );
+            }
+        }
+        
+        verbose( "Processing dependencies for project: " + project.getId() );
+        
+        List missingArtifacts = new ArrayList();
+        for ( Iterator it = deps.entrySet().iterator(); it.hasNext(); )
+        {
+            Map.Entry entry = (Map.Entry) it.next();
+
+            Artifact artifact = (Artifact) entry.getValue();
+            
+            verbose( "Processing artifact: " + artifact.getId() );
+
+            File deleteTarget = findDeleteTarget( artifact );
+
+            verbose( "Deleting: " + deleteTarget );
+            
+            if ( deleteTarget.isDirectory() )
+            {
+                try
+                {
+                    FileUtils.deleteDirectory( deleteTarget );
+                }
+                catch ( IOException e )
+                {
+                    throw new MojoFailureException( this, "Cannot delete dependency from the local repository: " + artifact.getId(), "Failed to delete: " + deleteTarget );
+                }
+            }
+            else
+            {
+                deleteTarget.delete();
+            }
+            
+            if ( reResolve )
+            {
+                verbose( "Re-resolving." );
+                
+                artifact.setResolved( false );
+                
+                try
+                {
+                    resolver.resolveAlways( artifact, project.getRemoteArtifactRepositories(), localRepository );
+                }
+                catch ( ArtifactResolutionException e )
+                {
+                    getLog().debug( e.getMessage() );
+                    missingArtifacts.add( artifact );
+                }
+                catch ( ArtifactNotFoundException e )
+                {
+                    getLog().debug( e.getMessage() );
+                    missingArtifacts.add( artifact );
+                }
+            }
+        }
+
+        if ( missingArtifacts.size() > 0 )
+        {
+            String message = "required artifacts missing:\n";
+            for ( Iterator i = missingArtifacts.iterator(); i.hasNext(); )
+            {
+                Artifact missingArtifact = (Artifact) i.next();
+                message += "  " + missingArtifact.getId() + "\n";
+            }
+            message += "\nfor the artifact:";
+
+            throw new ArtifactResolutionException( message, project.getArtifact(), project
+                .getRemoteArtifactRepositories() );
+        }
+
+    }
+
+    private File findDeleteTarget( Artifact artifact )
+    {
+        File deleteTarget = artifact.getFile();
+        
+        if ( GROUP_ID_FUZZINESS.equals( resolutionFuzziness ) )
+        {
+            // get the artifactId dir.
+            deleteTarget = deleteTarget.getParentFile().getParentFile();
+            
+            // get the first groupId dir.
+            deleteTarget = deleteTarget.getParentFile();
+            
+            String[] path = localRepository.pathOf( artifact ).split( "\\/" );
+            
+            // subtract the artifact filename, version dir, artifactId dir, and the first groupId 
+            // dir, since we've accounted for those above.
+            int groupParts = path.length - 4;
+            
+            File parent = deleteTarget.getParentFile();
+            int count = 0;
+            while( count++ < groupParts )
+            {
+                // prune empty dirs back to the beginning of the groupId, if possible.
+                
+                // if the parent dir only has the one child file, then it's okay to prune.
+                if ( parent.list().length < 2 )
+                {
+                    deleteTarget = parent;
+                    
+                    // check the parent of this newly checked dir
+                    parent = deleteTarget.getParentFile();
+                }
+                else
+                {
+                    // if there are more files than the one that we're interested in killing, stop.
+                    break;
+                }
+            }
+            
+        }
+        else if ( ARTIFACT_ID_FUZZINESS.equals( resolutionFuzziness ) )
+        {
+            // get the artifactId dir.
+            deleteTarget = deleteTarget.getParentFile().getParentFile();
+        }
+        else if ( VERSION_FUZZINESS.equals( resolutionFuzziness ) )
+        {
+            // get the version dir.
+            deleteTarget = deleteTarget.getParentFile();
+        }
+        // else it's file fuzziness.
+        
+        return deleteTarget;
+    }
+
+}

Propchange: maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/PurgeLocalRepositoryMojo.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: maven/plugins/trunk/maven-dependency-plugin/src/main/java/org/apache/maven/plugin/dependency/PurgeLocalRepositoryMojo.java
------------------------------------------------------------------------------
    svn:keywords = "Author Date Id Revision"

Modified: maven/plugins/trunk/maven-dependency-plugin/src/site/apt/index.apt
URL: http://svn.apache.org/viewvc/maven/plugins/trunk/maven-dependency-plugin/src/site/apt/index.apt?rev=431471&r1=431470&r2=431471&view=diff
==============================================================================
--- maven/plugins/trunk/maven-dependency-plugin/src/site/apt/index.apt (original)
+++ maven/plugins/trunk/maven-dependency-plugin/src/site/apt/index.apt Mon Aug 14 16:37:50 2006
@@ -15,7 +15,7 @@
 
 * Goals Overview
 
-  Dependency plugin has 8 goals:
+  Dependency plugin has 9 goals:
 
 	*{{{copy-mojo.html}dependency:copy}} takes a list of artifacts defined in
 	the plugin configuration section and copies them to a specified location,
@@ -44,6 +44,10 @@
     *{{{go-offline-mojo.html}dependency:go-offline}} tells Maven to resolve
     everything this project is dependent on (dependencies, plugins, reports)
     in preparation for going offline.
+
+        *{{{purge-local-repository.html}dependency:purge-local-repository}} tells
+        Maven to clear all dependency-artifact files out of the local repository,
+        and optionally re-resolve them.
 
   []
 

Modified: maven/plugins/trunk/maven-dependency-plugin/src/site/apt/introduction.apt
URL: http://svn.apache.org/viewvc/maven/plugins/trunk/maven-dependency-plugin/src/site/apt/introduction.apt?rev=431471&r1=431470&r2=431471&view=diff
==============================================================================
--- maven/plugins/trunk/maven-dependency-plugin/src/site/apt/introduction.apt (original)
+++ maven/plugins/trunk/maven-dependency-plugin/src/site/apt/introduction.apt Mon Aug 14 16:37:50 2006
@@ -22,10 +22,12 @@
 	
 	*{{{resolve-plugins-mojo.html}resolve-plugins}}: Tells Maven to resolve plugins and their dependencies.
 
-    *{{{go-offline-mojo.html}go-offline}}: Tells Maven to resolve everything this project is dependent on (dependencies, plugins, reports) in preparation for going offline.
-		
+        *{{{go-offline-mojo.html}go-offline}}: Tells Maven to resolve everything this project is dependent on (dependencies, plugins, reports) in preparation for going offline.
 
-  All goals are able to detect if the artifacts already exist and don't copy/unpack again. 
+        *{{{purge-local-repository.html}purge-local-repository}}: Clears out all dependency-artifact files for the current
+           project or projects from the local repository, and optionally re-resolves them.		
+
+  Where appropriate, goals are able to detect if the artifacts already exist and don't copy/unpack again. 
   
   All goals are also able to handle artifacts with classifiers. This enables the capability to manipulate sources and test-jars for example.
 

Modified: maven/plugins/trunk/maven-dependency-plugin/src/site/apt/usage.apt
URL: http://svn.apache.org/viewvc/maven/plugins/trunk/maven-dependency-plugin/src/site/apt/usage.apt?rev=431471&r1=431470&r2=431471&view=diff
==============================================================================
--- maven/plugins/trunk/maven-dependency-plugin/src/site/apt/usage.apt (original)
+++ maven/plugins/trunk/maven-dependency-plugin/src/site/apt/usage.apt Mon Aug 14 16:37:50 2006
@@ -286,3 +286,63 @@
   This goal is exactly the same as calling
   <<<mvn dependency:resolve dependency:resolve-plugins>>>.
 
+* The <<<dependency:purge-local-repository>>> mojo
+
+  This goal is meant to delete all of the dependencies for the current project
+  (or projects, in the case of a multimodule build) from the local repository.
+  Purges can be run with a variety of limiting parameters, including artifact
+  exclusions, limiting to direct dependencies only, and different levels of
+  depth for deletion. By default, deleted artifacts can be re-resolved 
+  afterwards; you can disable this by specifying <<<-DreResolve=false>>>.
+
+  In its simplest form, the mojo can be called like this:
+
++---+
+mvn dependency:purge-local-repository
++---+
+
+  To add the restriction that the <<<org.apache.maven:maven-plugin-api>>>
+  artifact not be deleted, we can modify the command to this:
+
++---+
+mvn dependency:purge-local-repository -Dexclude=org.apache.maven:maven-plugin-api
++---+
+
+  <<NOTE:>> The <<<exclude>>> parameter is a comma-delimited list of 
+  groupId:artifactId pairs. It has a corresponding List-based parameter -
+  <<<excludes>>> - for convenient use inside the POM.
+
+  Another handy aspect of this mojo is the ability to wipe out artifacts at
+  varying depths. These depths are:
+
+  * <<file>> - Delete just the artifact's file.
+
+  * <<version>> - Delete the version directory containing this artifact. Amounts to
+    <<<file.getParentFile()>>>.
+
+  * <<artifactId>> - Delete the artifactId directory containing this artifact.
+    Amounts to <<<file.getParentFile().getParentFile()>>>.
+
+  * <<groupId>> - Delete the groupId directory structure containing this artifact.
+
+    At a minimum, this amounts to <<<file.getParentFile().getParentFile().getParentFile()>>>.
+    However, if the groupId contains multiple parts, the mojo will prune all groupId-part
+    directories that contain only the files associated with this artifact. Again, note that
+    the exception to this pruning algorithm is the lowest groupId part, which will always
+    be pruned.
+
+  []
+
+  To prune dependency artifacts back to their associated artifactId directories
+  (in order to verify proper artifact resolution, for example), simply use this
+  command:
+
++---+
+mvn dependency:prune-local-repository -DresolutionFuzziness=artifactId
++---+
+
+  Finally, it's possible to bind this mojo to the build lifecycle. One reason for this
+  might be to clean out all dependencies when the build is initialized, to verify
+  correct resolution.
+
+