Can maven repository be added from maven extension in Maven 3.5

694 Views Asked by At

Is this code

project.getPluginRepositories().add(myCustomRepository); 

executed inside afterProjectsRead method of a maven extension (class extending AbstractMavenLifecycleParticipant) supposed to work? It executes fine (no errors nor warnings) but the repo does not seem to be taken into account by Maven and build fails with "Plugin .... or one of its dependencies could not be resolved"!

If this is not possible this way, are there any other ways to dynamically add a repo from maven extension?

2

There are 2 best solutions below

5
On

Another way is to listen as an EventSpy then inject project level settings, within what we can define custom repos.

For example,

in ${basedir}/.mvn/extensions.xml

    <extensions xmlns="http://maven.apache.org/EXTENSIONS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/EXTENSIONS/1.0.0 http://maven.apache.org/xsd/core-extensions-1.0.0.xsd">
      <extension>
        <groupId>com.github.gzm55.maven</groupId>
        <artifactId>project-settings-extension</artifactId>
        <version>0.3.5</version>
      </extension>
    </extensions>

in ${basedir}/.mvn/settings.xml

  <settings>

    <mirrors>...</mirrors>

    <profiles>
      <profile>
        <repositories/>
      </profile>
    </profiles>

  </settings>
0
On

If this is not possible this way, are there any other ways to dynamically add a repo from maven extension?

It seams this code

List<ArtifactRepository> pluginRepos = new LinkedList<>();
pluginRepos.addAll(project.getPluginArtifactRepositories());
pluginRepos.add(myCustomRepository);
project.setPluginArtifactRepositories(pluginRepos);

works. Here is an example from ExecutionListener rather than MavenLifecycleParticipant but I guess it should work in afterProjectsRead too.

WARNING: This is probably not what Maven expects you to do and may break some plugins. For example maven-shade-plugin works mostly OK but breaks (and fails the build) while trying to generate reduced POM when repositories are added this way.