Search code examples
mavenmaven-2pom.xmlmaven-dependency-pluginmaven-jar-plugin

How to download the souce of jars to custom location in maven?


This is follow up post of How to get all the specified jars mentioned in the pom.xml and transitively dependent jars? Except that I am looking to download the source of the both dependent and transitively dependent jars to custom mentioned location.

I have tried following command but it didn't works.

mvn dependency:sources -DoutputDirectory=.../

It didn't worked.

mvn dependency:sources dependency:copy-dependencies -DoutputDirectory=.../

It didn't worked.


Solution

  • The source jar is normally available via Maven using a classifier, so that for the same Maven coordinates (GAV, groupId, artifactId, version) you can have more than one artefact related to the same build (i.e. default application/library jar, sources jar, test sources jar, javadoc jar, etc.), as also explained in another SO answer. The standard classifier for sources is sources, created by the Maven Source Plugin.

    The copy-dependencies can be configured to fetch a certain classifier via the classifier option.

    So in your case, to get the sources of your dependencies to an external folder, you can invoke the command as following:

    mvn dependency:copy-dependencies -DoutputDirectory=somewhere -Dclassifier=sources

    Note the additional -Dclassifier=sources option.

    An example of pom configuration to achieve the same is also explained in the official documentation of the Dependency Plugin, using the following snippet:

    <project>
      [...]
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.10</version>
            <executions>
              <execution>
                <id>src-dependencies</id>
                <phase>package</phase>
                <goals>
                  <!-- use copy-dependencies instead if you don't want to explode the sources -->
                  <goal>unpack-dependencies</goal>
                </goals>
                <configuration>
                  <classifier>sources</classifier>
                  <failOnMissingClassifierArtifact>false</failOnMissingClassifierArtifact>
                  <outputDirectory>${project.build.directory}/sources</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      [...]
    </project>
    

    Beware though that Maven doesn't know about sources, it only knows about artefacts. So if the sources (classified) artefact is not available via its GAV+C, Maven will find it and as such will not download any source.