-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathVersion.java
More file actions
491 lines (412 loc) · 18 KB
/
Version.java
File metadata and controls
491 lines (412 loc) · 18 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package org.perlonjava.runtime.perlmodule;
import org.perlonjava.runtime.operators.ReferenceOperators;
import org.perlonjava.runtime.operators.VersionHelper;
import org.perlonjava.runtime.runtimetypes.*;
import static org.perlonjava.runtime.runtimetypes.GlobalVariable.getGlobalVariable;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarCache.*;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarType.DOUBLE;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarType.UNDEF;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarType.VSTRING;
// TODO - create test cases
// $ perl -E ' use version; say version->declare("v1.2.3"); say version->declare("1.2.3"); say version->declare("1.2"); say version->declare("1.2.3.4"); say version->declare("1"); say version->declare(" 1.2.4 ")->normal; say version->new(1.2); say version->new(1.2)->normal; say version->new("1.200000"); say version->new("1.2"); '
// v1.2.3
// 1.2.3
// v1.2
// 1.2.3.4
// 1
// v1.2.4
// 1.2
// v1.200.0
// 1.200000
// 1.2
/**
* The {@code Version} class provides methods for handling version objects
* within a Perl-like runtime environment. It extends {@link PerlModuleBase} and
* offers functionality to create, parse, and compare version numbers.
*/
public class Version extends PerlModuleBase {
/**
* Constructs a new {@code Version} instance and initializes the module with the name "version".
*/
public Version() {
super("version", false);
}
/**
* Initializes the Version module by registering methods.
*/
public static void initialize() {
Version version = new Version();
try {
version.registerMethod("declare", "$");
version.registerMethod("qv", "$");
version.registerMethod("_VERSION", "VERSION", "$$");
version.registerMethod("vcmp", "VCMP", "$$");
version.registerMethod("numify", "$");
version.registerMethod("normal", "$");
version.registerMethod("to_decimal", "$");
version.registerMethod("to_dotted_decimal", "$");
version.registerMethod("tuple", "$");
version.registerMethod("from_tuple", "@");
version.registerMethod("stringify", "$");
version.registerMethod("parse", "$");
version.registerMethod("new", "declare", "$");
} catch (NoSuchMethodException e) {
System.err.println("Warning: Missing Version method: " + e.getMessage());
}
}
/**
* Parses a version string into a version object.
*/
public static RuntimeList parse(RuntimeArray args, int ctx) {
return parseInternal(args, ctx, false);
}
/**
* Internal parse method with option to force qv mode.
* @param args The arguments array
* @param ctx The runtime context
* @param forceQv If true, always set qv=true (used by qv() function)
*/
private static RuntimeList parseInternal(RuntimeArray args, int ctx, boolean forceQv) {
if (args.size() < 2) {
throw new IllegalStateException("version->parse() requires an argument");
}
RuntimeScalar versionStr = args.get(1);
String version;
// Preserve the original version string before any modifications
RuntimeScalar originalVersionStr;
// Track whether the original input was a v-string
boolean isVString = false;
// Handle undef - treat as version 0 (Perl behavior)
if (versionStr.type == UNDEF) {
version = "0";
originalVersionStr = new RuntimeScalar("0");
}
// Handle VSTRING type (bare v-strings like v1.2.3)
else if (versionStr.type == VSTRING) {
isVString = true;
// Convert VSTRING to dotted format
String vstringValue = versionStr.value.toString();
StringBuilder dotted = new StringBuilder("v");
for (int i = 0; i < vstringValue.length(); i++) {
if (i > 0) dotted.append(".");
dotted.append((int) vstringValue.charAt(i));
}
version = dotted.toString();
originalVersionStr = new RuntimeScalar(version);
} else {
version = versionStr.toString().trim();
// Handle literal string "undef" - treat as version 0 (Perl behavior)
if (version.equals("undef")) {
version = "0";
originalVersionStr = new RuntimeScalar("0");
} else {
if (version.isEmpty()) {
throw new PerlCompilerException("Invalid version format (version required)");
}
// Check if original starts with 'v'
isVString = version.startsWith("v");
// Validate version format - check for multiple underscores
int underscoreCount = 0;
for (char c : version.toCharArray()) {
if (c == '_') underscoreCount++;
}
if (underscoreCount > 1) {
throw new PerlCompilerException("Invalid version format (multiple underscores)");
}
// Validate version format - must contain at least one digit
// and be a valid version pattern (digits, dots, underscores, optional v prefix)
String checkVersion = isVString ? version.substring(1) : version;
checkVersion = checkVersion.replace("_", "");
// Version must start with a digit and only contain digits and dots
// (after removing v prefix and underscores)
if (!checkVersion.matches("\\d+(\\.\\d+)*")) {
throw new PerlCompilerException("Invalid version format (non-numeric data)");
}
if (versionStr.type == DOUBLE) {
// Format with enough precision but strip trailing zeros
version = String.format("%.6f", versionStr.getDouble());
// Remove trailing zeros after decimal point
if (version.contains(".")) {
version = version.replaceAll("0+$", "");
// Remove trailing dot if all decimals were zeros (e.g., "1." -> "1")
if (version.endsWith(".")) {
version = version.substring(0, version.length() - 1);
}
}
originalVersionStr = new RuntimeScalar(version);
} else {
originalVersionStr = versionStr;
}
}
}
// For qv(), prepend 'v' if not already present and set original with v prefix
if (forceQv) {
isVString = true;
if (!version.startsWith("v")) {
version = "v" + version;
}
// For qv(), the original is the v-prefixed version
originalVersionStr = new RuntimeScalar(version);
} else if (!version.startsWith("v")) {
// Count the number of dots
long dotCount = version.chars().filter(ch -> ch == '.').count();
// If exactly one dot and short, prepend "v" for internal processing
// but keep the original for stringify() and qv flag
if (dotCount == 1 && version.length() < 4) {
version = "v" + version;
// Note: originalVersionStr stays as the user's input (e.g., "1.0")
// Note: isVString remains false - this is a decimal version
}
}
// Create a blessed version object
RuntimeHash versionObj = new RuntimeHash();
// Parse the version string
if (version.startsWith("v")) {
// v-string format (either originally or for internal processing)
versionObj.put("alpha", scalarFalse);
versionObj.put("qv", getScalarBoolean(isVString));
// Parse components
String normalized = VersionHelper.normalizeVersion(new RuntimeScalar(version));
versionObj.put("version", new RuntimeScalar(normalized));
} else {
// Decimal format
boolean isAlpha = version.contains("_");
String cleanVersion = version.replace("_", "");
versionObj.put("alpha", getScalarBoolean(isAlpha));
versionObj.put("qv", scalarFalse);
// Normalize the version
String normalized = VersionHelper.normalizeVersion(new RuntimeScalar(cleanVersion));
versionObj.put("version", new RuntimeScalar(normalized));
}
versionObj.put("original", originalVersionStr);
// Bless the object
RuntimeScalar blessed = versionObj.createReference();
ReferenceOperators.bless(blessed, new RuntimeScalar("version"));
return blessed.getList();
}
/**
* Creates a dotted-decimal version object.
* This is a method that expects to be called as version->declare()
*/
public static RuntimeList declare(RuntimeArray args, int ctx) {
if (args.size() < 2) {
throw new IllegalStateException("version->declare() requires an argument");
}
// Create version object via parse
RuntimeArray parseArgs = new RuntimeArray();
parseArgs.push(args.get(0)); // class name
parseArgs.push(RuntimeArray.pop(args));
return parse(parseArgs, ctx);
}
/**
* qv() - creates a dotted-decimal version object.
* Always receives class name as first argument due to how it's exported.
* qv() always sets is_qv to true, ensuring the version is treated as a v-string.
*/
public static RuntimeList qv(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("qv() requires an argument");
}
// Create version object via parseInternal with forceQv=true
RuntimeArray parseArgs = new RuntimeArray();
parseArgs.push(new RuntimeScalar("version")); // class name
parseArgs.push(RuntimeArray.pop(args));
return parseInternal(parseArgs, ctx, true); // forceQv=true
}
/**
* Returns the numified representation of the version.
*/
public static RuntimeList numify(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("numify requires an argument");
}
RuntimeScalar self = args.get(0);
RuntimeHash versionObj = self.hashDeref();
String version = versionObj.get("version").toString();
String[] parts = version.split("\\.");
if (parts.length == 0) {
return new RuntimeScalar(0.0).getList();
}
// Convert to decimal: major.minorpatch
double major = Double.parseDouble(parts[0]);
double minor = parts.length > 1 ? Double.parseDouble(parts[1]) : 0;
double patch = parts.length > 2 ? Double.parseDouble(parts[2]) : 0;
double numified = major + (minor / 1000.0) + (patch / 1000000.0);
return new RuntimeScalar(numified).getList();
}
/**
* Returns the normalized dotted-decimal form with leading v.
*/
public static RuntimeList normal(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("normal requires an argument");
}
RuntimeScalar self = args.get(0);
RuntimeHash versionObj = self.hashDeref();
String version = versionObj.get("version").toString();
String[] parts = version.split("\\.");
// Ensure at least 3 components
StringBuilder normal = new StringBuilder("v");
for (int i = 0; i < 3; i++) {
if (i > 0) normal.append(".");
if (i < parts.length) {
normal.append(parts[i]);
} else {
normal.append("0");
}
}
return new RuntimeScalar(normal.toString()).getList();
}
/**
* Converts to decimal version object.
*/
public static RuntimeList to_decimal(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("to_decimal requires an argument");
}
// Get numified version
RuntimeList numified = numify(args, ctx);
// Parse it as a new version object
RuntimeArray parseArgs = new RuntimeArray();
parseArgs.push(new RuntimeScalar("version"));
parseArgs.push(numified.elements.getFirst());
return parse(parseArgs, ctx);
}
/**
* Converts to dotted decimal version object.
*/
public static RuntimeList to_dotted_decimal(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("to_dotted_decimal requires an argument");
}
// Get normalized version
RuntimeList normalized = normal(args, ctx);
// Parse it as a new version object
RuntimeArray parseArgs = new RuntimeArray();
parseArgs.push(new RuntimeScalar("version"));
parseArgs.push(normalized.elements.getFirst());
return parse(parseArgs, ctx);
}
/**
* Returns version components as a list.
*/
public static RuntimeList tuple(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("tuple requires an argument");
}
RuntimeScalar self = args.get(0);
RuntimeHash versionObj = self.hashDeref();
String version = versionObj.get("version").toString();
String[] parts = version.split("\\.");
RuntimeArray result = new RuntimeArray();
for (String part : parts) {
result.push(new RuntimeScalar(Integer.parseInt(part)));
}
return result.getList();
}
/**
* Creates a version object from a list of components.
*/
public static RuntimeList from_tuple(RuntimeArray args, int ctx) {
if (args.size() < 2) {
throw new IllegalStateException("from_tuple requires at least one component");
}
StringBuilder version = new StringBuilder("v");
for (int i = 1; i < args.size(); i++) {
if (i > 1) version.append(".");
version.append(args.get(i).toString());
}
RuntimeArray parseArgs = new RuntimeArray();
parseArgs.push(args.get(0)); // class name
parseArgs.push(new RuntimeScalar(version.toString()));
return parse(parseArgs, ctx);
}
/**
* Returns string representation of the version.
*/
public static RuntimeList stringify(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("stringify requires an argument");
}
RuntimeScalar self = args.get(0);
RuntimeHash versionObj = self.hashDeref();
// Return the original representation
return versionObj.get("original").getList();
}
/**
* Compares two version objects.
*/
public static RuntimeList VCMP(RuntimeArray args, int ctx) {
if (args.size() < 2) {
throw new IllegalStateException("vcmp requires two arguments");
}
RuntimeScalar v1 = args.get(0);
RuntimeScalar v2 = args.get(1);
// Check if arguments were swapped (third argument from overload)
boolean swapped = args.size() > 2 && args.get(2).getBoolean();
// Handle non-version objects - treat undef/empty as version 0
if (!v1.isBlessed() || !NameNormalizer.getBlessStr(v1.blessId).equals("version")) {
String v1Str = v1.toString().trim();
if (v1Str.isEmpty()) {
v1Str = "0";
}
RuntimeArray parseArgs = new RuntimeArray();
parseArgs.push(new RuntimeScalar("version"));
parseArgs.push(new RuntimeScalar(v1Str));
v1 = parse(parseArgs, RuntimeContextType.SCALAR).scalar();
}
if (!v2.isBlessed() || !NameNormalizer.getBlessStr(v2.blessId).equals("version")) {
String v2Str = v2.toString().trim();
if (v2Str.isEmpty()) {
v2Str = "0";
}
RuntimeArray parseArgs = new RuntimeArray();
parseArgs.push(new RuntimeScalar("version"));
parseArgs.push(new RuntimeScalar(v2Str));
v2 = parse(parseArgs, RuntimeContextType.SCALAR).scalar();
}
// Get normalized versions
RuntimeHash obj1 = v1.hashDeref();
RuntimeHash obj2 = v2.hashDeref();
String ver1 = obj1.get("version").toString();
String ver2 = obj2.get("version").toString();
// Compare versions
String[] v1Parts = ver1.split("\\.");
String[] v2Parts = ver2.split("\\.");
int length = Math.max(v1Parts.length, v2Parts.length);
int cmp = 0;
for (int i = 0; i < length; i++) {
int v1Part = i < v1Parts.length ? Integer.parseInt(v1Parts[i]) : 0;
int v2Part = i < v2Parts.length ? Integer.parseInt(v2Parts[i]) : 0;
if (v1Part != v2Part) {
cmp = v1Part - v2Part;
break;
}
}
// If arguments were swapped, negate the result
if (swapped) {
cmp = -cmp;
}
return new RuntimeScalar(cmp).getList();
}
/**
* Implementation of UNIVERSAL::VERSION.
*/
public static RuntimeList VERSION(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
throw new IllegalStateException("VERSION requires at least one argument");
}
RuntimeScalar pkg = args.get(0);
String packageName = pkg.toString();
// Get the package's $VERSION
RuntimeScalar hasVersion = getGlobalVariable(packageName + "::VERSION");
if (args.size() == 1) {
// Just return the version
return hasVersion.getList();
}
// Check version requirement
RuntimeScalar wantVersion = args.get(1);
RuntimeScalar result = VersionHelper.compareVersion(hasVersion, wantVersion, packageName);
return result.getList();
}
}