2010-07-01 55 views
2

我希望能够在执行过程中发现插件的版本; 0.0.1-SNAPSHOT,0.0.1,1.0-SNAPSHOT等。Maven插件在执行期间如何发现它自己的版本?

可以这样做吗? AbstractMojo类并没有给你提供关于插件本身的更多信息。

编辑 - 我正在使用下面的代码作为解决方法。它假定可以从使用插件本身的资源URL构建的资源URL加载插件的MANIFEST。这不是很好,但似乎对清单位于任一文件或jar类加载器的工作:

String getPluginVersion() throws IOException { 
    Manifest mf = loadManifest(getClass().getClassLoader(), getClass()); 
    return mf.getMainAttributes().getValue("Implementation-Version"); 
} 

Manifest loadManifest(final ClassLoader cl, final Class c) throws IOException { 
    String resourceName = "/" + c.getName().replaceAll("\\.", "/") + ".class"; 
    URL classResource = cl.getResource(resourceName); 
    String path = classResource.toString(); 

    int idx = path.indexOf(resourceName); 
    if (idx < 0) { 
     return null; 
    } 

    String urlStr = classResource.toString().substring(0, idx) + "/META-INF/MANIFEST.MF"; 

    URL url = new URL(urlStr); 

    InputStream in = null; 
    Manifest mf = null; 
    try { 
     in = url.openStream(); 
     mf = new Manifest(in); 
    } finally { 
     if (null != in) { 
      in.close(); 
     } 
     in = null; 
    } 

    return mf; 
} 

回答

0

首先,添加以下依赖于你的插件的POM:

<dependency> 
    <groupId>org.apache.maven</groupId> 
    <artifactId>maven-project</artifactId> 
    <version>2.0</version> 
</dependency> 

然后,你可以做以下:

public class MyMojo extends AbstractMojo { 

private static final String GROUP_ID = "your-group-id"; 
private static final String ARTIFACT_ID = "your-artifact-id"; 

/** 
* @parameter default-value="${project}" 
*/ 
MavenProject project; 

public void execute() throws MojoExecutionException { 
    Set pluginArtifacts = project.getPluginArtifacts(); 
    for (Iterator iterator = pluginArtifacts.iterator(); iterator.hasNext();) { 
     Artifact artifact = (Artifact) iterator.next(); 
     String groupId = artifact.getGroupId(); 
     String artifactId = artifact.getArtifactId(); 
     if (groupId.equals(GROUP_ID) && artifactId.equals(ARTIFACT_ID)) { 
      System.out.println(artifact.getVersion()); 
      break; 
     } 
    } 
} 
+0

我不认为这是正确的。如果插件是针对POM运行的,那么将返回POM的版本,而不是插件的版本。 – 2010-07-02 09:21:37

+0

嗨保罗,是的,你是对的,它给了项目的版本,而不是插件。我相应地更新了代码。这不是一个非常优雅的解决方案,但似乎工作。也许别人知道一个更干净的方式来做到这一点。 – 2010-07-02 21:08:52

1

我不认为你的清单文件的“解决方法”是一个坏主意。由于它包装在插件的.jar中,因此您应该始终可以访问它。

对于这个职位是一个答案,这里是另一个想法:让你的Maven插件的构建过程中为你做肮脏的工作:有一个占位符,在你的插件来源:

private final String myVersion = "[CURRENT-VERSION]"; 

使用ant-插件或其他东西在编译前用当前版本替换占位符。

相关问题