visual_studio.dart 17.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:process/process.dart';
6

7
import '../base/common.dart';
8
import '../base/file_system.dart';
9
import '../base/io.dart';
10
import '../base/logger.dart';
11
import '../base/platform.dart';
12
import '../base/process.dart';
13
import '../base/version.dart';
14 15 16 17
import '../convert.dart';

/// Encapsulates information about the installed copy of Visual Studio, if any.
class VisualStudio {
18
  VisualStudio({
19 20 21 22
    required FileSystem fileSystem,
    required ProcessManager processManager,
    required Platform platform,
    required Logger logger,
23 24 25 26 27 28 29 30
  }) : _platform = platform,
       _fileSystem = fileSystem,
       _processUtils = ProcessUtils(processManager: processManager, logger: logger);

  final FileSystem _fileSystem;
  final Platform _platform;
  final ProcessUtils _processUtils;

31
  /// True if Visual Studio installation was found.
32 33 34 35
  ///
  /// Versions older than 2017 Update 2 won't be detected, so error messages to
  /// users should take into account that [false] may mean that the user may
  /// have an old version rather than no installation at all.
36
  bool get isInstalled => _bestVisualStudioDetails.isNotEmpty;
37

38
  bool get isAtLeastMinimumVersion {
39
    final int? installedMajorVersion = _majorVersion;
40 41 42
    return installedMajorVersion != null && installedMajorVersion >= _minimumSupportedVersion;
  }

43 44
  /// True if there is a version of Visual Studio with all the components
  /// necessary to build the project.
45
  bool get hasNecessaryComponents => _usableVisualStudioDetails.isNotEmpty;
46 47 48

  /// The name of the Visual Studio install.
  ///
49
  /// For instance: "Visual Studio Community 2019".
50
  String get displayName => _bestVisualStudioDetails[_displayNameKey] as String;
51 52 53 54

  /// The user-friendly version number of the Visual Studio install.
  ///
  /// For instance: "15.4.0".
55
  String? get displayVersion {
56 57 58
    if (_bestVisualStudioDetails[_catalogKey] == null) {
      return null;
    }
59
    return _bestVisualStudioDetails[_catalogKey][_catalogDisplayVersionKey] as String;
60
  }
61 62

  /// The directory where Visual Studio is installed.
63
  String get installLocation => _bestVisualStudioDetails[_installationPathKey] as String;
64 65 66 67

  /// The full version of the Visual Studio install.
  ///
  /// For instance: "15.4.27004.2002".
68
  String get fullVersion => _bestVisualStudioDetails[_fullVersionKey] as String;
69

70 71 72 73
  // Properties that determine the status of the installation. There might be
  // Visual Studio versions that don't include them, so default to a "valid" value to
  // avoid false negatives.

74 75 76 77 78 79 80
  /// True if there is a complete installation of Visual Studio.
  ///
  /// False if installation is not found.
  bool get isComplete {
    if (_bestVisualStudioDetails.isEmpty) {
      return false;
    }
81
    return _bestVisualStudioDetails[_isCompleteKey] as bool? ?? true;
82
  }
83 84

  /// True if Visual Studio is launchable.
85 86 87 88 89 90
  ///
  /// False if installation is not found.
  bool get isLaunchable {
    if (_bestVisualStudioDetails.isEmpty) {
      return false;
    }
91
    return _bestVisualStudioDetails[_isLaunchableKey] as bool? ?? true;
92
  }
93 94

    /// True if the Visual Studio installation is as pre-release version.
95
  bool get isPrerelease => _bestVisualStudioDetails[_isPrereleaseKey] as bool? ?? false;
96 97

