View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.cling.invoker.mvnup.goals;
20  
21  import java.nio.file.Path;
22  import java.util.HashSet;
23  import java.util.Map;
24  import java.util.Set;
25  
26  import eu.maveniverse.domtrip.Document;
27  import eu.maveniverse.domtrip.Element;
28  import eu.maveniverse.domtrip.maven.Coordinates;
29  import eu.maveniverse.domtrip.maven.MavenPomElements;
30  import org.apache.maven.api.cli.mvnup.UpgradeOptions;
31  import org.apache.maven.cling.invoker.mvnup.UpgradeContext;
32  
33  import static eu.maveniverse.domtrip.maven.MavenPomElements.Elements.PARENT;
34  
35  /**
36   * Abstract base class for upgrade strategies that provides common functionality
37   * and reduces code duplication across strategy implementations.
38   *
39   * <p>Strategies work with domtrip Documents for perfect formatting preservation.
40   * Subclasses can create domtrip Editors from Documents as needed:
41   * <pre>
42   * Editor editor = new Editor(document);
43   * // ... perform domtrip operations ...
44   * // Document is automatically updated
45   * </pre>
46   */
47  public abstract class AbstractUpgradeStrategy implements UpgradeStrategy {
48  
49      /**
50       * Template method that handles common logging and error handling.
51       * Subclasses implement the actual upgrade logic in doApply().
52       */
53      @Override
54      public final UpgradeResult apply(UpgradeContext context, Map<Path, Document> pomMap) {
55          context.info(getDescription());
56          context.indent();
57  
58          try {
59              UpgradeResult result = doApply(context, pomMap);
60  
61              // Log summary
62              logSummary(context, result);
63  
64              return result;
65          } catch (Exception e) {
66              context.failure("Strategy execution failed: " + e.getMessage());
67              return UpgradeResult.failure(pomMap.keySet(), Set.of());
68          } finally {
69              context.unindent();
70          }
71      }
72  
73      /**
74       * Subclasses implement the actual upgrade logic here.
75       *
76       * @param context the upgrade context
77       * @param pomMap map of all POM files in the project
78       * @return the result of the upgrade operation
79       */
80      protected abstract UpgradeResult doApply(UpgradeContext context, Map<Path, Document> pomMap);
81  
82      /**
83       * Gets the upgrade options from the context.
84       *
85       * @param context the upgrade context
86       * @return the upgrade options
87       */
88      protected final UpgradeOptions getOptions(UpgradeContext context) {
89          return context.options();
90      }
91  
92      /**
93       * Logs a summary of the upgrade results.
94       *
95       * @param context the upgrade context
96       * @param result the upgrade result
97       */
98      protected void logSummary(UpgradeContext context, UpgradeResult result) {
99          context.println();
100         context.info(getDescription() + " Summary:");
101         context.indent();
102         context.info(result.modifiedCount() + " POM(s) modified");
103         context.info(result.unmodifiedCount() + " POM(s) needed no changes");
104         if (result.errorCount() > 0) {
105             context.info(result.errorCount() + " POM(s) had errors");
106         }
107         context.unindent();
108     }
109 
110     /**
111      * Extracts an Artifact from a POM document with parent resolution.
112      * If groupId or version are missing, attempts to resolve from parent.
113      *
114      * <p>This method handles Maven's inheritance mechanism where groupId and version
115      * can be inherited from the parent POM.
116      *
117      * @param context the upgrade context for logging
118      * @param pomDocument the POM document
119      * @return the Artifact or null if it cannot be determined
120      */
121     public static Coordinates extractArtifactCoordinatesWithParentResolution(
122             UpgradeContext context, Document pomDocument) {
123         Element root = pomDocument.root();
124 
125         // Extract direct values
126         String groupId = root.childTextTrimmed(MavenPomElements.Elements.GROUP_ID);
127         String artifactId = root.childTextTrimmed(MavenPomElements.Elements.ARTIFACT_ID);
128         String version = root.childTextTrimmed(MavenPomElements.Elements.VERSION);
129 
130         // If groupId or version is missing, try to get from parent
131         if (groupId == null || version == null) {
132             Element parentElement = root.child(PARENT).orElse(null);
133             if (parentElement != null) {
134                 if (groupId == null) {
135                     groupId = parentElement.childTextTrimmed(MavenPomElements.Elements.GROUP_ID);
136                 }
137                 if (version == null) {
138                     version = parentElement.childTextTrimmed(MavenPomElements.Elements.VERSION);
139                 }
140             }
141         }
142 
143         // ArtifactId is required and cannot be inherited
144         if (artifactId == null || artifactId.isEmpty()) {
145             context.debug("Cannot determine artifactId for POM");
146             return null;
147         }
148 
149         // GroupId and version can be inherited, but if still null, we can't create a valid Artifact
150         if (groupId == null || groupId.isEmpty() || version == null || version.isEmpty()) {
151             context.debug("Cannot determine complete GAV for artifactId: " + artifactId);
152             return null;
153         }
154 
155         return Coordinates.of(groupId, artifactId, version);
156     }
157 
158     /**
159      * Computes all artifacts from all POMs in a multi-module project.
160      * This includes resolving parent inheritance.
161      *
162      * @param context the upgrade context for logging
163      * @param pomMap map of all POM files in the project
164      * @return set of all Artifacts in the project
165      */
166     public static Set<Coordinates> computeAllArtifactCoordinates(UpgradeContext context, Map<Path, Document> pomMap) {
167         Set<Coordinates> coordinates = new HashSet<>();
168 
169         context.info("Computing artifacts for inference from " + pomMap.size() + " POM(s)...");
170 
171         // Extract artifact from all POMs in the project
172         for (Map.Entry<Path, Document> entry : pomMap.entrySet()) {
173             Path pomPath = entry.getKey();
174             Document pomDocument = entry.getValue();
175 
176             Coordinates coordinate =
177                     AbstractUpgradeStrategy.extractArtifactCoordinatesWithParentResolution(context, pomDocument);
178             if (coordinate != null) {
179                 coordinates.add(coordinate);
180                 context.debug("Found artifact: " + coordinate.toGAV() + " from " + pomPath);
181             }
182         }
183 
184         context.info("Computed " + coordinates.size() + " unique artifact(s) for inference");
185         return coordinates;
186     }
187 }