Implementing switch expressions in flutter_tools/ (#145632)

This pull request is step 12 in the journey to make this entire repository more readable.

(previous PRs: #139048, #139882, #141591, #142279, #142634, #142793, #143293, #143496, #143634, #143812, #144580)

We're getting close to the end! 😄
This commit is contained in:
Nate 2024-03-29 16:31:19 -06:00 committed by GitHub
parent 7f6685658c
commit a17d4b34f0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 222 additions and 409 deletions

View File

@ -681,108 +681,66 @@ DarwinArch getIOSArchForName(String arch) {
} }
DarwinArch getDarwinArchForName(String arch) { DarwinArch getDarwinArchForName(String arch) {
switch (arch) { return switch (arch) {
case 'arm64': 'arm64' => DarwinArch.arm64,
return DarwinArch.arm64; 'x86_64' => DarwinArch.x86_64,
case 'x86_64': _ => throw Exception('Unsupported MacOS arch name "$arch"'),
return DarwinArch.x86_64; };
}
throw Exception('Unsupported MacOS arch name "$arch"');
} }
String getNameForTargetPlatform(TargetPlatform platform, {DarwinArch? darwinArch}) { String getNameForTargetPlatform(TargetPlatform platform, {DarwinArch? darwinArch}) {
switch (platform) { return switch (platform) {
case TargetPlatform.android_arm: TargetPlatform.ios when darwinArch != null => 'ios-${darwinArch.name}',
return 'android-arm'; TargetPlatform.darwin when darwinArch != null => 'darwin-${darwinArch.name}',
case TargetPlatform.android_arm64: TargetPlatform.ios => 'ios',
return 'android-arm64'; TargetPlatform.darwin => 'darwin',
case TargetPlatform.android_x64: TargetPlatform.android_arm => 'android-arm',
return 'android-x64'; TargetPlatform.android_arm64 => 'android-arm64',
case TargetPlatform.android_x86: TargetPlatform.android_x64 => 'android-x64',
return 'android-x86'; TargetPlatform.android_x86 => 'android-x86',
case TargetPlatform.ios: TargetPlatform.linux_x64 => 'linux-x64',
if (darwinArch != null) { TargetPlatform.linux_arm64 => 'linux-arm64',
return 'ios-${darwinArch.name}'; TargetPlatform.windows_x64 => 'windows-x64',
} TargetPlatform.windows_arm64 => 'windows-arm64',
return 'ios'; TargetPlatform.fuchsia_arm64 => 'fuchsia-arm64',
case TargetPlatform.darwin: TargetPlatform.fuchsia_x64 => 'fuchsia-x64',
if (darwinArch != null) { TargetPlatform.tester => 'flutter-tester',
return 'darwin-${darwinArch.name}'; TargetPlatform.web_javascript => 'web-javascript',
} TargetPlatform.android => 'android',
return 'darwin'; };
case TargetPlatform.linux_x64:
return 'linux-x64';
case TargetPlatform.linux_arm64:
return 'linux-arm64';
case TargetPlatform.windows_x64:
return 'windows-x64';
case TargetPlatform.windows_arm64:
return 'windows-arm64';
case TargetPlatform.fuchsia_arm64:
return 'fuchsia-arm64';
case TargetPlatform.fuchsia_x64:
return 'fuchsia-x64';
case TargetPlatform.tester:
return 'flutter-tester';
case TargetPlatform.web_javascript:
return 'web-javascript';
case TargetPlatform.android:
return 'android';
}
} }
TargetPlatform getTargetPlatformForName(String platform) { TargetPlatform getTargetPlatformForName(String platform) {
switch (platform) { return switch (platform) {
case 'android': 'android' => TargetPlatform.android,
return TargetPlatform.android; 'android-arm' => TargetPlatform.android_arm,
case 'android-arm': 'android-arm64' => TargetPlatform.android_arm64,
return TargetPlatform.android_arm; 'android-x64' => TargetPlatform.android_x64,
case 'android-arm64': 'android-x86' => TargetPlatform.android_x86,
return TargetPlatform.android_arm64; 'fuchsia-arm64' => TargetPlatform.fuchsia_arm64,
case 'android-x64': 'fuchsia-x64' => TargetPlatform.fuchsia_x64,
return TargetPlatform.android_x64; 'ios' => TargetPlatform.ios,
case 'android-x86':
return TargetPlatform.android_x86;
case 'fuchsia-arm64':
return TargetPlatform.fuchsia_arm64;
case 'fuchsia-x64':
return TargetPlatform.fuchsia_x64;
case 'ios':
return TargetPlatform.ios;
case 'darwin':
// For backward-compatibility and also for Tester, where it must match // For backward-compatibility and also for Tester, where it must match
// host platform name (HostPlatform.darwin_x64) // host platform name (HostPlatform.darwin_x64)
case 'darwin-x64': 'darwin' || 'darwin-x64' || 'darwin-arm64' => TargetPlatform.darwin,
case 'darwin-arm64': 'linux-x64' => TargetPlatform.linux_x64,
return TargetPlatform.darwin; 'linux-arm64' => TargetPlatform.linux_arm64,
case 'linux-x64': 'windows-x64' => TargetPlatform.windows_x64,
return TargetPlatform.linux_x64; 'windows-arm64' => TargetPlatform.windows_arm64,
case 'linux-arm64': 'web-javascript' => TargetPlatform.web_javascript,
return TargetPlatform.linux_arm64; 'flutter-tester' => TargetPlatform.tester,
case 'windows-x64': _ => throw Exception('Unsupported platform name "$platform"'),
return TargetPlatform.windows_x64; };
case 'windows-arm64':
return TargetPlatform.windows_arm64;
case 'web-javascript':
return TargetPlatform.web_javascript;
case 'flutter-tester':
return TargetPlatform.tester;
}
throw Exception('Unsupported platform name "$platform"');
} }
AndroidArch getAndroidArchForName(String platform) { AndroidArch getAndroidArchForName(String platform) {
switch (platform) { return switch (platform) {
case 'android-arm': 'android-arm' => AndroidArch.armeabi_v7a,
return AndroidArch.armeabi_v7a; 'android-arm64' => AndroidArch.arm64_v8a,
case 'android-arm64': 'android-x64' => AndroidArch.x86_64,
return AndroidArch.arm64_v8a; 'android-x86' => AndroidArch.x86,
case 'android-x64': _ => throw Exception('Unsupported Android arch name "$platform"'),
return AndroidArch.x86_64; };
case 'android-x86':
return AndroidArch.x86;
}
throw Exception('Unsupported Android arch name "$platform"');
} }
HostPlatform getCurrentHostPlatform() { HostPlatform getCurrentHostPlatform() {

View File

@ -88,36 +88,26 @@ class SourceVisitor implements ResolvedFiles {
void visitPattern(String pattern, bool optional) { void visitPattern(String pattern, bool optional) {
// perform substitution of the environmental values and then // perform substitution of the environmental values and then
// of the local values. // of the local values.
final List<String> segments = <String>[];
final List<String> rawParts = pattern.split('/'); final List<String> rawParts = pattern.split('/');
final bool hasWildcard = rawParts.last.contains('*'); final bool hasWildcard = rawParts.last.contains('*');
String? wildcardFile; String? wildcardFile;
if (hasWildcard) { if (hasWildcard) {
wildcardFile = rawParts.removeLast(); wildcardFile = rawParts.removeLast();
} }
final List<String> segments = <String>[
...environment.fileSystem.path.split(switch (rawParts.first) {
// flutter root will not contain a symbolic link.
Environment.kFlutterRootDirectory => environment.flutterRootDir.absolute.path,
Environment.kProjectDirectory => environment.projectDir.resolveSymbolicLinksSync(),
Environment.kBuildDirectory => environment.buildDir.resolveSymbolicLinksSync(),
Environment.kCacheDirectory => environment.cacheDir.resolveSymbolicLinksSync(),
Environment.kOutputDirectory => environment.outputDir.resolveSymbolicLinksSync(),
// If the pattern does not start with an env variable, then we have nothing // If the pattern does not start with an env variable, then we have nothing
// to resolve it to, error out. // to resolve it to, error out.
switch (rawParts.first) { _ => throw InvalidPatternException(pattern),
case Environment.kProjectDirectory: }),
segments.addAll( ...rawParts.skip(1),
environment.fileSystem.path.split(environment.projectDir.resolveSymbolicLinksSync())); ];
case Environment.kBuildDirectory:
segments.addAll(environment.fileSystem.path.split(
environment.buildDir.resolveSymbolicLinksSync()));
case Environment.kCacheDirectory:
segments.addAll(
environment.fileSystem.path.split(environment.cacheDir.resolveSymbolicLinksSync()));
case Environment.kFlutterRootDirectory:
// flutter root will not contain a symbolic link.
segments.addAll(
environment.fileSystem.path.split(environment.flutterRootDir.absolute.path));
case Environment.kOutputDirectory:
segments.addAll(
environment.fileSystem.path.split(environment.outputDir.resolveSymbolicLinksSync()));
default:
throw InvalidPatternException(pattern);
}
rawParts.skip(1).forEach(segments.add);
final String filePath = environment.fileSystem.path.joinAll(segments); final String filePath = environment.fileSystem.path.joinAll(segments);
if (!hasWildcard) { if (!hasWildcard) {
if (optional && !environment.fileSystem.isFileSync(filePath)) { if (optional && !environment.fileSystem.isFileSync(filePath)) {

View File

@ -1229,21 +1229,14 @@ class PubspecHeader extends PubspecLine {
final List<String> parts = strippedLine.split(':'); final List<String> parts = strippedLine.split(':');
final String sectionName = parts.first; final String sectionName = parts.first;
final String value = parts.last.trim(); final String value = parts.last.trim();
switch (sectionName) { return switch (sectionName) {
case 'dependencies': 'dependencies' => PubspecHeader(line, Section.dependencies),
return PubspecHeader(line, Section.dependencies); 'dev_dependencies' => PubspecHeader(line, Section.devDependencies),
case 'dev_dependencies': 'dependency_overrides' => PubspecHeader(line, Section.dependencyOverrides),
return PubspecHeader(line, Section.devDependencies); 'builders' => PubspecHeader(line, Section.builders),
case 'dependency_overrides': 'name' || 'version' => PubspecHeader(line, Section.header, name: sectionName, value: value),
return PubspecHeader(line, Section.dependencyOverrides); _ => PubspecHeader(line, Section.other),
case 'builders': };
return PubspecHeader(line, Section.builders);
case 'name':
case 'version':
return PubspecHeader(line, Section.header, name: sectionName, value: value);
default:
return PubspecHeader(line, Section.other);
}
} }
/// Returns the input after removing trailing spaces and anything after the /// Returns the input after removing trailing spaces and anything after the

View File

@ -98,19 +98,12 @@ class ValidateProject {
} }
String getStringResult(ProjectValidatorResult result) { String getStringResult(ProjectValidatorResult result) {
final String icon; final String icon = switch (result.status) {
switch (result.status) { StatusProjectValidator.warning => '[!]',
case StatusProjectValidator.error: StatusProjectValidator.error => '[✗]',
icon = '[✗]'; StatusProjectValidator.crash => '[☠]',
case StatusProjectValidator.info: StatusProjectValidator.info || StatusProjectValidator.success => '[✓]',
case StatusProjectValidator.success: };
icon = '[✓]';
case StatusProjectValidator.warning:
icon = '[!]';
case StatusProjectValidator.crash:
icon = '[☠]';
}
return '$icon $result'; return '$icon $result';
} }
} }

View File

@ -31,17 +31,13 @@ class TargetModel {
/// Throws an exception if passed a value other than 'flutter', /// Throws an exception if passed a value other than 'flutter',
/// 'flutter_runner', 'vm', or 'dartdevc'. /// 'flutter_runner', 'vm', or 'dartdevc'.
factory TargetModel(String rawValue) { factory TargetModel(String rawValue) {
switch (rawValue) { return switch (rawValue) {
case 'flutter': 'flutter' => flutter,
return flutter; 'flutter_runner' => flutterRunner,
case 'flutter_runner': 'vm' => vm,
return flutterRunner; 'dartdevc' => dartdevc,
case 'vm': _ => throw Exception('Unexpected target model $rawValue'),
return vm; };
case 'dartdevc':
return dartdevc;
}
throw Exception('Unexpected target model $rawValue');
} }
const TargetModel._(this._value); const TargetModel._(this._value);

View File

@ -242,15 +242,11 @@ class AnalysisError implements Comparable<AnalysisError> {
String get _separator => _platform.isWindows ? '-' : ''; String get _separator => _platform.isWindows ? '-' : '';
String get colorSeverity { String get colorSeverity {
switch (writtenError.severityLevel) { return switch (writtenError.severityLevel) {
case AnalysisSeverity.error: AnalysisSeverity.error => _terminal.color(writtenError.severity, TerminalColor.red),
return _terminal.color(writtenError.severity, TerminalColor.red); AnalysisSeverity.warning => _terminal.color(writtenError.severity, TerminalColor.yellow),
case AnalysisSeverity.warning: AnalysisSeverity.info || AnalysisSeverity.none => writtenError.severity,
return _terminal.color(writtenError.severity, TerminalColor.yellow); };
case AnalysisSeverity.info:
case AnalysisSeverity.none:
return writtenError.severity;
}
} }
String get type => writtenError.type; String get type => writtenError.type;

View File

@ -581,23 +581,19 @@ enum DeviceConnectionInterface {
/// Returns the `DeviceConnectionInterface` enum based on its string name. /// Returns the `DeviceConnectionInterface` enum based on its string name.
DeviceConnectionInterface getDeviceConnectionInterfaceForName(String name) { DeviceConnectionInterface getDeviceConnectionInterfaceForName(String name) {
switch (name) { return switch (name) {
case 'attached': 'attached' => DeviceConnectionInterface.attached,
return DeviceConnectionInterface.attached; 'wireless' => DeviceConnectionInterface.wireless,
case 'wireless': _ => throw Exception('Unsupported DeviceConnectionInterface name "$name"'),
return DeviceConnectionInterface.wireless; };
}
throw Exception('Unsupported DeviceConnectionInterface name "$name"');
} }
/// Returns a `DeviceConnectionInterface`'s string name. /// Returns a `DeviceConnectionInterface`'s string name.
String getNameForDeviceConnectionInterface(DeviceConnectionInterface connectionInterface) { String getNameForDeviceConnectionInterface(DeviceConnectionInterface connectionInterface) {
switch (connectionInterface) { return switch (connectionInterface) {
case DeviceConnectionInterface.attached: DeviceConnectionInterface.attached => 'attached',
return 'attached'; DeviceConnectionInterface.wireless => 'wireless',
case DeviceConnectionInterface.wireless: };
return 'wireless';
}
} }
/// A device is a physical hardware that can run a Flutter application. /// A device is a physical hardware that can run a Flutter application.

View File

@ -162,47 +162,31 @@ class ValidationResult {
final List<ValidationMessage> messages; final List<ValidationMessage> messages;
String get leadingBox { String get leadingBox {
switch (type) { return switch (type) {
case ValidationType.crash: ValidationType.crash => '[☠]',
return '[☠]'; ValidationType.missing => '[✗]',
case ValidationType.missing: ValidationType.success => '[✓]',
return '[✗]'; ValidationType.notAvailable || ValidationType.partial => '[!]',
case ValidationType.success: };
return '[✓]';
case ValidationType.notAvailable:
case ValidationType.partial:
return '[!]';
}
} }
String get coloredLeadingBox { String get coloredLeadingBox {
switch (type) { return globals.terminal.color(leadingBox, switch (type) {
case ValidationType.crash: ValidationType.success => TerminalColor.green,
return globals.terminal.color(leadingBox, TerminalColor.red); ValidationType.crash || ValidationType.missing => TerminalColor.red,
case ValidationType.missing: ValidationType.notAvailable || ValidationType.partial => TerminalColor.yellow,
return globals.terminal.color(leadingBox, TerminalColor.red); });
case ValidationType.success:
return globals.terminal.color(leadingBox, TerminalColor.green);
case ValidationType.notAvailable:
case ValidationType.partial:
return globals.terminal.color(leadingBox, TerminalColor.yellow);
}
} }
/// The string representation of the type. /// The string representation of the type.
String get typeStr { String get typeStr {
switch (type) { return switch (type) {
case ValidationType.crash: ValidationType.crash => 'crash',
return 'crash'; ValidationType.missing => 'missing',
case ValidationType.missing: ValidationType.success => 'installed',
return 'missing'; ValidationType.notAvailable => 'notAvailable',
case ValidationType.success: ValidationType.partial => 'partial',
return 'installed'; };
case ValidationType.notAvailable:
return 'notAvailable';
case ValidationType.partial:
return 'partial';
}
} }
@override @override
@ -254,25 +238,19 @@ class ValidationMessage {
bool get isInformation => type == ValidationMessageType.information; bool get isInformation => type == ValidationMessageType.information;
String get indicator { String get indicator {
switch (type) { return switch (type) {
case ValidationMessageType.error: ValidationMessageType.error => '',
return ''; ValidationMessageType.hint => '!',
case ValidationMessageType.hint: ValidationMessageType.information => '',
return '!'; };
case ValidationMessageType.information:
return '';
}
} }
String get coloredIndicator { String get coloredIndicator {
switch (type) { return globals.terminal.color(indicator, switch (type) {
case ValidationMessageType.error: ValidationMessageType.error => TerminalColor.red,
return globals.terminal.color(indicator, TerminalColor.red); ValidationMessageType.hint => TerminalColor.yellow,
case ValidationMessageType.hint: ValidationMessageType.information => TerminalColor.green,
return globals.terminal.color(indicator, TerminalColor.yellow); });
case ValidationMessageType.information:
return globals.terminal.color(indicator, TerminalColor.green);
}
} }
@override @override

View File

@ -270,15 +270,11 @@ class Feature {
/// Retrieve the correct setting for the provided `channel`. /// Retrieve the correct setting for the provided `channel`.
FeatureChannelSetting getSettingForChannel(String channel) { FeatureChannelSetting getSettingForChannel(String channel) {
switch (channel) { return switch (channel) {
case 'stable': 'stable' => stable,
return stable; 'beta' => beta,
case 'beta': 'master' || _ => master,
return beta; };
case 'master':
default:
return master;
}
} }
} }

View File

@ -143,27 +143,18 @@ class PlistParser {
static final RegExp _nonBase64Pattern = RegExp('[^a-zA-Z0-9+/=]+'); static final RegExp _nonBase64Pattern = RegExp('[^a-zA-Z0-9+/=]+');
Object? _parseXmlNode(XmlElement node) { Object? _parseXmlNode(XmlElement node) {
switch (node.name.local){ return switch (node.name.local) {
case 'string': 'string' => node.innerText,
return node.innerText; 'real' => double.parse(node.innerText),
case 'real': 'integer' => int.parse(node.innerText),
return double.parse(node.innerText); 'true' => true,
case 'integer': 'false' => false,
return int.parse(node.innerText); 'date' => DateTime.parse(node.innerText),
case 'true': 'data' => base64.decode(node.innerText.replaceAll(_nonBase64Pattern, '')),
return true; 'array' => node.children.whereType<XmlElement>().map<Object?>(_parseXmlNode).whereType<Object>().toList(),
case 'false': 'dict' => _parseXmlDict(node),
return false; _ => null,
case 'date': };
return DateTime.parse(node.innerText);
case 'data':
return base64.decode(node.innerText.replaceAll(_nonBase64Pattern, ''));
case 'array':
return node.children.whereType<XmlElement>().map<Object?>(_parseXmlNode).whereType<Object>().toList();
case 'dict':
return _parseXmlDict(node);
}
return null;
} }
/// Parses the Plist file located at [plistFilePath] and returns the value /// Parses the Plist file located at [plistFilePath] and returns the value

View File

@ -156,34 +156,24 @@ Future<void> _copyNativeAssetsAndroid(
/// Get the [Target] for [androidArch]. /// Get the [Target] for [androidArch].
Target _getNativeTarget(AndroidArch androidArch) { Target _getNativeTarget(AndroidArch androidArch) {
switch (androidArch) { return switch (androidArch) {
case AndroidArch.armeabi_v7a: AndroidArch.armeabi_v7a => Target.androidArm,
return Target.androidArm; AndroidArch.arm64_v8a => Target.androidArm64,
case AndroidArch.arm64_v8a: AndroidArch.x86 => Target.androidIA32,
return Target.androidArm64; AndroidArch.x86_64 => Target.androidX64,
case AndroidArch.x86: };
return Target.androidIA32;
case AndroidArch.x86_64:
return Target.androidX64;
}
} }
/// Get the [AndroidArch] for [target]. /// Get the [AndroidArch] for [target].
AndroidArch _getAndroidArch(Target target) { AndroidArch _getAndroidArch(Target target) {
switch (target) { return switch (target) {
case Target.androidArm: Target.androidArm => AndroidArch.armeabi_v7a,
return AndroidArch.armeabi_v7a; Target.androidArm64 => AndroidArch.arm64_v8a,
case Target.androidArm64: Target.androidIA32 => AndroidArch.x86,
return AndroidArch.arm64_v8a; Target.androidX64 => AndroidArch.x86_64,
case Target.androidIA32: Target.androidRiscv64 => throwToolExit('Android RISC-V not yet supported.'),
return AndroidArch.x86; _ => throwToolExit('Invalid target: $target.'),
case Target.androidX64: };
return AndroidArch.x86_64;
case Target.androidRiscv64:
throwToolExit('Android RISC-V not yet supported.');
default:
throwToolExit('Invalid target: $target.');
}
} }
Map<AssetImpl, KernelAsset> _assetTargetLocations( Map<AssetImpl, KernelAsset> _assetTargetLocations(

View File

@ -124,24 +124,19 @@ Future<List<Uri>> buildNativeAssetsIOS({
} }
IOSSdkImpl _getIOSSdkImpl(EnvironmentType environmentType) { IOSSdkImpl _getIOSSdkImpl(EnvironmentType environmentType) {
switch (environmentType) { return switch (environmentType) {
case EnvironmentType.physical: EnvironmentType.physical => IOSSdkImpl.iPhoneOS,
return IOSSdkImpl.iPhoneOS; EnvironmentType.simulator => IOSSdkImpl.iPhoneSimulator,
case EnvironmentType.simulator: };
return IOSSdkImpl.iPhoneSimulator;
}
} }
/// Extract the [Target] from a [DarwinArch]. /// Extract the [Target] from a [DarwinArch].
Target _getNativeTarget(DarwinArch darwinArch) { Target _getNativeTarget(DarwinArch darwinArch) {
switch (darwinArch) { return switch (darwinArch) {
case DarwinArch.armv7: DarwinArch.armv7 => Target.iOSArm,
return Target.iOSArm; DarwinArch.arm64 => Target.iOSArm64,
case DarwinArch.arm64: DarwinArch.x86_64 => Target.iOSX64,
return Target.iOSArm64; };
case DarwinArch.x86_64:
return Target.iOSX64;
}
} }
Map<KernelAssetPath, List<AssetImpl>> _fatAssetTargetLocations( Map<KernelAssetPath, List<AssetImpl>> _fatAssetTargetLocations(

View File

@ -156,14 +156,11 @@ Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> buildNativeAssetsMacOS({
/// Extract the [Target] from a [DarwinArch]. /// Extract the [Target] from a [DarwinArch].
Target _getNativeTarget(DarwinArch darwinArch) { Target _getNativeTarget(DarwinArch darwinArch) {
switch (darwinArch) { return switch (darwinArch) {
case DarwinArch.arm64: DarwinArch.arm64 => Target.macOSArm64,
return Target.macOSArm64; DarwinArch.x86_64 => Target.macOSX64,
case DarwinArch.x86_64: DarwinArch.armv7 => throw Exception('Unknown DarwinArch: $darwinArch.'),
return Target.macOSX64; };
case DarwinArch.armv7:
throw Exception('Unknown DarwinArch: $darwinArch.');
}
} }
Map<KernelAssetPath, List<AssetImpl>> _fatAssetTargetLocations( Map<KernelAssetPath, List<AssetImpl>> _fatAssetTargetLocations(

View File

@ -64,29 +64,12 @@ class LocaleInfo implements Comparable<LocaleInfo> {
/// across various countries. For example, we know Taiwan uses traditional (Hant) /// across various countries. For example, we know Taiwan uses traditional (Hant)
/// script, so it is safe to apply (Hant) to Taiwanese languages. /// script, so it is safe to apply (Hant) to Taiwanese languages.
if (deriveScriptCode && scriptCode == null) { if (deriveScriptCode && scriptCode == null) {
switch (languageCode) { scriptCode = switch ((languageCode, countryCode)) {
case 'zh': { ('zh', 'CN' || 'SG' || null) => 'Hans',
if (countryCode == null) { ('zh', 'TW' || 'HK' || 'MO') => 'Hant',
scriptCode = 'Hans'; ('sr', null) => 'Cyrl',
} _ => null,
switch (countryCode) { };
case 'CN':
case 'SG':
scriptCode = 'Hans';
case 'TW':
case 'HK':
case 'MO':
scriptCode = 'Hant';
}
break;
}
case 'sr': {
if (countryCode == null) {
scriptCode = 'Cyrl';
}
break;
}
}
// Increment length if we were able to assume a scriptCode. // Increment length if we were able to assume a scriptCode.
if (scriptCode != null) { if (scriptCode != null) {
length += 1; length += 1;

View File

@ -1511,24 +1511,16 @@ String _describePausedIsolates(int pausedIsolatesFound, String serviceEventKind)
message.write('$pausedIsolatesFound isolates are '); message.write('$pausedIsolatesFound isolates are ');
plural = true; plural = true;
} }
switch (serviceEventKind) { message.write(switch (serviceEventKind) {
case vm_service.EventKind.kPauseStart: vm_service.EventKind.kPauseStart => 'paused (probably due to --start-paused)',
message.write('paused (probably due to --start-paused)'); vm_service.EventKind.kPauseExit => 'paused because ${ plural ? 'they have' : 'it has' } terminated',
case vm_service.EventKind.kPauseExit: vm_service.EventKind.kPauseBreakpoint => 'paused in the debugger on a breakpoint',
message.write('paused because ${ plural ? 'they have' : 'it has' } terminated'); vm_service.EventKind.kPauseInterrupted => 'paused due in the debugger',
case vm_service.EventKind.kPauseBreakpoint: vm_service.EventKind.kPauseException => 'paused in the debugger after an exception was thrown',
message.write('paused in the debugger on a breakpoint'); vm_service.EventKind.kPausePostRequest => 'paused',
case vm_service.EventKind.kPauseInterrupted: '' => 'paused for various reasons',
message.write('paused due in the debugger'); _ => 'paused',
case vm_service.EventKind.kPauseException: });
message.write('paused in the debugger after an exception was thrown');
case vm_service.EventKind.kPausePostRequest:
message.write('paused');
case '':
message.write('paused for various reasons');
default:
message.write('paused');
}
return message.toString(); return message.toString();
} }

View File

@ -375,22 +375,15 @@ class FlutterTesterTestDevice extends TestDevice {
} }
String _getExitCodeMessage(int exitCode) { String _getExitCodeMessage(int exitCode) {
switch (exitCode) { return switch (exitCode) {
case 1: 1 => 'Shell subprocess cleanly reported an error. Check the logs above for an error message.',
return 'Shell subprocess cleanly reported an error. Check the logs above for an error message.'; 0 => 'Shell subprocess ended cleanly. Did main() call exit()?',
case 0: -0x0f => 'Shell subprocess crashed with SIGTERM ($exitCode).', // ProcessSignal.SIGTERM
return 'Shell subprocess ended cleanly. Did main() call exit()?'; -0x0b => 'Shell subprocess crashed with segmentation fault.', // ProcessSignal.SIGSEGV
case -0x0f: // ProcessSignal.SIGTERM -0x06 => 'Shell subprocess crashed with SIGABRT ($exitCode).', // ProcessSignal.SIGABRT
return 'Shell subprocess crashed with SIGTERM ($exitCode).'; -0x02 => 'Shell subprocess terminated by ^C (SIGINT, $exitCode).', // ProcessSignal.SIGINT
case -0x0b: // ProcessSignal.SIGSEGV _ => 'Shell subprocess crashed with unexpected exit code $exitCode.',
return 'Shell subprocess crashed with segmentation fault.'; };
case -0x06: // ProcessSignal.SIGABRT
return 'Shell subprocess crashed with SIGABRT ($exitCode).';
case -0x02: // ProcessSignal.SIGINT
return 'Shell subprocess terminated by ^C (SIGINT, $exitCode).';
default:
return 'Shell subprocess crashed with unexpected exit code $exitCode.';
}
} }
StreamChannel<String> _webSocketToStreamChannel(WebSocket webSocket) { StreamChannel<String> _webSocketToStreamChannel(WebSocket webSocket) {

View File

@ -1163,14 +1163,11 @@ class VersionFreshnessValidator {
/// beta releases happen approximately every month. /// beta releases happen approximately every month.
@visibleForTesting @visibleForTesting
static Duration versionAgeConsideredUpToDate(String channel) { static Duration versionAgeConsideredUpToDate(String channel) {
switch (channel) { return switch (channel) {
case 'stable': 'stable' => const Duration(days: 365 ~/ 2), // Six months
return const Duration(days: 365 ~/ 2); // Six months 'beta' => const Duration(days: 7 * 8), // Eight weeks
case 'beta': _ => const Duration(days: 7 * 3), // Three weeks
return const Duration(days: 7 * 8); // Eight weeks };
default:
return const Duration(days: 7 * 3); // Three weeks
}
} }
/// Execute validations and print warning to [logger] if necessary. /// Execute validations and print warning to [logger] if necessary.

View File

@ -179,13 +179,10 @@ class VisualStudio {
/// version. /// version.
String? get cmakeGenerator { String? get cmakeGenerator {
// From https://cmake.org/cmake/help/v3.22/manual/cmake-generators.7.html#visual-studio-generators // From https://cmake.org/cmake/help/v3.22/manual/cmake-generators.7.html#visual-studio-generators
switch (_majorVersion) { return switch (_majorVersion) {
case 17: 17 => 'Visual Studio 17 2022',
return 'Visual Studio 17 2022'; _ => 'Visual Studio 16 2019',
case 16: };
default:
return 'Visual Studio 16 2019';
}
} }
/// The path to cl.exe, or null if no Visual Studio installation has /// The path to cl.exe, or null if no Visual Studio installation has

View File

@ -122,25 +122,15 @@ class LogLine {
} }
static String clarify(String line) { static String clarify(String line) {
return line.runes.map<String>((int rune) { return line.runes.map<String>((int rune) => switch (rune) {
if (rune >= 0x20 && rune <= 0x7F) { >= 0x20 && <= 0x7F => String.fromCharCode(rune),
return String.fromCharCode(rune); 0x00 => '<NUL>',
} 0x07 => '<BEL>',
switch (rune) { 0x08 => '<TAB>',
case 0x00: 0x09 => '<BS>',
return '<NUL>'; 0x0A => '<LF>',
case 0x07: 0x0D => '<CR>',
return '<BEL>'; _ => '<${rune.toRadixString(16).padLeft(rune <= 0xFF ? 2 : rune <= 0xFFFF ? 4 : 5, '0')}>',
case 0x08:
return '<TAB>';
case 0x09:
return '<BS>';
case 0x0A:
return '<LF>';
case 0x0D:
return '<CR>';
}
return '<${rune.toRadixString(16).padLeft(rune <= 0xFF ? 2 : rune <= 0xFFFF ? 4 : 5, '0')}>';
}).join(); }).join();
} }
} }

View File

@ -20,23 +20,15 @@ enum HttpMethod {
} }
HttpMethod _fromMethodString(String value) { HttpMethod _fromMethodString(String value) {
final String name = value.toLowerCase(); return switch (value.toLowerCase()) {
switch (name) { 'get' => HttpMethod.get,
case 'get': 'put' => HttpMethod.put,
return HttpMethod.get; 'delete' => HttpMethod.delete,
case 'put': 'post' => HttpMethod.post,
return HttpMethod.put; 'patch' => HttpMethod.patch,
case 'delete': 'head' => HttpMethod.head,
return HttpMethod.delete; _ => throw StateError('Unrecognized HTTP method $value'),
case 'post': };
return HttpMethod.post;
case 'patch':
return HttpMethod.patch;
case 'head':
return HttpMethod.head;
default:
throw StateError('Unrecognized HTTP method $value');
}
} }
String _toMethodString(HttpMethod method) { String _toMethodString(HttpMethod method) {