1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.internal.impl;
20
21 import javax.inject.Inject;
22 import javax.inject.Named;
23
24 import java.nio.file.Path;
25 import java.util.Map;
26 import java.util.Objects;
27 import java.util.Optional;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.stream.Stream;
30
31 import org.apache.maven.api.Artifact;
32 import org.apache.maven.api.ProducedArtifact;
33 import org.apache.maven.api.annotations.Nonnull;
34 import org.apache.maven.api.di.SessionScoped;
35 import org.apache.maven.api.services.ArtifactManager;
36 import org.apache.maven.project.MavenProject;
37 import org.eclipse.sisu.Typed;
38
39 import static org.apache.maven.internal.impl.Utils.nonNull;
40
41 @Named
42 @Typed
43 @SessionScoped
44 public class DefaultArtifactManager implements ArtifactManager {
45
46 @Nonnull
47 private final InternalMavenSession session;
48
49 private final Map<String, Path> paths = new ConcurrentHashMap<>();
50
51 @Inject
52 public DefaultArtifactManager(@Nonnull InternalMavenSession session) {
53 this.session = session;
54 }
55
56 @Nonnull
57 @Override
58 public Optional<Path> getPath(@Nonnull Artifact artifact) {
59 String id = id(nonNull(artifact, "artifact"));
60 if (session.getMavenSession().getAllProjects() != null) {
61 for (MavenProject project : session.getMavenSession().getAllProjects()) {
62 if (id.equals(id(project.getArtifact()))
63 && project.getArtifact().getFile() != null) {
64 return Optional.of(project.getArtifact().getFile().toPath());
65 }
66 }
67 }
68 Path path = paths.get(id);
69 if (path == null && artifact instanceof DefaultArtifact) {
70 path = ((DefaultArtifact) artifact).getArtifact().getPath();
71 }
72 return Optional.ofNullable(path);
73 }
74
75 @Override
76 public void setPath(@Nonnull ProducedArtifact artifact, Path path) {
77 String id = id(nonNull(artifact, "artifact"));
78 if (session.getMavenSession().getAllProjects() != null) {
79 session.getMavenSession().getAllProjects().stream()
80 .flatMap(this::getProjectArtifacts)
81 .filter(a -> Objects.equals(id, id(a)))
82 .forEach(a -> a.setFile(path != null ? path.toFile() : null));
83 }
84 if (path == null) {
85 paths.remove(id);
86 } else {
87 paths.put(id, path);
88 }
89 }
90
91
92
93
94
95 private Stream<org.apache.maven.artifact.Artifact> getProjectArtifacts(MavenProject project) {
96 return Stream.concat(Stream.of(project.getArtifact()), project.getAttachedArtifacts().stream());
97 }
98
99 private String id(org.apache.maven.artifact.Artifact artifact) {
100 return artifact.getGroupId()
101 + ":" + artifact.getArtifactId()
102 + ":" + artifact.getArtifactHandler().getExtension()
103 + (artifact.getClassifier() == null || artifact.getClassifier().isEmpty()
104 ? ""
105 : ":" + artifact.getClassifier())
106 + ":" + artifact.getVersion();
107 }
108
109 private String id(Artifact artifact) {
110 return artifact.key();
111 }
112 }