-
Notifications
You must be signed in to change notification settings - Fork 16
/
catalog_check_updates.java
executable file
·268 lines (246 loc) · 11.2 KB
/
catalog_check_updates.java
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
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.6.1
//DEPS io.quarkus:quarkus-devtools-registry-client:3.7.1
//DEPS org.eclipse.jgit:org.eclipse.jgit:5.13.0.202109080827-r
//JAVA_OPTIONS "-Djava.util.logging.SimpleFormatter.format=%1$s [%4$s] %5$s%6$s%n"
//JAVA 17
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import io.quarkus.registry.catalog.CatalogMapperHelper;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.maven.artifact.repository.metadata.Metadata;
import org.apache.maven.artifact.repository.metadata.Versioning;
import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.jboss.logging.Logger;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
@Command(name = "catalog_check_updates", mixinStandardHelpOptions = true, version = "catalog_check_updates 0.1",
description = "catalog_check_updates made with jbang")
class catalog_check_updates implements Callable<Integer> {
private static final String MAVEN_CENTRAL = "https://repo1.maven.org/maven2/";
private static final Logger log = Logger.getLogger(catalog_check_updates.class);
@Option(names = { "-w", "--working-directory" }, description = "The working directory", required = true)
Path workingDirectory;
@Option(names = { "-n", "--no-commit" }, description = "Do not commit changes")
boolean noCommit;
private final ObjectMapper yamlMapper;
private Git git;
public static void main(String... args) {
int exitCode = new CommandLine(new catalog_check_updates()).execute(args);
System.exit(exitCode);
}
public catalog_check_updates() {
this.yamlMapper = new YAMLMapper();
CatalogMapperHelper.initMapper(yamlMapper);
}
@Override
public Integer call() throws Exception {
try (Git gitHandle = Git.open(workingDirectory.toFile())) {
this.git = gitHandle;
list(workingDirectory.resolve("platforms"), this::processCatalog);
list(workingDirectory.resolve("extensions"), this::processExtension);
}
return 0;
}
private void list(Path path, Consumer<Path> consumer) throws IOException {
try (Stream<Path> files = Files.list(path)) {
files
.filter(file -> {
String fileName = file.getFileName().toString();
return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
})
.forEach(consumer);
}
}
private void processCatalog(Path platformYaml) {
try {
log.infof("Processing platform %s", platformYaml);
log.info("---------------------------------------------------------------");
ObjectNode tree = (ObjectNode) yamlMapper.readTree(platformYaml.toFile());
if (!tree.path("enabled").asBoolean(true)) {
log.info("Platform is disabled. Skipping");
return;
}
String repository = tree.path("maven-repository").asText(MAVEN_CENTRAL);
String groupId = tree.get("group-id").asText();
String artifactId = tree.get("artifact-id").asText();
log.infof("Fetching latest version for %s:%s", groupId, artifactId);
List<String> newVersions = populateVersions(repository, groupId, artifactId,
tree.withArray("versions"),
tree.withArray("exclude-versions"));
if (newVersions.isEmpty()) {
log.info("No new versions found");
} else {
log.infof("New versions Found: %s", newVersions);
yamlMapper.writeValue(platformYaml.toFile(), tree);
// Git commit
gitCommit(platformYaml, "Add " + newVersions + " to " + workingDirectory.resolve(platformYaml).normalize());
}
} catch (IOException e) {
log.error("Error while processing platform", e);
}
log.info("---------------------------------------------------------------");
}
private void processExtension(Path extensionYaml) {
try {
log.infof("Processing extension %s", extensionYaml);
log.info("---------------------------------------------------------------");
// Read
ObjectNode tree = (ObjectNode) yamlMapper.readTree(extensionYaml.toFile());
if (!tree.path("enabled").asBoolean(true)) {
log.info("Extension is disabled. Skipping");
return;
}
String repository = tree.path("maven-repository").asText(MAVEN_CENTRAL);
String groupId = tree.get("group-id").asText();
String artifactId = tree.get("artifact-id").asText();
log.infof("Fetching latest version for %s:%s", groupId, artifactId);
List<String> newVersions = populateVersions(repository, groupId, artifactId,
tree.withArray("versions"),
tree.withArray("exclude-versions"))
.stream().filter(catalog_check_updates::isFinal)
.collect(Collectors.toList());
if (newVersions.isEmpty()) {
log.info("No new versions found");
} else {
log.infof("New Versions Found: %s", newVersions);
// Write version
yamlMapper.writeValue(extensionYaml.toFile(), tree);
// Git commit
gitCommit(extensionYaml, "Add " + newVersions + " to " + workingDirectory.resolve(extensionYaml).normalize());
}
} catch (IOException e) {
log.error("Error while processing extension", e);
}
log.info("---------------------------------------------------------------");
}
private List<String> populateVersions(String repository, String groupId, String artifactId, ArrayNode versionsNode,
ArrayNode excludeVersions)
throws IOException {
List<String> newVersions = new ArrayList<>();
Map<String, JsonNode> map = new LinkedHashMap<>();
List<String> versionsAlreadyRead = StreamSupport.stream(versionsNode.spliterator(), false)
.map(node -> {
String versionName;
if (node.isObject()) {
versionName = node.fieldNames().next();
map.put(versionName, node.get(versionName));
} else {
versionName = node.asText();
map.put(versionName, versionsNode.nullNode());
}
return versionName;
})
.collect(Collectors.toList());
URI metadataURL = URI.create(MessageFormat.format("{0}{1}/{2}/maven-metadata.xml",
Objects.toString(repository, MAVEN_CENTRAL),
groupId.replace('.', '/'),
artifactId));
try (CloseableHttpClient httpClient = createHttpClient();
InputStream is = httpClient.execute(new HttpGet(metadataURL)).getEntity().getContent()) {
MetadataXpp3Reader metadataReader = new MetadataXpp3Reader();
Metadata metadata = metadataReader.read(is);
Versioning versioning = metadata.getVersioning();
List<String> versions = versioning.getVersions();
Collections.reverse(versions);
versions = keepLatest(versions);
versionsNode.removeAll();
for (String version : versions) {
if (!containsValue(excludeVersions, version)) {
if (map.get(version) == null || map.get(version).isNull()) {
versionsNode.add(version);
} else {
versionsNode.addObject()
.set(version, map.get(version));
}
newVersions.add(version);
}
}
} catch (XmlPullParserException e) {
log.debug("Invalid metadata", e);
}
newVersions.removeAll(versionsAlreadyRead);
return newVersions;
}
private boolean containsValue(ArrayNode arrayNode, String latestVersion) {
for (JsonNode node : arrayNode) {
if (node.isObject()) {
if (latestVersion.matches(node.fieldNames().next())) {
return true;
}
} else {
if (latestVersion.matches(node.asText())) {
return true;
}
}
}
return false;
}
private List<String> keepLatest(List<String> versions) {
int major = -1, minor = -1;
List<String> latest = new ArrayList<>();
for (String version : versions) {
DefaultArtifactVersion dav = new DefaultArtifactVersion(version);
if (dav.getMajorVersion() != major || dav.getMinorVersion() != minor) {
major = dav.getMajorVersion();
minor = dav.getMinorVersion();
latest.add(version);
}
}
return latest;
}
public void gitCommit(Path file, String message) throws IOException {
if (noCommit) {
return;
}
try {
git.add().addFilepattern(workingDirectory.resolve(file).normalize().toString()).call();
git.commit().setSign(false).setMessage(message).call();
} catch (GitAPIException e) {
throw new IOException(e);
}
}
private static boolean isFinal(String version) {
DefaultArtifactVersion v = new DefaultArtifactVersion(version);
String qualifier = v.getQualifier();
if (qualifier == null) {
return true;
}
qualifier = qualifier.trim().toUpperCase(Locale.ROOT);
return !qualifier.startsWith("ALPHA") && !qualifier.startsWith("BETA") && !qualifier.startsWith("CR");
}
private CloseableHttpClient createHttpClient() {
return HttpClients.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
}
}