  /// True if a reboot is required to complete the Visual Studio installation.
98
  bool get isRebootRequired => _bestVisualStudioDetails[_isRebootRequiredKey] as bool? ?? false;
99

100 101 102
  /// The name of the recommended Visual Studio installer workload.
  String get workloadDescription => 'Desktop development with C++';

103 104 105
  /// Returns the highest installed Windows 10 SDK version, or null if none is
  /// found.
  ///
106
  /// For instance: 10.0.18362.0.
107 108
  String? getWindows10SDKVersion() {
    final String? sdkLocation = _getWindows10SdkLocation();
109 110 111 112 113 114 115 116
    if (sdkLocation == null) {
      return null;
    }
    final Directory sdkIncludeDirectory = _fileSystem.directory(sdkLocation).childDirectory('Include');
    if (!sdkIncludeDirectory.existsSync()) {
      return null;
    }
    // The directories in this folder are named by the SDK version.
117
    Version? highestVersion;
118 119 120 121
    for (final FileSystemEntity versionEntry in sdkIncludeDirectory.listSync()) {
      if (versionEntry.basename.startsWith('10.')) {
        // Version only handles 3 components; strip off the '10.' to leave three
        // components, since they all start with that.
122 123
        final Version? version = Version.parse(versionEntry.basename.substring(3));
        if (highestVersion == null || (version != null && version > highestVersion)) {
124 125 126 127 128 129 130 131 132 133
          highestVersion = version;
        }
      }
    }
    if (highestVersion == null) {
      return null;
    }
    return '10.$highestVersion';
  }

134 135
  /// The names of the components within the workload that must be installed.
  ///
136 137 138 139 140 141 142
  /// The descriptions of some components differ from version to version. When
  /// a supported version is present, the descriptions used will be for that
  /// version.
  List<String> necessaryComponentDescriptions() {
    return _requiredComponents().values.toList();
  }

143
  /// The consumer-facing version name of the minimum supported version.
144 145 146 147
  ///
  /// E.g., for Visual Studio 2019 this returns "2019" rather than "16".
  String get minimumVersionDescription {
    return '2019';
148 149
  }

150
  /// The path to CMake, or null if no Visual Studio installation has
151
  /// the components necessary to build.
152
  String? get cmakePath {
153
    final Map<String, dynamic> details = _usableVisualStudioDetails;
154
    if (details.isEmpty) {
155 156
      return null;
    }
157
    return _fileSystem.path.joinAll(<String>[
158
      _usableVisualStudioDetails[_installationPathKey] as String,
159 160 161 162 163 164 165 166 167
      'Common7',
      'IDE',
      'CommonExtensions',
      'Microsoft',
      'CMake',
      'CMake',
      'bin',
      'cmake.exe',
    ]);
168 169
  }

170
  /// The major version of the Visual Studio install, as an integer.
171
  int? get _majorVersion => fullVersion != null ? int.tryParse(fullVersion.split('.')[0]) : null;
172

173 174 175 176 177 178
  /// The path to vswhere.exe.
  ///
  /// vswhere should be installed for VS 2017 Update 2 and later; if it's not
  /// present then there isn't a new enough installation of VS. This path is
  /// not user-controllable, unlike the install location of Visual Studio
  /// itself.
179 180 181 182 183 184 185 186 187 188 189 190
  String get _vswherePath {
    const String programFilesEnv = 'PROGRAMFILES(X86)';
    if (!_platform.environment.containsKey(programFilesEnv)) {
      throwToolExit('%$programFilesEnv% environment variable not found.');
    }
    return _fileSystem.path.join(
      _platform.environment[programFilesEnv]!,
      'Microsoft Visual Studio',
      'Installer',
      'vswhere.exe',
    );
  }
191

192 193
  /// Workload ID for use with vswhere requirements.
  ///
194
  /// Workload ID is different between Visual Studio IDE and Build Tools.
195
  /// See https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
196 197 198 199
  static const List<String> _requiredWorkloads = <String>[
    'Microsoft.VisualStudio.Workload.NativeDesktop',
    'Microsoft.VisualStudio.Workload.VCTools'
  ];
200

201
  /// Components for use with vswhere requirements.
202 203 204
  ///
  /// Maps from component IDs to description in the installer UI.
  /// See https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
205
  Map<String, String> _requiredComponents([int? majorVersion]) {
206 207
    // The description of the C++ toolchain required by the template. The
    // component name is significantly different in different versions.
208
    // When a new major version of VS is supported, its toolchain description
209 210 211 212 213 214 215 216
    // should be added below. It should also be made the default, so that when
    // there is no installation, the message shows the string that will be
    // relevant for the most likely fresh install case).
    String cppToolchainDescription;
    switch (majorVersion ?? _majorVersion) {
      case 16:
      default:
        cppToolchainDescription = 'MSVC v142 - VS 2019 C++ x64/x86 build tools';
217
    }
218 219 220 221 222
    // The 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64' ID is assigned to the latest
    // release of the toolchain, and there can be minor updates within a given version of
    // Visual Studio. Since it changes over time, listing a precise version would become
    // wrong after each VC++ toolchain update, so just instruct people to install the
    // latest version.
223
    cppToolchainDescription += '\n   - If there are multiple build tool versions available, install the latest';
224 225
    // Things which are required by the workload (e.g., MSBuild) don't need to
    // be included here.
226 227 228
    return <String, String>{
      // The C++ toolchain required by the template.
      'Microsoft.VisualStudio.Component.VC.Tools.x86.x64': cppToolchainDescription,
229 230
      // CMake
      'Microsoft.VisualStudio.Component.VC.CMake.Project': 'C++ CMake tools for Windows',
231 232 233
    };
  }

234 235 236
  /// The minimum supported major version.
  static const int _minimumSupportedVersion = 16;  // '16' is VS 2019.

237
  /// vswhere argument to specify the minimum version.
238 239 240 241 242
  static const String _vswhereMinVersionArgument = '-version';

