installedXcodeVersions function

Future<Set<String>> installedXcodeVersions()

The versions of every Xcode on this Mac: the selected one and each Xcode*.app in the Applications folders.

Implementation

Future<Set<String>> installedXcodeVersions() async {
  final home = Platform.environment['HOME'] ?? '.';
  final plists = <String>{};
  for (final apps in ['/Applications', '$home/Applications']) {
    final d = Directory(apps);
    if (!d.existsSync()) continue;
    for (final app in d.listSync().whereType<Directory>().where((a) => a.path.contains('/Xcode'))) {
      plists.add('${app.path}/Contents/version.plist');
    }
  }
  try {
    final selected =
        await runBounded('xcode-select', ['-p'], timeout: const Duration(seconds: 5), phase: 'xcode-select');
    final dir = '${selected.stdout}'.trim();
    if (dir.endsWith('/Developer')) plists.add('${dir.substring(0, dir.length - '/Developer'.length)}/version.plist');
  } on Object {
    return const {};
  }
  final versions = <String>{};
  for (final p in plists.where((p) => File(p).existsSync())) {
    try {
      final r = await runBounded('plutil', ['-extract', 'CFBundleShortVersionString', 'raw', '-o', '-', p],
          timeout: const Duration(seconds: 5), phase: 'plutil reading an Xcode version');
      final v = '${r.stdout}'.trim();
      if (r.exitCode == 0 && v.isNotEmpty) versions.add(v);
    } on Object {
      continue;
    }
  }
  return versions;
}