Attaching Sources To Eclipse Artifacts

After running mvn eclipse:make-artifacts -DstripQualifier=true -DeclipseDir=...path/to/eclipse, you might have lots of source JARs but they aren’t in the right place for Maven 2 to pick them up.

This little Python script fixes that. Just run it after eclipse:make-artifacts.

Note: You may be wondering why I use eclipse:make-artifacts instead of the recommended eclipse:to-maven. Simple: I don’t like to have a dozen core-*.jar in my project.

"""Maven 2 Eclipse Artifact Source resolver

After importing Eclipse artifacts into an M2 repository with

> mvn eclipse:make-artifacts -DstripQualifier=true -DeclipseDir=.../eclipse

run this script to move all source JARs in the right place for
Maven 2 to pick them up.
"""
import os, sys
from shutil import copyfile

def processGroup(path):
    print 'group %s' % path
    for dir in os.listdir(path):
        path2 = os.path.join(path, dir)
        if '.' in dir:
            processArtifact(path2)
        else:
            processGroup(path2)

def processArtifact(path):
    srcPath = path + '.source'
    #print 'processArtifact',srcPath
    if os.path.exists(srcPath):
        processArtifactWithSource(path)

def processArtifactWithSource(basePath):
    binPath = basePath
    srcPath = basePath + '.source'
    baseName = os.path.basename(basePath)
    print 'artifact', baseName
    
    for version in os.listdir(binPath):
        vbinPath = os.path.join(binPath, version)
        vsrcPath = os.path.join(srcPath, version)
        
        srcJar = os.path.join(vsrcPath, '%s.source-%s.jar' % (baseName, version))
        destJar = os.path.join(vbinPath, '%s-%s-sources.jar' % (baseName, version))
        
        if os.path.exists(srcJar):
            print '%s -> %s' % (srcJar, destJar)
            copyfile(srcJar, destJar)

m2repo = os.environ['M2_REPO']
if not m2repo:
    raise Exception('Env variable M2_REPO is not set')

root = os.path.join(m2repo, 'org', 'eclipse')
for dir in os.listdir(root):
    path = os.path.join(root, dir)
    processGroup(path)

Updated 01. December 2009: The script now figures out where your M2 repo is. Plus a minimum of documentation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: