writeDartVersion static method
Updates the dart entry in the .tool-versions file in directory to
version, preserving all other tool entries.
Does nothing if the file does not exist.
Implementation
static void writeDartVersion(
final Directory directory,
final String version,
) {
final file = File(p.join(directory.path, _fileName));
if (!file.existsSync()) return;
final String content;
try {
content = file.readAsStringSync();
} catch (_) {
return;
}
final lines = content.split('\n');
var found = false;
final updated = lines.map((final line) {
final trimmed = line.trim();
if (trimmed.startsWith('#') || trimmed.isEmpty) return line;
final parts = trimmed.split(RegExp(r'\s+'));
if (parts.length >= 2 && parts[0] == 'dart') {
found = true;
return 'dart $version';
}
return line;
}).toList();
if (!found) {
final insertAt = updated.isNotEmpty && updated.last.isEmpty
? updated.length - 1
: updated.length;
updated.insert(insertAt, 'dart $version');
}
file.writeAsStringSync(updated.join('\n'));
}