forked from openrewrite/rewrite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpgradePluginVersion.java
More file actions
349 lines (309 loc) · 19.5 KB
/
UpgradePluginVersion.java
File metadata and controls
349 lines (309 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
* Copyright 2021 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.gradle.plugins;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.gradle.*;
import org.openrewrite.gradle.internal.ChangeStringLiteral;
import org.openrewrite.gradle.marker.GradleProject;
import org.openrewrite.gradle.marker.GradleSettings;
import org.openrewrite.gradle.trait.GradlePlugin;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.marker.Markup;
import org.openrewrite.maven.MavenDownloadingException;
import org.openrewrite.maven.internal.MavenPomDownloader;
import org.openrewrite.maven.table.MavenMetadataFailures;
import org.openrewrite.maven.tree.Dependency;
import org.openrewrite.maven.tree.GroupArtifact;
import org.openrewrite.maven.tree.GroupArtifactVersion;
import org.openrewrite.properties.PropertiesVisitor;
import org.openrewrite.properties.tree.Properties;
import org.openrewrite.semver.Semver;
import org.openrewrite.semver.VersionComparator;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
@SuppressWarnings("DuplicatedCode")
@Value
@EqualsAndHashCode(callSuper = false)
public class UpgradePluginVersion extends ScanningRecipe<UpgradePluginVersion.DependencyVersionState> {
private static final String GRADLE_PROPERTIES_FILE_NAME = "gradle.properties";
@EqualsAndHashCode.Exclude
transient MavenMetadataFailures metadataFailures = new MavenMetadataFailures(this);
@Option(displayName = "Plugin id",
description = "The `ID` part of `plugin { ID }`, as a glob expression.",
example = "com.jfrog.bintray")
String pluginIdPattern;
@Option(displayName = "New version",
description = "An exact version number or node-style semver selector used to select the version number. " +
"You can also use `latest.release` for the latest available version and `latest.patch` if " +
"the current version is a valid semantic version. For more details, you can look at the documentation " +
"page of [version selectors](https://docs.openrewrite.org/reference/dependency-version-selectors). " +
"Defaults to `latest.release`.",
example = "29.X",
required = false)
@Nullable
String newVersion;
@Option(displayName = "Version pattern",
description = "Allows version selection to be extended beyond the original Node Semver semantics. So for example," +
"Setting 'version' to \"25-29\" can be paired with a metadata pattern of \"-jre\" to select Guava 29.0-jre",
example = "-jre",
required = false)
@Nullable
String versionPattern;
String displayName = "Update a Gradle plugin by id";
String description = "Update a Gradle plugin by id to a later version defined by the plugins DSL. " +
"To upgrade a plugin dependency defined by `buildscript.dependencies`, use the `UpgradeDependencyVersion` " +
"recipe instead.";
@Override
public Validated<Object> validate() {
Validated<Object> validated = super.validate();
if (newVersion != null) {
validated = validated.and(Semver.validate(newVersion, versionPattern));
}
return validated;
}
public static class DependencyVersionState {
Map<String, String> versionPropNameToPluginId = new HashMap<>();
Map<String, @Nullable String> pluginIdToNewVersion = new HashMap<>();
}
@Override
public DependencyVersionState getInitialValue(ExecutionContext ctx) {
return new DependencyVersionState();
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(DependencyVersionState acc) {
JavaVisitor<ExecutionContext> javaVisitor = new JavaVisitor<ExecutionContext>() {
@Nullable
private GradleProject gradleProject;
@Nullable
private GradleSettings gradleSettings;
private final Map<String, String> localVariableValues = new HashMap<>();
@Override
public @Nullable J visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
gradleProject = tree.getMarkers().findFirst(GradleProject.class).orElse(null);
gradleSettings = tree.getMarkers().findFirst(GradleSettings.class).orElse(null);
localVariableValues.clear();
}
return super.visit(tree, ctx);
}
@Override
public J visitVariable(J.VariableDeclarations.NamedVariable variable, ExecutionContext ctx) {
J.VariableDeclarations.NamedVariable v = (J.VariableDeclarations.NamedVariable) super.visitVariable(variable, ctx);
if (v.getInitializer() instanceof J.Literal) {
String value = literalValue(v.getInitializer());
if (value != null) {
localVariableValues.put(v.getSimpleName(), value);
}
}
return v;
}
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
GradlePlugin plugin = new GradlePlugin.Matcher().pluginIdPattern(pluginIdPattern).get(getCursor()).orElse(null);
if (plugin == null || plugin.getPluginId() == null) {
return m;
}
String pluginId = plugin.getPluginId();
List<Expression> versionArgs = m.getArguments();
try {
if (plugin.getVersion() != null) {
String resolvedVersion = new DependencyVersionSelector(metadataFailures, gradleProject, gradleSettings)
.select(new GroupArtifactVersion(pluginId, pluginId + ".gradle.plugin", plugin.getVersion()), "classpath", newVersion, versionPattern, ctx);
acc.pluginIdToNewVersion.put(pluginId, resolvedVersion);
} else if (versionArgs.get(0) instanceof G.GString) {
G.GString gString = (G.GString) versionArgs.get(0);
if (gString.getStrings().isEmpty() || !(gString.getStrings().get(0) instanceof G.GString.Value)) {
return m;
}
G.GString.Value gStringValue = (G.GString.Value) gString.getStrings().get(0);
String versionVariableName = gStringValue.getTree().toString();
String resolvedPluginVersion = new DependencyVersionSelector(metadataFailures, gradleProject, gradleSettings)
.select(new GroupArtifact(pluginId, pluginId + ".gradle.plugin"), "classpath", newVersion, versionPattern, ctx);
acc.versionPropNameToPluginId.put(versionVariableName, pluginId);
assert resolvedPluginVersion != null;
acc.pluginIdToNewVersion.put(pluginId, resolvedPluginVersion);
} else if (versionArgs.get(0) instanceof J.Identifier) {
J.Identifier identifier = (J.Identifier) versionArgs.get(0);
String versionVariableName = identifier.getSimpleName();
String localCurrentVersion = localVariableValues.get(versionVariableName);
String resolvedPluginVersion;
if (localCurrentVersion != null) {
resolvedPluginVersion = new DependencyVersionSelector(metadataFailures, gradleProject, gradleSettings)
.select(new GroupArtifactVersion(pluginId, pluginId + ".gradle.plugin", localCurrentVersion), "classpath", newVersion, versionPattern, ctx);
} else {
resolvedPluginVersion = new DependencyVersionSelector(metadataFailures, gradleProject, gradleSettings)
.select(new GroupArtifact(pluginId, pluginId + ".gradle.plugin"), "classpath", newVersion, versionPattern, ctx);
}
acc.versionPropNameToPluginId.put(versionVariableName, pluginId);
acc.pluginIdToNewVersion.put(pluginId, resolvedPluginVersion);
}
} catch (MavenDownloadingException e) {
m = Markup.warn(m, e);
}
return m;
}
};
return Preconditions.check(Preconditions.or(new IsBuildGradle<>(), new IsSettingsGradle<>()), javaVisitor);
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(DependencyVersionState acc) {
PropertiesVisitor<ExecutionContext> propertiesVisitor = new PropertiesVisitor<ExecutionContext>() {
@Override
public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
return super.isAcceptable(sourceFile, ctx) && sourceFile.getSourcePath().endsWith(GRADLE_PROPERTIES_FILE_NAME);
}
@Override
public Properties visitEntry(Properties.Entry entry, ExecutionContext ctx) {
if (acc.versionPropNameToPluginId.containsKey(entry.getKey())) {
String currentVersion = entry.getValue().getText();
String pluginId = acc.versionPropNameToPluginId.get(entry.getKey());
if (!StringUtils.isBlank(newVersion)) {
String resolvedVersion = acc.pluginIdToNewVersion.get(pluginId);
VersionComparator versionComparator = Semver.validate(newVersion, versionPattern).getValue();
if (versionComparator == null) {
return entry;
}
Optional<String> finalVersion = versionComparator.upgrade(currentVersion, singletonList(resolvedVersion));
if (finalVersion.isPresent()) {
return entry.withValue(entry.getValue().withText(finalVersion.get()));
}
}
}
return entry;
}
};
JavaVisitor<ExecutionContext> javaVisitor = new JavaVisitor<ExecutionContext>() {
@Override
public @Nullable J visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
GradleProject gradleProject = tree.getMarkers().findFirst(GradleProject.class).orElse(null);
String sbVersion = acc.pluginIdToNewVersion.get("org.springframework.boot");
if (gradleProject != null && sbVersion != null) {
if (acc.pluginIdToNewVersion.containsKey("org.springframework.boot") &&
gradleProject.getPlugins().stream().anyMatch(plugin -> "io.spring.dependency-management".equals(plugin.getId())) &&
gradleProject.getPlugins().stream().anyMatch(plugin -> "org.springframework.boot".equals(plugin.getId()))) {
//noinspection NullableProblems
AtomicReference<@Nullable String> springBootPluginVersion = new GradlePlugin.Matcher()
.pluginIdPattern("org.springframework.boot")
.asVisitor((GradlePlugin plugin, AtomicReference<String> ref) -> {
if (plugin.getVersion() != null) {
ref.set(plugin.getVersion());
}
return plugin.getTree();
}).reduce(tree, new AtomicReference<>());
if (springBootPluginVersion.get() != null) {
Set<GroupArtifact> requested = gradleProject.getConfigurations().stream()
.flatMap(conf -> conf.getRequested().stream())
.map(Dependency::getGav)
.map(GroupArtifactVersion::asGroupArtifact)
.collect(toSet());
try {
MavenPomDownloader mpd = new MavenPomDownloader(ctx);
List<GroupArtifact> oldPlatformManaged = mpd.download(new GroupArtifactVersion("org.springframework.boot", "spring-boot-dependencies", springBootPluginVersion.get()), null, null, gradleProject.getMavenRepositories()).getDependencyManagement().stream()
.map(md -> new GroupArtifact(md.getGroupId(), md.getArtifactId()))
.filter(requested::contains)
.collect(toList());
List<GroupArtifactVersion> newPlatformManaged = mpd.download(new GroupArtifactVersion("org.springframework.boot", "spring-boot-dependencies", sbVersion), null, null, gradleProject.getMavenRepositories()).getDependencyManagement().stream()
.map(md -> new GroupArtifactVersion(md.getGroupId(), md.getArtifactId(), md.getVersion()))
.filter(gav -> requested.stream().anyMatch(r -> r.equals(gav.asGroupArtifact())))
.collect(toList());
List<GroupArtifact> newlyManaged = newPlatformManaged.stream().map(GroupArtifactVersion::asGroupArtifact).collect(toList());
List<GroupArtifact> noLongerManaged = new ArrayList<>(oldPlatformManaged);
noLongerManaged.removeAll(newlyManaged);
newlyManaged.removeAll(oldPlatformManaged);
gradleProject = gradleProject.upgradeDirectDependencyVersions(newPlatformManaged, ctx);
for (GroupArtifact ga : noLongerManaged) {
doAfterVisit(new AddExplicitDependencyVersion(ga.getGroupId(), ga.getArtifactId()));
}
for (GroupArtifact ga : newlyManaged) {
doAfterVisit(new RemoveRedundantDependencyVersions(ga.getGroupId(), ga.getArtifactId(), RemoveRedundantDependencyVersions.Comparator.GTE).getVisitor());
}
} catch (MavenDownloadingException e) {
tree = Markup.warn(tree, e);
}
}
}
gradleProject = gradleProject.upgradeBuildscriptDirectDependencyVersions(singletonList(new GroupArtifactVersion("org.springframework.boot", "org.springframework.boot.gradle.plugin", sbVersion)), ctx);
tree = tree.withMarkers(tree.getMarkers().setByType(gradleProject));
}
}
return super.visit(tree, ctx);
}
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
// Match the trait before super to ensure the cursor is unmodified
GradlePlugin plugin = new GradlePlugin.Matcher().pluginIdPattern(pluginIdPattern).get(getCursor()).orElse(null);
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (plugin == null || plugin.getPluginId() == null || plugin.getVersion() == null ||
!"version".equals(m.getSimpleName())) {
return m;
}
String resolvedVersion = acc.pluginIdToNewVersion.get(plugin.getPluginId());
if (resolvedVersion == null) {
return m;
}
List<Expression> versionArgs = m.getArguments();
return m.withArguments(ListUtils.map(versionArgs, v -> ChangeStringLiteral.withStringValue(v, resolvedVersion)));
}
@Override
public J visitVariable(J.VariableDeclarations.NamedVariable variable, ExecutionContext ctx) {
J.VariableDeclarations.NamedVariable visited = (J.VariableDeclarations.NamedVariable) super.visitVariable(variable, ctx);
if (acc.versionPropNameToPluginId.containsKey(visited.getSimpleName()) && visited.getInitializer() instanceof J.Literal) {
J.Literal initializer = (J.Literal) visited.getInitializer();
String oldVersion = literalValue(initializer);
String newVersion = acc.pluginIdToNewVersion.get(acc.versionPropNameToPluginId.get(visited.getSimpleName()));
if (newVersion != null && !newVersion.equals(oldVersion)) {
VersionComparator versionComparator = Semver.validate(newVersion, versionPattern).getValue();
if (versionComparator == null) {
return visited;
}
Optional<String> finalVersion = versionComparator.upgrade(oldVersion != null ? oldVersion : "", singletonList(newVersion));
if (finalVersion.isPresent()) {
String valueSource = initializer.getValueSource() == null || oldVersion == null ? initializer.getValueSource() : initializer.getValueSource().replace(oldVersion, newVersion);
return visited.withInitializer(initializer.withValueSource(valueSource).withValue(finalVersion.get()));
}
}
}
return visited;
}
};
return Preconditions.or(propertiesVisitor, Preconditions.check(Preconditions.or(new IsBuildGradle<>(), new IsSettingsGradle<>()), javaVisitor));
}
private @Nullable String literalValue(Expression expr) {
return new JavaVisitor<AtomicReference<@Nullable String>>() {
@Override
public J visitLiteral(J.Literal literal, AtomicReference<@Nullable String> value) {
if (literal.getType() == JavaType.Primitive.String) {
value.compareAndSet(null, (String) literal.getValue());
}
return literal;
}
}.reduce(expr, new AtomicReference<>(null)).get();
}
}