about summary refs log tree commit diff
path: root/pkgs/development/compilers/openjdk/JavaUpdater.java
blob: 32dddf2fabc7ce6195cfdeaa340c89eb20d58e7a (plain) (blame)
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
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.http.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class JavaUpdater {

  record GitHubResult(Optional<String> latestVersion, Optional<String> next) {
  }

  record JsonInfo(String repo, String version, String hash) {
    public JsonInfo(JSONObject json) {
      this(json.getString("repo"), json.getString("version"), json.getString("hash"));
    }

    public String toJsonString(String featureVersion) {
      return """
        \s "%s": {
        \s   "version": "%s",
        \s   "repo":    "%s",
        \s   "hash":    "%s"
        \s }\
        """.formatted(featureVersion, version, repo, hash);
    }
  }

  // Parses the GitHub Link header
  public static Optional<String> getNextLink(HttpHeaders headers) {
    var linkHeader = headers.map().get("Link");
    if (linkHeader == null || linkHeader.isEmpty()) return null;

    var links = linkHeader.getFirst();
    var linksRegex = Pattern.compile("<(.+)>;\\s*rel=\"next\"");
    return Pattern.compile(",")
      .splitAsStream(links)
      .map(x -> linksRegex.matcher(x).results()
        .map(g -> g.group(1))
        .findFirst()
      )
      .filter(Optional::isPresent)
      .map(Optional::orElseThrow)
      .findFirst();
  }

  // HTTP request helper, sets GITHUB_TOKEN if present
  private static HttpRequest NewGithubRequest(String url) {
    var token = System.getenv().get("GITHUB_TOKEN");
    var builder = HttpRequest.newBuilder()
      .uri(URI.create(url));
    if (token != null)
      builder.setHeader("Authorization", "Bearer " + token);
    return builder.build();
  }

  private static GitHubResult getLatestTag(String url) {
    var request = NewGithubRequest(url);

    var response =
      HttpClient.newHttpClient().sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .join();

    var json = new JSONArray(response.body());

    Optional<String> version = StreamSupport.stream(json.spliterator(), false)
      .map(JSONObject.class::cast)
      .map(x -> x.getString("name").replaceFirst("jdk-", ""))
      .filter(x -> x.contains("-ga"))
      .max(Comparator.comparing(Runtime.Version::parse));

    return new GitHubResult(version, getNextLink(response.headers()));
  }

  public String findNewerVersion() {
    var url = Optional.of("https://api.github.com/repos/openjdk/" + getRepo() + "/tags?per_page=100");
    String version = getCurrentVersion();
    do {
      GitHubResult response = getLatestTag(url.orElseThrow());
      if (response.latestVersion.isPresent() && response.latestVersion.orElseThrow().equals(version)) {
        return null;
      }

      String latestVersion = Stream.of(version, response.latestVersion.orElse(version))
        .max(Comparator.comparing(Runtime.Version::parse)).orElseThrow();

      if (latestVersion != version)
        return latestVersion;

      url = response.next;
    } while (url.isPresent());
    return null;
  }


  private static String prettyPrint(JSONObject json) {

    Iterable<String> iterable = () -> json.keys();

    return StreamSupport
      .stream(iterable.spliterator(), false)
      .sorted(Comparator.reverseOrder())
      .map(majorVersion -> (new JsonInfo(json.getJSONObject(majorVersion))).toJsonString(majorVersion))
      .collect(
        Collectors.joining(",\n", "{\n", "\n}")
      );
  }

  public void updateJsonInfo(String newVersion) {
    try {
      JSONObject json = getJsonInfo();
      var info = json.getJSONObject(featureNumber);
      info.put("version", newVersion);
      info.put("hash", nixHash(newVersion));

      try (PrintWriter out = new PrintWriter(infoJsonPath)) {
        out.println(prettyPrint(json));
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private String nixHash(String version) {
    try {
      var process = new ProcessBuilder("nix", "flake", "prefetch",
        "--extra-experimental-features", "'nix-command flakes'",
        "--json", "github:openjdk/" + getRepo() + "/jdk-" + version).start();

      var json = new JSONObject(new String(process.getInputStream().readAllBytes()));
      process.waitFor();
      return json.getString("hash");
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private final String featureNumber;
  private final String infoJsonPath;
  private final JSONObject jsonInfo;

  public String getCurrentVersion() {
    return this.jsonInfo.getJSONObject(this.featureNumber).getString("version");
  }

  public String getRepo() {
    return this.jsonInfo.getJSONObject(this.featureNumber).getString("repo");
  }

  public JSONObject getJsonInfo() {
    try {
      String infoStr = Files.readString(Path.of(this.infoJsonPath));
      return new JSONObject(infoStr);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public JavaUpdater(String featureNumber, String infoJsonPath) {
    this.featureNumber = featureNumber;
    this.infoJsonPath = infoJsonPath;
    this.jsonInfo = getJsonInfo();
  }

  public static void main(String[] args) {
    var updater = new JavaUpdater(args[0], args[1]);
    String newerVersion = updater.findNewerVersion();
    if (newerVersion != null) {
      updater.updateJsonInfo(newerVersion);
    }
  }
}