packageVersion top-level property
String
get
packageVersion
Gets the package version from pubspec.yaml
This function locates the pubspec.yaml file relative to the current script's location and extracts the version number. It handles both running from source and from a compiled executable.
Implementation
String get packageVersion {
try {
// Get the directory of the current script
final scriptDir = File(Platform.script.toFilePath()).parent;
// Try to find pubspec.yaml by walking up directories
File? pubspecFile;
var currentDir = scriptDir;
// Walk up until we find pubspec.yaml or hit the root
while (currentDir.path != currentDir.parent.path) {
final file = File(path.join(currentDir.path, 'pubspec.yaml'));
if (file.existsSync()) {
pubspecFile = file;
break;
}
currentDir = currentDir.parent;
}
if (pubspecFile == null) {
return 'unknown'; // Fallback if pubspec.yaml cannot be found
}
// Read and parse the pubspec.yaml content
final content = pubspecFile.readAsStringSync();
// Extract version using a simple regex
// This looks for a line starting with 'version:' followed by the version number
final versionMatch =
RegExp(r'^version:\s*(.+)$', multiLine: true).firstMatch(content);
return versionMatch?.group(1)?.trim() ?? 'unknown';
} catch (e) {
// Return 'unknown' if any error occurs during version detection
return 'unknown';
}
}