tryParse static method
Parse a version string into a SemVer.
Supports formats like "1.2.3", "1.2.3-beta.1", "1.2.3+sha123". Returns null if the string cannot be parsed.
Implementation
static SemVer? tryParse(String version) {
// Coerce: strip leading non-numeric characters (like 'v')
var v = version.trim();
if (v.startsWith('v') || v.startsWith('V')) {
v = v.substring(1);
}
// Split off build metadata
String? build;
final plusIdx = v.indexOf('+');
if (plusIdx >= 0) {
build = v.substring(plusIdx + 1);
v = v.substring(0, plusIdx);
}
// Split off pre-release
String? pre;
final dashIdx = v.indexOf('-');
if (dashIdx >= 0) {
pre = v.substring(dashIdx + 1);
v = v.substring(0, dashIdx);
}
final parts = v.split('.');
if (parts.length < 3) {
// Try to coerce: pad missing parts with 0
while (parts.length < 3) {
parts.add('0');
}
}
final major = int.tryParse(parts[0]);
final minor = int.tryParse(parts[1]);
final patch = int.tryParse(parts[2]);
if (major == null || minor == null || patch == null) return null;
return SemVer(
major: major,
minor: minor,
patch: patch,
preRelease: pre,
buildMetadata: build,
);
}