  /// vswhere argument to allow prerelease versions.
  static const String _vswherePrereleaseArgument = '-prerelease';

243 244 245 246 247 248 249 250 251 252 253
  // Keys in a VS details dictionary returned from vswhere.

  /// The root directory of the Visual Studio installation.
  static const String _installationPathKey = 'installationPath';

  /// The user-friendly name of the installation.
  static const String _displayNameKey = 'displayName';

  /// The complete version.
  static const String _fullVersionKey = 'installationVersion';

254 255 256 257 258
  /// Keys for the status of the installation.
  static const String _isCompleteKey = 'isComplete';
  static const String _isLaunchableKey = 'isLaunchable';
  static const String _isRebootRequiredKey = 'isRebootRequired';

259 260 261
  /// The 'catalog' entry containing more details.
  static const String _catalogKey = 'catalog';

262 263 264
  /// The key for a pre-release version.
  static const String _isPrereleaseKey = 'isPrerelease';

265 266 267 268 269
  /// The user-friendly version.
  ///
  /// This key is under the 'catalog' entry.
  static const String _catalogDisplayVersionKey = 'productDisplayVersion';

270 271 272 273 274 275 276 277 278 279
  /// The registry path for Windows 10 SDK installation details.
  static const String _windows10SdkRegistryPath = r'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\v10.0';

  /// The registry key in _windows10SdkRegistryPath for the folder where the
  /// SDKs are installed.
  static const String _windows10SdkRegistryKey = 'InstallationFolder';

  /// Returns the details dictionary for the newest version of Visual Studio.
  /// If [validateRequirements] is set, the search will be limited to versions
  /// that have all of the required workloads and components.
280
  Map<String, dynamic>? _visualStudioDetails({
281
      bool validateRequirements = false,
282 283
      List<String>? additionalArguments,
      String? requiredWorkload
284 285 286
    }) {
    final List<String> requirementArguments = validateRequirements
        ? <String>[
287 288 289 290
            if (requiredWorkload != null) ...<String>[
              '-requires',
              requiredWorkload,
            ],
291 292 293
            ..._requiredComponents(_minimumSupportedVersion).keys
          ]
        : <String>[];
294
    try {
295
      final List<String> defaultArguments = <String>[
296
        '-format', 'json',
297
        '-products', '*',
298 299
        '-utf8',
        '-latest',
300
      ];
301
      final RunResult whereResult = _processUtils.runSync(<String>[
302 303 304
        _vswherePath,
        ...defaultArguments,
        ...?additionalArguments,
305
        ...requirementArguments,
306
      ], encoding: utf8);
307
      if (whereResult.exitCode == 0) {
308
        final List<Map<String, dynamic>> installations =
309
            (json.decode(whereResult.stdout) as List<dynamic>).cast<Map<String, dynamic>>();
310 311 312 313
        if (installations.isNotEmpty) {
          return installations[0];
        }
      }
314 315
    } on ArgumentError {
      // Thrown if vswhere doesn't exist; ignore and return null below.
316 317
    } on ProcessException {
      // Ignored, return null below.
318 319
    } on FormatException {
      // may be thrown if invalid JSON is returned.
320 321 322 323
    }
    return null;
  }

324
  /// Checks if the given installation has issues that the user must resolve.
325 326 327
  ///
  /// Returns false if the required information is missing since older versions
  /// of Visual Studio might not include them.
328 329
  bool installationHasIssues(Map<String, dynamic>installationDetails) {
    assert(installationDetails != null);
330
    if (installationDetails[_isCompleteKey] != null && !(installationDetails[_isCompleteKey] as bool)) {
331 332 333
      return true;
    }

334
    if (installationDetails[_isLaunchableKey] != null && !(installationDetails[_isLaunchableKey] as bool)) {
335 336 337
      return true;
    }

338
    if (installationDetails[_isRebootRequiredKey] != null && installationDetails[_isRebootRequiredKey] as bool) {
339 340
      return true;
    }
341

342
    return false;
343 344
  }

345
  /// Returns the details dictionary for the latest version of Visual Studio
346 347
  /// that has all required components and is a supported version, or {} if
  /// there is no such installation.
348 349 350
  ///
  /// If no installation is found, the cached VS details are set to an empty map
  /// to avoid repeating vswhere queries that have already not found an installation.
351
  Map<String, dynamic>? _cachedUsableVisualStudioDetails;
352
  Map<String, dynamic> get _usableVisualStudioDetails {
353
    if (_cachedUsableVisualStudioDetails != null) {
354
      return _cachedUsableVisualStudioDetails!;
355
    }
356 357 358 359
    final List<String> minimumVersionArguments = <String>[
      _vswhereMinVersionArgument,
      _minimumSupportedVersion.toString(),
    ];
360
    Map<String, dynamic>? visualStudioDetails;
361 362 363 364 365 366 367 368 369 370 371
    // Check in the order of stable VS, stable BT, pre-release VS, pre-release BT
    for (final bool checkForPrerelease in <bool>[false, true]) {
      for (final String requiredWorkload in _requiredWorkloads) {
        visualStudioDetails ??= _visualStudioDetails(
          validateRequirements: true,
          additionalArguments: checkForPrerelease
              ? <String>[...minimumVersionArguments, _vswherePrereleaseArgument]
              : minimumVersionArguments,
          requiredWorkload: requiredWorkload);
      }
    }
372 373 374 375 376 377

    if (visualStudioDetails != null) {
      if (installationHasIssues(visualStudioDetails)) {
        _cachedAnyVisualStudioDetails = visualStudioDetails;
      } else {
        _cachedUsableVisualStudioDetails = visualStudioDetails;
378 379
      }
    }
380
    _cachedUsableVisualStudioDetails ??= <String, dynamic>{};
381
    return _cachedUsableVisualStudioDetails!;
382 383 384
  }

