Add windows build version detection (#154797)

With this PR flutter doctor will report the actual Windows version. This
resolves #154796

<!-- *If you had to change anything in the [flutter/tests] repo, include
a link to the migration guide as per the [breaking change policy].* -->

The flutter doctor result is with this patch like this:
```
[√] Flutter (Channel stable, 3.24.2, on Microsoft Windows [Version 10.0.22631.4037], locale de-DE)
[√] Windows Version (Windows 11 - 23H2)
[√] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[√] Chrome - develop for the web
[√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.8.3)
[√] Android Studio (version 2024.1)
[√] Connected device (3 available)
[√] Network resources

• No issues found!
```

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md

---------

Co-authored-by: Andrew Kolos <andrewrkolos@gmail.com>
This commit is contained in:
René Kilczan
2024-10-22 21:53:08 +02:00
committed by GitHub
parent e38eb756bc
commit 48149781f2
3 changed files with 316 additions and 15 deletions

View File

@@ -142,6 +142,10 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {
WindowsVersionValidator(
operatingSystemUtils: globals.os,
processLister: ProcessLister(globals.processManager),
versionExtractor: WindowsVersionExtractor(
processManager: globals.processManager,
logger: globals.logger,
),
),
if (androidWorkflow!.appliesToHostPlatform)
GroupedValidator(<DoctorValidator>[androidValidator!, androidLicenseValidator!]),

View File

@@ -5,6 +5,7 @@
import 'package:process/process.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../doctor_validator.dart';
@@ -16,8 +17,8 @@ const List<String> kUnsupportedVersions = <String>[
];
/// Regex pattern for identifying line from systeminfo stdout with windows version
/// (ie. 10.5.4123)
const String kWindowsOSVersionSemVerPattern = r'([0-9]+)\.([0-9]+)\.([0-9\.]+)';
/// (ie. 10.0.22631.4037)
const String kWindowsOSVersionSemVerPattern = r'([0-9]+)\.([0-9]+)\.([0-9]+)\.?([0-9\.]+)?';
/// Regex pattern for identifying a running instance of the Topaz OFD process.
/// This is a known process that interferes with the build toolchain.
@@ -29,12 +30,18 @@ class WindowsVersionValidator extends DoctorValidator {
const WindowsVersionValidator({
required OperatingSystemUtils operatingSystemUtils,
required ProcessLister processLister,
required WindowsVersionExtractor versionExtractor,
}) : _operatingSystemUtils = operatingSystemUtils,
_processLister = processLister,
_versionExtractor = versionExtractor,
super('Windows Version');
// See https://learn.microsoft.com/en-us/windows/release-health/windows11-release-information
static const int _lowestWindows11BuildNumber = 22000;
final OperatingSystemUtils _operatingSystemUtils;
final ProcessLister _processLister;
final WindowsVersionExtractor _versionExtractor;
Future<ValidationResult> _topazScan() async {
if (!_processLister.canRunPowershell()) {
@@ -86,7 +93,18 @@ class WindowsVersionValidator extends DoctorValidator {
if (matches.length == 1 &&
!kUnsupportedVersions.contains(matches.elementAt(0).group(1))) {
windowsVersionStatus = ValidationType.success;
statusInfo = 'Installed version of Windows is version 10 or higher';
final WindowsVersionExtractionResult details = await _versionExtractor.getDetails();
String? caption = details.caption;
if (caption == null || caption.isEmpty) {
final bool isWindows11 = int.parse(matches.elementAt(0).group(3)!) > _lowestWindows11BuildNumber;
if (isWindows11) {
caption = 'Windows 11 or higher';
} else {
caption = 'Windows 10';
}
}
statusInfo = <String?>[caption, details.displayVersion, details.releaseId]
.where((String? part) => part != null).join(', ');
// Check if the Topaz OFD security module is running, and warn the user if it is.
// See https://github.com/flutter/flutter/issues/121366
@@ -138,3 +156,88 @@ class ProcessLister {
throw StateError('Failed to find $powershell or $pwsh on PATH');
}
}
/// This helper class takes the Windows edition and processor architecture from the Windows management interface (WMI)
/// with the wmic command. The Windows ReleaseId and DisplayVersion are taken from the registry key
/// HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion via the reg command. The extracted data are caption (consists of
/// the edition and the processor architecture), releaseId and displayVersion and are returned via the
/// [WindowsVersionExtractionResult] class.
class WindowsVersionExtractor {
WindowsVersionExtractor({
required ProcessManager processManager,
required Logger logger,
}) : _logger = logger, _processManager = processManager;
final ProcessManager _processManager;
final Logger _logger;
Future<WindowsVersionExtractionResult> getDetails() async {
String? caption, releaseId, displayVersion;
try {
final ProcessResult captionResult = await _processManager.run(
<String>['wmic', 'os', 'get', 'Caption,OSArchitecture'],
);
if (captionResult.exitCode == 0) {
final String? output = captionResult.stdout as String?;
if (output != null) {
final List<String> parts = output.split('\n');
if (parts.length >= 2) {
caption = parts[1].replaceAll('Microsoft Windows', '').replaceAll(' ', ' ').trim();
}
}
}
} on ProcessException catch (e) {
_logger.printTrace('Failed to get Caption and OSArchitecture from WMI: $e');
}
try {
final ProcessResult osDetails = await _processManager.run(
<String>['reg', 'query', r'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion', '/t', 'REG_SZ'],
);
if (osDetails.exitCode == 0) {
final String? output = osDetails.stdout as String?;
if (output != null) {
final Map<String, String> data = Map<String, String>.fromEntries(
output.split('\n').where((String line) => line.contains('REG_SZ')).map((String line) {
final List<String> parts = line.split('REG_SZ');
return MapEntry<String, String>(parts.first.trim(), parts.last.trim());
}));
releaseId = data['ReleaseId'];
displayVersion = data['DisplayVersion'];
}
}
} on ProcessException catch (e) {
_logger.printTrace('Failed to get ReleaseId and DisplayVersion from registry: $e');
}
return WindowsVersionExtractionResult(
caption: caption,
releaseId: releaseId,
displayVersion: displayVersion,
);
}
}
/// The result of the Windows version extraction. Typically values would be for [caption] e.g. "11 Pro 64-bit", for
/// [releaseId] e.g. "2009" and for [displayVersion] e.g. "22H2". All values could be null when the extraction fails.
final class WindowsVersionExtractionResult {
WindowsVersionExtractionResult({
required this.caption,
required this.releaseId,
required this.displayVersion,
});
factory WindowsVersionExtractionResult.empty() {
return WindowsVersionExtractionResult(
caption: null,
releaseId: null,
displayVersion: null,
);
}
final String? caption;
final String? releaseId;
final String? displayVersion;
}

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/os.dart';
import 'package:flutter_tools/src/doctor_validator.dart';
import 'package:flutter_tools/src/windows/windows_version_validator.dart';
@@ -10,6 +11,7 @@ import 'package:test/fake.dart';
import '../src/common.dart';
import '../src/context.dart';
import '../src/fake_process_manager.dart';
/// Fake [_WindowsUtils] to use for testing
class FakeValidOperatingSystemUtils extends Fake
@@ -58,10 +60,10 @@ FakeProcessLister powershellUnavailable() {
/// The expected validation result object for
/// a passing windows version test
const ValidationResult validWindows10ValidationResult = ValidationResult(
const ValidationResult validWindows11ValidationResult = ValidationResult(
ValidationType.success,
<ValidationMessage>[],
statusInfo: 'Installed version of Windows is version 10 or higher',
statusInfo: '11 Pro 64-bit, 23H2, 2009',
);
/// The expected validation result object for
@@ -100,19 +102,37 @@ const ValidationResult getProcessFailed = ValidationResult(
statusInfo: 'Problem detected with Windows installation',
);
class FakeVersionExtractor extends Fake implements WindowsVersionExtractor {
FakeVersionExtractor({required this.mockData});
FakeVersionExtractor.win11ProX64()
: this(
mockData: WindowsVersionExtractionResult(
caption: '11 Pro 64-bit',
releaseId: '2009',
displayVersion: '23H2'),
);
final WindowsVersionExtractionResult mockData;
@override
Future<WindowsVersionExtractionResult> getDetails() async {
return mockData;
}
}
void main() {
testWithoutContext('Successfully running windows version check on windows 10',
() async {
final WindowsVersionValidator windowsVersionValidator =
WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(),
processLister: ofdNotRunning());
processLister: ofdNotRunning(),
versionExtractor: FakeVersionExtractor.win11ProX64());
final ValidationResult result = await windowsVersionValidator.validate();
expect(result.type, validWindows10ValidationResult.type,
expect(result.type, validWindows11ValidationResult.type,
reason: 'The ValidationResult type should be the same (installed)');
expect(result.statusInfo, validWindows10ValidationResult.statusInfo,
expect(result.statusInfo, validWindows11ValidationResult.statusInfo,
reason: 'The ValidationResult statusInfo messages should be the same');
});
@@ -123,13 +143,14 @@ void main() {
WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(
'Microsoft Windows [versão 10.0.22621.1105]'),
processLister: ofdNotRunning());
processLister: ofdNotRunning(),
versionExtractor: FakeVersionExtractor.win11ProX64());
final ValidationResult result = await windowsVersionValidator.validate();
expect(result.type, validWindows10ValidationResult.type,
expect(result.type, validWindows11ValidationResult.type,
reason: 'The ValidationResult type should be the same (installed)');
expect(result.statusInfo, validWindows10ValidationResult.statusInfo,
expect(result.statusInfo, validWindows11ValidationResult.statusInfo,
reason: 'The ValidationResult statusInfo messages should be the same');
});
@@ -138,7 +159,8 @@ void main() {
WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(
'Microsoft Windows [Version 8.0.22621.1105]'),
processLister: ofdNotRunning());
processLister: ofdNotRunning(),
versionExtractor: FakeVersionExtractor.win11ProX64());
final ValidationResult result = await windowsVersionValidator.validate();
@@ -172,7 +194,8 @@ OS 版本: 10.0.22621 暂缺 Build 22621
final WindowsVersionValidator validator =
WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(),
processLister: ofdRunning());
processLister: ofdRunning(),
versionExtractor: FakeVersionExtractor.win11ProX64());
final ValidationResult result = await validator.validate();
expect(result.type, ofdFoundRunning.type, reason: 'The ValidationResult type should be the same (partial)');
expect(result.statusInfo, ofdFoundRunning.statusInfo, reason: 'The ValidationResult statusInfo should be the same');
@@ -184,7 +207,8 @@ OS 版本: 10.0.22621 暂缺 Build 22621
final WindowsVersionValidator validator =
WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(),
processLister: powershellUnavailable());
processLister: powershellUnavailable(),
versionExtractor: FakeVersionExtractor.win11ProX64());
final ValidationResult result = await validator.validate();
expect(result.type, powershellUnavailableResult.type, reason: 'The ValidationResult type should be the same (partial)');
expect(result.statusInfo, powershellUnavailableResult.statusInfo, reason: 'The ValidationResult statusInfo should be the same');
@@ -196,7 +220,8 @@ OS 版本: 10.0.22621 暂缺 Build 22621
final WindowsVersionValidator validator =
WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(),
processLister: failure());
processLister: failure(),
versionExtractor: FakeVersionExtractor(mockData: WindowsVersionExtractionResult.empty()));
final ValidationResult result = await validator.validate();
expect(result.type, getProcessFailed.type, reason: 'The ValidationResult type should be the same (partial)');
expect(result.statusInfo, getProcessFailed.statusInfo, reason: 'The ValidationResult statusInfo should be the same');
@@ -274,4 +299,173 @@ OS 版本: 10.0.22621 暂缺 Build 22621
fail('Unexpected exception: $e');
}
});
testWithoutContext('Parses Caption, OSArchitecture, releaseId, and CurrentVersion from the OS', () async {
final FakeProcessManager processManager = FakeProcessManager.list(
<FakeCommand>[
const FakeCommand(
command: <Pattern>['wmic', 'os', 'get', 'Caption,OSArchitecture'],
stdout: '''
Caption OSArchitecture
Microsoft Windows 10 Enterprise 64-bit
'''),
const FakeCommand(command: <Pattern>[
'reg',
'query',
r'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion',
'/t',
'REG_SZ',
], stdout: r'''
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
SystemRoot REG_SZ C:\Windows
BuildBranch REG_SZ vb_release
BuildGUID REG_SZ ffffffff-ffff-ffff-ffff-ffffffffffff
BuildLab REG_SZ 19041.vb_release.191206-1406
BuildLabEx REG_SZ 19041.1.amd64fre.vb_release.191206-1406
CompositionEditionID REG_SZ Enterprise
CurrentBuild REG_SZ 19045
CurrentBuildNumber REG_SZ 19045
CurrentType REG_SZ Multiprocessor Free
CurrentVersion REG_SZ 6.3
EditionID REG_SZ Enterprise
EditionSubManufacturer REG_SZ
EditionSubstring REG_SZ
EditionSubVersion REG_SZ
InstallationType REG_SZ Client
ProductName REG_SZ Windows 10 Enterprise
ReleaseId REG_SZ 2009
SoftwareType REG_SZ System
PathName REG_SZ C:\Windows
ProductId REG_SZ 00329-00000-00003-AA153
DisplayVersion REG_SZ 22H2
WinREVersion REG_SZ 10.0.19041.3920
End of search: 22 match(es) found.
'''),
],
);
final WindowsVersionValidator validator = WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(),
processLister: ofdNotRunning(),
versionExtractor: WindowsVersionExtractor(
processManager: processManager,
logger: BufferLogger.test(),
),
);
final ValidationResult result = await validator.validate();
expect(result.type, ValidationType.success);
expect(result.statusInfo, '10 Enterprise 64-bit, 22H2, 2009');
});
testWithoutContext('Differentiates Windows 11 from 10 when wmic call fails', () async {
const String windows10RegQueryOutput = r'''
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
SystemRoot REG_SZ C:\WINDOWS
BuildBranch REG_SZ ni_release
BuildGUID REG_SZ ffffffff-ffff-ffff-ffff-ffffffffffff
BuildLab REG_SZ 22621.ni_release.220506-1250
BuildLabEx REG_SZ 22621.1.amd64fre.ni_release.220506-1250
CompositionEditionID REG_SZ Enterprise
CurrentBuild REG_SZ 22631
CurrentBuildNumber REG_SZ 22631
CurrentType REG_SZ Multiprocessor Free
CurrentVersion REG_SZ 6.3
DisplayVersion REG_SZ 23H2
EditionID REG_SZ Professional
EditionSubManufacturer REG_SZ
EditionSubstring REG_SZ
EditionSubVersion REG_SZ
InstallationType REG_SZ Client
ProductName REG_SZ Windows 10 Pro
ReleaseId REG_SZ 2009
SoftwareType REG_SZ System
PathName REG_SZ C:\Windows
ProductId REG_SZ 00330-80832-91035-AA540
End of search: 21 match(es) found.
''';
const List<String> wmicCommand = <String>['wmic', 'os', 'get', 'Caption,OSArchitecture'];
final FakeProcessManager processManager = FakeProcessManager.list(
<FakeCommand>[
FakeCommand(
command: wmicCommand,
exception: ProcessException(
wmicCommand[0],
wmicCommand.sublist(1),
),
),
const FakeCommand(
command: <Pattern>[
'reg',
'query',
r'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion',
'/t',
'REG_SZ',
],
stdout: windows10RegQueryOutput,
),
],
);
final WindowsVersionValidator validator = WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(),
processLister: ofdNotRunning(),
versionExtractor: WindowsVersionExtractor(
processManager: processManager,
logger: BufferLogger.test(),
),
);
final ValidationResult result = await validator.validate();
expect(result.type, ValidationType.success);
expect(result.statusInfo, 'Windows 11 or higher, 23H2, 2009');
});
testWithoutContext('Handles reg call failing', () async {
const List<String> wmicCommand = <String>[
'wmic',
'os',
'get',
'Caption,OSArchitecture',
];
const List<String> regCommand = <String>[
'reg',
'query',
r'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion',
'/t',
'REG_SZ',
];
final FakeProcessManager processManager = FakeProcessManager.list(
<FakeCommand>[
const FakeCommand(
command: wmicCommand,
stdout: r'''
Caption OSArchitecture
Microsoft Windows 11 Pro 64-bit
'''
),
FakeCommand(
command: regCommand,
exception: ProcessException(
regCommand[0],
regCommand.sublist(1),
)
),
],
);
final WindowsVersionValidator validator = WindowsVersionValidator(
operatingSystemUtils: FakeValidOperatingSystemUtils(),
processLister: ofdNotRunning(),
versionExtractor: WindowsVersionExtractor(
processManager: processManager,
logger: BufferLogger.test(),
),
);
final ValidationResult result = await validator.validate();
expect(result.type, ValidationType.success);
expect(result.statusInfo, 'Windows 11 or higher');
});
}