maven plugin that download dependencies but failed to attach them to project compile scope in intellij (maven 3.9.0)

182 views Asked by At

We have a requirement to write a maven plugin that

  1. downloads dependencies
  2. add them to the compile class-path of project

download dependency logic is working as expected.

But, when the project is opened in intellij, downloaded library is not there in project compile classpath.


Attached a very simplified project on github to reproduce problem:-

https://github.com/moglideveloper/download-dependencies-from-maven-plugin-example

Execute below commands to reproduce problem :-

git clone https://github.com/moglideveloper/download-dependencies-from-maven-plugin-example
cd download-dependencies-maven-plugin
mvn install

cd ../example-project
mvn clean compile

Below is the DownloadDependencyMojo configuration :-

public void execute() throws MojoExecutionException {

    Artifact aetherArtifact = new DefaultArtifact(groupId, artifactId, type, version);

    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(aetherArtifact);
    artifactRequest.setRepositories(remoteRepos);

    try {
        ArtifactResult aetherArtifactResult = repoSystem.resolveArtifact(repoSession, artifactRequest);
        Artifact resolvedAetherArtifact = aetherArtifactResult.getArtifact();

        getLog().info("Resolved aetherArtifact: " + resolvedAetherArtifact.getFile().getPath());

        project.addCompileSourceRoot(resolvedAetherArtifact.getFile().getAbsolutePath());
        org.apache.maven.artifact.DefaultArtifact defaultArtifact = toMavenDefaultArtifact(resolvedAetherArtifact, "compile");
        project.addAttachedArtifact(defaultArtifact);

        Dependency compileScopeDependency = toDependency(resolvedAetherArtifact, "compile");
        project.getDependencies().add(compileScopeDependency);

        getLog().info("added to project: " + resolvedAetherArtifact.getFile().getPath());
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("failed to download dependencies", e);
    }
}

❯ mvn --version

Apache Maven 3.9.0 (9b58d2bad23a66be161c4664ef21ce219c2c8584)
Maven home: /Users/mogli/.sdkman/candidates/maven/current
Java version: 17.0.6, vendor: Eclipse Adoptium, runtime: /Users/mogli/.sdkman/candidates/java/17.0.6-tem
Default locale: en_IN, platform encoding: UTF-8
OS name: "mac os x", version: "12.6.1", arch: "x86_64", family: "mac"
0

There are 0 answers