  /// Returns the details dictionary of the latest version of Visual Studio,
385 386
  /// regardless of components and version, or {} if no such installation is
  /// found.
387
  ///
388 389 390
  /// If no installation is found, the cached VS details are set to an empty map
  /// to avoid repeating vswhere queries that have already not found an
  /// installation.
391
  Map<String, dynamic>? _cachedAnyVisualStudioDetails;
392
  Map<String, dynamic> get _anyVisualStudioDetails {
393 394
    // Search for all types of installations.
    _cachedAnyVisualStudioDetails ??= _visualStudioDetails(
395
        additionalArguments: <String>[_vswherePrereleaseArgument, '-all']);
396 397
    // Add a sentinel empty value to avoid querying vswhere again.
    _cachedAnyVisualStudioDetails ??= <String, dynamic>{};
398
    return _cachedAnyVisualStudioDetails!;
399 400 401
  }

  /// Returns the details dictionary of the best available version of Visual
402 403 404
  /// Studio.
  ///
  /// If there's a version that has all the required components, that
405
  /// will be returned, otherwise returns the latest installed version (if any).
406
  Map<String, dynamic> get _bestVisualStudioDetails {
407
    if (_usableVisualStudioDetails.isNotEmpty) {
408 409 410 411
      return _usableVisualStudioDetails;
    }
    return _anyVisualStudioDetails;
  }
412 413 414

  /// Returns the installation location of the Windows 10 SDKs, or null if the
  /// registry doesn't contain that information.
415
  String? _getWindows10SdkLocation() {
416 417 418 419 420 421 422 423 424 425
    try {
      final RunResult result = _processUtils.runSync(<String>[
        'reg',
        'query',
        _windows10SdkRegistryPath,
        '/v',
        _windows10SdkRegistryKey,
      ]);
      if (result.exitCode == 0) {
        final RegExp pattern = RegExp(r'InstallationFolder\s+REG_SZ\s+(.+)');
426
        final RegExpMatch? match = pattern.firstMatch(result.stdout);
427
        if (match != null) {
428
          return match.group(1)!.trim();
429 430
        }
      }
431 432
    } on ArgumentError {
      // Thrown if reg somehow doesn't exist; ignore and return null below.
433 434 435 436 437 438 439 440 441 442
    } on ProcessException {
      // Ignored, return null below.
    }
    return null;
  }

  /// Returns the highest-numbered SDK version in [dir], which should be the
  /// Windows 10 SDK installation directory.
  ///
  /// Returns null if no Windows 10 SDKs are found.
443
  String? findHighestVersionInSdkDirectory(Directory dir) {
444 445 446 447 448
    // This contains subfolders that are named by the SDK version.
    final Directory includeDir = dir.childDirectory('Includes');
    if (!includeDir.existsSync()) {
      return null;
    }
449
    Version? highestVersion;
450 451 452 453 454 455
    for (final FileSystemEntity versionEntry in includeDir.listSync()) {
      if (!versionEntry.basename.startsWith('10.')) {
        continue;
      }
      // Version only handles 3 components; strip off the '10.' to leave three
      // components, since they all start with that.
456 457
      final Version? version = Version.parse(versionEntry.basename.substring(3));
      if (highestVersion == null || (version != null && version > highestVersion)) {
458 459 460 461 462 463
        highestVersion = version;
      }
    }
    // Re-add the leading '10.' that was removed for comparison.
    return highestVersion == null ? null : '10.$highestVersion';
  }
464
}