writeVersion method
Writes newVersion into pubspecFile preserving all unrelated formatting and comments.
Implementation
void writeVersion(File pubspecFile, ProjectVersion newVersion) {
if (!pubspecFile.existsSync()) {
throw ValidationException(
'pubspec.yaml not found at path "${pubspecFile.path}".');
}
final lines = pubspecFile.readAsLinesSync();
bool updated = false;
final updatedLines = <String>[];
for (final line in lines) {
final trimmed = line.trim();
if (!updated &&
trimmed.startsWith('version:') &&
!trimmed.startsWith('#')) {
final leadingSpaces = line.substring(0, line.indexOf('version:'));
updatedLines.add('${leadingSpaces}version: $newVersion');
updated = true;
} else {
updatedLines.add(line);
}
}
if (!updated) {
throw const ValidationException(
'Failed to locate "version:" line in pubspec.yaml to update.');
}
pubspecFile.writeAsStringSync('${updatedLines.join('\n')}\n');
}