-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVersion.java
More file actions
103 lines (80 loc) · 2.87 KB
/
Version.java
File metadata and controls
103 lines (80 loc) · 2.87 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
package com.eternalcode.commons.updater;
import java.util.Arrays;
import org.jetbrains.annotations.NotNull;
public class Version implements Comparable<Version> {
private static final int DEFAULT_VERSION_COMPONENT_VALUE = 0;
private final String value;
private final int[] versionComponents;
public Version(String version) {
if (version == null || version.trim().isEmpty()) {
throw new IllegalArgumentException("Version cannot be null or empty");
}
this.value = version.trim();
this.versionComponents = parseVersion(this.value);
}
private static String cleanVersion(String version) {
String cleaned = version.startsWith("v") ? version.substring(1) : version;
int dashIndex = cleaned.indexOf('-');
if (dashIndex > 0) {
return cleaned.substring(0, dashIndex);
}
return cleaned;
}
private int[] parseVersion(String version) {
String cleaned = cleanVersion(version);
String[] rawVersionComponents = cleaned.split("\\.");
int[] versionComponents = new int[rawVersionComponents.length];
for (int i = 0; i < rawVersionComponents.length; i++) {
try {
versionComponents[i] = Integer.parseInt(rawVersionComponents[i]);
}
catch (NumberFormatException exception) {
throw new IllegalArgumentException("Invalid version format: " + version);
}
}
return versionComponents;
}
@Override
public int compareTo(@NotNull Version other) {
int maxLength = Math.max(this.versionComponents.length, other.versionComponents.length);
for (int i = 0; i < maxLength; i++) {
int thisComponent = getComponentAtIndex(i, this);
int otherComponent = getComponentAtIndex(i, other);
int result = Integer.compare(thisComponent, otherComponent);
if (result != 0) {
return result;
}
}
return 0;
}
private int getComponentAtIndex(int index, Version version) {
return index < version.versionComponents.length
? version.versionComponents[index]
: DEFAULT_VERSION_COMPONENT_VALUE;
}
public boolean isNewerThan(Version other) {
return this.compareTo(other) > 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Version version = (Version) obj;
return this.compareTo(version) == 0;
}
@Override
public int hashCode() {
return Arrays.hashCode(versionComponents);
}
public boolean isSnapshot() {
return this.value.contains("-SNAPSHOT");
}
@Override
public String toString() {
return value;
}
}