-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Expand file tree
/
Copy pathstep_3_generate_stats.java
More file actions
404 lines (357 loc) · 12.8 KB
/
step_3_generate_stats.java
File metadata and controls
404 lines (357 loc) · 12.8 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import java.io.*;
import java.net.http.*;
import java.net.URI;
import java.nio.file.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Fetches GitHub stars and last commit data for repositories and creates a mapping file.
*
* Usage: step_3_generate_stats.java [parsed_projects_file] [stats_file]
*/
void main(String[] args) throws IOException, InterruptedException {
var inputPath = args.length > 0 ? Path.of(args[0]) : Path.of(Constants.TMP_DIR + "/" + Constants.PARSED_PROJECTS_FILE);
var tmpDir = FileUtils.ensureTmpDirectory();
var outputPath = args.length > 1 ? Path.of(args[1]) : tmpDir.resolve(Constants.GITHUB_STATS_FILE);
System.out.println("Step 3: Fetching GitHub stars and last commit data...");
System.out.printf("Input: %s%n", inputPath.toAbsolutePath());
System.out.printf("Output: %s%n", outputPath.toAbsolutePath());
// Validate input
FileUtils.validateInputFile(inputPath);
// Read parsed entries
var entries = readParsedEntries(inputPath);
// Try to load existing stats mappings if available
Map<String, StatsMapping> existingMappings = new HashMap<>();
if (Files.exists(outputPath)) {
try {
System.out.println("Loading existing stats data...");
existingMappings = readStatsMappings(outputPath);
System.out.printf("Found %d existing stats entries%n", existingMappings.size());
} catch (Exception e) {
System.out.println("Could not load existing stats data, will fetch all new data");
}
}
// Generate stats mappings with actual GitHub data
var statsMappings = generateStatsMappings(entries, existingMappings);
// Write stats mappings
writeStatsMappings(outputPath, statsMappings);
System.out.printf(
"SUCCESS: Successfully fetched data for %d repositories!%n",
statsMappings.size()
);
}
/**
* Reads parsed entries from the temporary file.
*/
List<ProjectEntry> readParsedEntries(Path inputPath) throws IOException {
var content = FileUtils.readFileContent(inputPath);
var entries = new ArrayList<ProjectEntry>();
var sections = content.split(Constants.SECTION_SEPARATOR);
for (var section : sections) {
if (section.isBlank()) {
continue;
}
String name = null, url = null, description = null;
int linesToSkip = 0;
for (var line : section.lines().toArray(String[]::new)) {
if (line.startsWith(Constants.NAME_PREFIX)) {
name = line.substring(Constants.NAME_PREFIX.length());
} else if (line.startsWith(Constants.URL_PREFIX)) {
url = line.substring(Constants.URL_PREFIX.length());
} else if (line.startsWith(Constants.DESC_PREFIX)) {
description = line.substring(Constants.DESC_PREFIX.length());
} else if (line.startsWith(Constants.SKIP_PREFIX)) {
linesToSkip = Integer.parseInt(line.substring(Constants.SKIP_PREFIX.length()));
}
}
if (name != null && url != null) {
entries.add(new ProjectEntry(
name,
url,
description != null ? description : "",
linesToSkip,
""
));
}
}
return entries;
}
/**
* Reads existing stats mappings from file.
*/
Map<String, StatsMapping> readStatsMappings(Path statsPath) throws IOException {
var content = FileUtils.readFileContent(statsPath);
var mappings = new HashMap<String, StatsMapping>();
for (var section : content.split("\n\n")) {
if (section.isBlank()) {
continue;
}
String repo = null, name = null, starsText = null, lastCommitText = null, licenseText = null;
for (var line : section.lines().toArray(String[]::new)) {
if (line.trim().isEmpty()) {
continue;
}
if (line.startsWith(Constants.REPO_PREFIX)) {
repo = line.substring(Constants.REPO_PREFIX.length());
} else if (line.startsWith(Constants.NAME_PREFIX)) {
name = line.substring(Constants.NAME_PREFIX.length());
} else if (line.startsWith(Constants.STARS_PREFIX)) {
starsText = line.substring(Constants.STARS_PREFIX.length());
} else if (line.startsWith(Constants.COMMIT_PREFIX)) {
lastCommitText = line.substring(Constants.COMMIT_PREFIX.length());
} else if (line.startsWith(Constants.LICENSE_PREFIX)) {
licenseText = line.substring(Constants.LICENSE_PREFIX.length());
}
}
if (repo != null && name != null) {
mappings.put(name, new StatsMapping(
name,
repo,
starsText != null ? starsText : Constants.NO_STATS,
lastCommitText != null ? lastCommitText : Constants.NO_STATS,
licenseText != null ? licenseText : Constants.NO_STATS
));
}
}
return mappings;
}
/**
* Generates stats mappings for GitHub repositories by fetching data from GitHub API.
* Reuses existing mappings when available.
*/
List<StatsMapping> generateStatsMappings(List<ProjectEntry> entries, Map<String, StatsMapping> existingMappings) throws IOException, InterruptedException {
var mappings = new ArrayList<StatsMapping>();
var total = entries.stream().filter(ProjectEntry::isGitHubRepo).count();
var processed = 0;
var needsApiCall = false;
// First pass: check if we need any API calls
for (var entry : entries) {
if (!entry.isGitHubRepo()) {
continue;
}
var repo = entry.getGitHubRepo();
if (repo == null) {
continue;
}
var existing = existingMappings.get(entry.name());
if (existing == null || !existing.repo().equals(repo) ||
existing.starsText().equals(Constants.NO_STATS) ||
existing.lastCommitText().equals(Constants.NO_STATS) ||
existing.starsText().equals(Constants.INVALID_REPO) ||
existing.lastCommitText().equals(Constants.INVALID_REPO)) {
needsApiCall = true;
break;
}
}
// Only require PAT and create HttpClient if we need to fetch data
String githubToken = null;
HttpClient client = null;
if (needsApiCall) {
githubToken = System.getenv("PAT");
if (githubToken == null || githubToken.isBlank()) {
System.err.println("ERROR: PAT environment variable is required!");
System.err.println(" Without a PAT, the rate limit is only 60 requests/hour (not enough for all repositories)");
System.err.println(" Please set PAT environment variable:");
System.err.println(" export PAT=your_token_here");
System.exit(1);
}
System.out.println("Using GitHub PAT");
client = HttpClient.newHttpClient();
} else {
System.out.println("All data available in cache, skipping API calls");
}
for (var entry : entries) {
if (!entry.isGitHubRepo()) {
mappings.add(new StatsMapping(
entry.name(),
"",
Constants.NO_STATS,
Constants.NO_STATS,
Constants.NO_STATS
));
continue;
}
var repo = entry.getGitHubRepo();
if (repo == null) {
mappings.add(new StatsMapping(
entry.name(),
"",
Constants.NO_STATS,
Constants.NO_STATS,
Constants.NO_STATS
));
continue;
}
processed++;
// Check if we already have complete data for this repository
var existing = existingMappings.get(entry.name());
if (existing != null && existing.repo().equals(repo) &&
!existing.starsText().equals(Constants.NO_STATS) &&
!existing.lastCommitText().equals(Constants.NO_STATS) &&
!existing.starsText().equals(Constants.INVALID_REPO) &&
!existing.lastCommitText().equals(Constants.INVALID_REPO)) {
mappings.add(existing);
if (processed % 50 == 0) {
System.out.printf("Processing %d/%d repositories... (using cached data)%n", processed, total);
}
continue;
}
if (processed % 10 == 0) {
System.out.printf("Processing %d/%d repositories... (fetching from API)%n", processed, total);
}
var stats = fetchRepoStats(client, repo, githubToken, processed);
mappings.add(new StatsMapping(
entry.name(),
repo,
stats.starsText(),
stats.lastCommitText(),
stats.licenseText()
));
// Rate limiting: Add a 0.5 second delay to avoid hitting the limit too quickly
Thread.sleep(500);
}
return mappings;
}
/**
* Builds an authenticated HTTP request for GitHub API.
*/
HttpRequest buildGitHubRequest(String uri, String githubToken) {
var builder = HttpRequest.newBuilder()
.uri(URI.create(uri))
.header("Accept", "application/vnd.github.v3+json");
if (githubToken != null && !githubToken.isBlank()) {
builder.header("Authorization", "Bearer %s".formatted(githubToken));
}
return builder.GET().build();
}
/**
* Fetches stars, last commit date, and license in a single API request.
*/
record RepoStats(String starsText, String lastCommitText, String licenseText) {}
RepoStats fetchRepoStats(HttpClient client, String repo, String githubToken, int requestNumber) {
try {
var request = buildGitHubRequest("https://api.github.com/repos/" + repo, githubToken);
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
return switch (response.statusCode()) {
case 200 -> {
var body = response.body();
var starsMatcher = Constants.STARS_PATTERN.matcher(body);
var pushedAtMatcher = Constants.PUSHED_AT_PATTERN.matcher(body);
var licenseMatcher = Constants.LICENSE_PATTERN.matcher(body);
var starsText = starsMatcher.find()
? formatStars(Long.parseLong(starsMatcher.group(1)))
: Constants.NO_STATS;
var lastCommitText = pushedAtMatcher.find()
? formatDate(pushedAtMatcher.group(1))
: Constants.NO_STATS;
var licenseText = licenseMatcher.find() && licenseMatcher.group(1) != null
? formatLicense(licenseMatcher.group(1))
: Constants.NO_STATS;
yield new RepoStats(starsText, lastCommitText, licenseText);
}
case 404 -> {
System.err.printf("ERROR: Repository %s not found%n", repo);
yield new RepoStats(Constants.INVALID_REPO, Constants.INVALID_REPO, Constants.NO_STATS);
}
case 403 -> {
System.err.printf("ERROR: Access forbidden for %s%n", repo);
yield new RepoStats(Constants.NO_STATS, Constants.NO_STATS, Constants.NO_STATS);
}
default -> new RepoStats(Constants.NO_STATS, Constants.NO_STATS, Constants.NO_STATS);
};
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return new RepoStats(Constants.NO_STATS, Constants.NO_STATS, Constants.NO_STATS);
} catch (Exception e) {
System.err.printf("ERROR fetching stats for %s: %s%n", repo, e.getMessage());
return new RepoStats(Constants.NO_STATS, Constants.NO_STATS, Constants.NO_STATS);
}
}
/**
* Formats stars count as text.
*/
String formatStars(long stars) {
if (stars >= 1000) {
return "%.1fk".formatted(stars / 1000.0);
}
return String.valueOf(stars);
}
/**
* Formats license SPDX ID for display.
*/
String formatLicense(String spdxId) {
if (spdxId == null || spdxId.isBlank() || spdxId.equals("NOASSERTION")) {
return Constants.NO_STATS;
}
return spdxId;
}
/**
* Formats date as relative time (e.g., "2d", "1mo") or absolute date.
*/
String formatDate(String dateStr) {
try {
var formatter = DateTimeFormatter.ISO_DATE_TIME;
var dateTime = ZonedDateTime.parse(dateStr, formatter);
var now = ZonedDateTime.now();
var duration = Duration.between(dateTime, now);
var days = duration.toDays();
if (days == 0) {
var hours = duration.toHours();
if (hours == 0) {
var minutes = duration.toMinutes();
return minutes <= 1 ? "now" : minutes + "m";
}
return hours + "h";
} else if (days < 30) {
return days + "d";
} else if (days < 365) {
var months = days / 30;
return months + "mo";
} else {
var years = days / 365;
return years + "y";
}
} catch (Exception e) {
// If parsing fails, try to extract just the date part
try {
var datePart = dateStr.substring(0, 10); // YYYY-MM-DD
return datePart;
} catch (Exception e2) {
return Constants.NO_STATS;
}
}
}
/**
* Writes stats mappings to a file.
*/
void writeStatsMappings(Path outputPath, List<StatsMapping> mappings) throws IOException {
var content = mappings.stream()
.map(m -> """
%s%s
%s%s
%s%s
%s%s
%s%s
""".formatted(
Constants.REPO_PREFIX, m.repo(),
Constants.NAME_PREFIX, m.name(),
Constants.STARS_PREFIX, m.starsText(),
Constants.COMMIT_PREFIX, m.lastCommitText(),
Constants.LICENSE_PREFIX, m.licenseText()
).trim())
.collect(Collectors.joining("\n\n"));
FileUtils.writeOutputFile(outputPath, content);
}
/**
* Stats mapping for GitHub repository data.
*/
record StatsMapping(
String name,
String repo,
String starsText,
String lastCommitText,
String licenseText
) {}