[flutter_tool] Use curly braces around single statment control structures (#40446)
diff --git a/packages/flutter_tools/analysis_options.yaml b/packages/flutter_tools/analysis_options.yaml index 62b0550..7d472a0 100644 --- a/packages/flutter_tools/analysis_options.yaml +++ b/packages/flutter_tools/analysis_options.yaml
@@ -12,3 +12,4 @@ rules: unawaited_futures: true avoid_as: false # Disabled so we can gradually migrate to no implicit dynamic. + curly_braces_in_flow_control_structures: true
diff --git a/packages/flutter_tools/bin/fuchsia_tester.dart b/packages/flutter_tools/bin/fuchsia_tester.dart index 7fb9364..32ff962 100644 --- a/packages/flutter_tools/bin/fuchsia_tester.dart +++ b/packages/flutter_tools/bin/fuchsia_tester.dart
@@ -161,8 +161,9 @@ } else { fs.currentDirectory = testDirectory; } - if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath], coverageDirectory: coverageDirectory)) + if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath], coverageDirectory: coverageDirectory)) { throwToolExit('Failed to collect coverage data'); + } } } finally { tempDir.deleteSync(recursive: true);
diff --git a/packages/flutter_tools/lib/runner.dart b/packages/flutter_tools/lib/runner.dart index 35c8ca0..9c4e9a9 100644 --- a/packages/flutter_tools/lib/runner.dart +++ b/packages/flutter_tools/lib/runner.dart
@@ -93,10 +93,12 @@ // Argument error exit code. return _exit(64); } else if (error is ToolExit) { - if (error.message != null) + if (error.message != null) { printError(error.message); - if (verbose) + } + if (verbose) { printError('\n$stackTrace\n'); + } return _exit(error.exitCode ?? 1); } else if (error is ProcessExit) { // We've caught an exit code. @@ -213,8 +215,9 @@ } Future<int> _exit(int code) async { - if (flutterUsage.isFirstRun) + if (flutterUsage.isFirstRun) { flutterUsage.printWelcome(); + } // Send any last analytics calls that are in progress without overly delaying // the tool's exit (we wait a maximum of 250ms).
diff --git a/packages/flutter_tools/lib/src/android/android_console.dart b/packages/flutter_tools/lib/src/android/android_console.dart index a292b57..7272a7b 100644 --- a/packages/flutter_tools/lib/src/android/android_console.dart +++ b/packages/flutter_tools/lib/src/android/android_console.dart
@@ -59,8 +59,9 @@ while (true) { final String text = await _queue.next; final String trimmedText = text.trim(); - if (trimmedText == 'OK') + if (trimmedText == 'OK') { break; + } if (trimmedText.endsWith('\nOK')) { output.write(trimmedText.substring(0, trimmedText.length - 3)); break;
diff --git a/packages/flutter_tools/lib/src/android/android_device.dart b/packages/flutter_tools/lib/src/android/android_device.dart index d42b4c6..72bd738 100644 --- a/packages/flutter_tools/lib/src/android/android_device.dart +++ b/packages/flutter_tools/lib/src/android/android_device.dart
@@ -143,8 +143,9 @@ /// will be returned. @override Future<String> get emulatorId async { - if (!(await isLocalEmulator)) + if (!(await isLocalEmulator)) { return null; + } // Emulators always have IDs in the format emulator-(port) where port is the // Android Console port number. @@ -375,8 +376,10 @@ return false; } - if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion()) + if (!await _checkForSupportedAdbVersion() || + !await _checkForSupportedAndroidVersion()) { return false; + } final Status status = logger.startProgress('Installing ${fs.path.relative(apk.file.path)}...', timeout: timeoutConfiguration.slowOperation); final RunResult installResult = await processUtils.run( @@ -408,8 +411,10 @@ @override Future<bool> uninstallApp(ApplicationPackage app) async { - if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion()) + if (!await _checkForSupportedAdbVersion() || + !await _checkForSupportedAndroidVersion()) { return false; + } String uninstallOut; try { @@ -470,8 +475,10 @@ bool prebuiltApplication = false, bool ipv6 = false, }) async { - if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion()) + if (!await _checkForSupportedAdbVersion() || + !await _checkForSupportedAndroidVersion()) { return LaunchResult.failed(); + } final TargetPlatform devicePlatform = await targetPlatform; if (!(devicePlatform == TargetPlatform.android_arm || @@ -522,8 +529,9 @@ printTrace("Stopping app '${package.name}' on $name."); await stopApp(package); - if (!await _installLatestApp(package)) + if (!await _installLatestApp(package)) { return LaunchResult.failed(); + } final bool traceStartup = platformArgs['trace-startup'] ?? false; final AndroidApk apk = package; @@ -591,8 +599,9 @@ return LaunchResult.failed(); } - if (!debuggingOptions.debuggingEnabled) + if (!debuggingOptions.debuggingEnabled) { return LaunchResult.succeeded(); + } // Wait for the service protocol port here. This will complete once the // device has printed "Observatory is listening on...". @@ -687,16 +696,18 @@ Map<String, String> parseAdbDeviceProperties(String str) { final Map<String, String> properties = <String, String>{}; final RegExp propertyExp = RegExp(r'\[(.*?)\]: \[(.*?)\]'); - for (Match match in propertyExp.allMatches(str)) + for (Match match in propertyExp.allMatches(str)) { properties[match.group(1)] = match.group(2); + } return properties; } /// Return the list of connected ADB devices. List<AndroidDevice> getAdbDevices() { final String adbPath = getAdbPath(androidSdk); - if (adbPath == null) + if (adbPath == null) { return <AndroidDevice>[]; + } String text; try { text = processUtils.runSync( @@ -718,8 +729,9 @@ /// Get diagnostics about issues with any connected devices. Future<List<String>> getAdbDeviceDiagnostics() async { final String adbPath = getAdbPath(androidSdk); - if (adbPath == null) + if (adbPath == null) { return <String>[]; + } final RunResult result = await processUtils.run(<String>[adbPath, 'devices', '-l']); if (result.exitCode != 0) { @@ -752,8 +764,9 @@ for (String line in text.trim().split('\n')) { // Skip lines like: * daemon started successfully * - if (line.startsWith('* daemon ')) + if (line.startsWith('* daemon ')) { continue; + } // Skip lines about adb server and client version not matching if (line.startsWith(RegExp(r'adb server (version|is out of date)'))) { @@ -761,8 +774,9 @@ continue; } - if (line.startsWith('List of devices')) + if (line.startsWith('List of devices')) { continue; + } if (_kDeviceRegex.hasMatch(line)) { final Match match = _kDeviceRegex.firstMatch(line); @@ -782,8 +796,9 @@ } } - if (info['model'] != null) + if (info['model'] != null) { info['model'] = cleanAdbDeviceName(info['model']); + } if (deviceState == 'unauthorized') { diagnostics?.add( @@ -856,8 +871,9 @@ _process.stdout.transform<String>(decoder).transform<String>(const LineSplitter()).listen(_onLine); _process.stderr.transform<String>(decoder).transform<String>(const LineSplitter()).listen(_onLine); _process.exitCode.whenComplete(() { - if (_linesController.hasListener) + if (_linesController.hasListener) { _linesController.close(); + } }); }); }
diff --git a/packages/flutter_tools/lib/src/android/android_sdk.dart b/packages/flutter_tools/lib/src/android/android_sdk.dart index fe13948..cd04804 100644 --- a/packages/flutter_tools/lib/src/android/android_sdk.dart +++ b/packages/flutter_tools/lib/src/android/android_sdk.dart
@@ -46,8 +46,9 @@ /// will work for those users who have Android Platform Tools installed but /// not the full SDK. String getAdbPath([ AndroidSdk existingSdk ]) { - if (existingSdk?.adbPath != null) + if (existingSdk?.adbPath != null) { return existingSdk.adbPath; + } final AndroidSdk sdk = AndroidSdk.locateAndroidSdk(); @@ -74,8 +75,9 @@ platform.environment['ANDROID_AVD_HOME'], ]; - if (platform.environment['HOME'] != null) + if (platform.environment['HOME'] != null) { searchPaths.add(fs.path.join(platform.environment['HOME'], '.android', 'avd')); + } if (platform.isWindows) { final String homeDrive = platform.environment['HOMEDRIVE']; @@ -309,21 +311,26 @@ } else if (platform.environment.containsKey(kAndroidSdkRoot)) { androidHomeDir = platform.environment[kAndroidSdkRoot]; } else if (platform.isLinux) { - if (homeDirPath != null) + if (homeDirPath != null) { androidHomeDir = fs.path.join(homeDirPath, 'Android', 'Sdk'); + } } else if (platform.isMacOS) { - if (homeDirPath != null) + if (homeDirPath != null) { androidHomeDir = fs.path.join(homeDirPath, 'Library', 'Android', 'sdk'); + } } else if (platform.isWindows) { - if (homeDirPath != null) + if (homeDirPath != null) { androidHomeDir = fs.path.join(homeDirPath, 'AppData', 'Local', 'Android', 'sdk'); + } } if (androidHomeDir != null) { - if (validSdkDirectory(androidHomeDir)) + if (validSdkDirectory(androidHomeDir)) { return androidHomeDir; - if (validSdkDirectory(fs.path.join(androidHomeDir, 'sdk'))) + } + if (validSdkDirectory(fs.path.join(androidHomeDir, 'sdk'))) { return fs.path.join(androidHomeDir, 'sdk'); + } } // in build-tools/$version/aapt @@ -332,8 +339,9 @@ // Make sure we're using the aapt from the SDK. aaptBin = fs.file(aaptBin.resolveSymbolicLinksSync()); final String dir = aaptBin.parent.parent.parent.path; - if (validSdkDirectory(dir)) + if (validSdkDirectory(dir)) { return dir; + } } // in platform-tools/adb @@ -342,8 +350,9 @@ // Make sure we're using the adb from the SDK. adbBin = fs.file(adbBin.resolveSymbolicLinksSync()); final String dir = adbBin.parent.parent.path; - if (validSdkDirectory(dir)) + if (validSdkDirectory(dir)) { return dir; + } } return null; @@ -405,8 +414,9 @@ /// Validate the Android SDK. This returns an empty list if there are no /// issues; otherwise, it returns a list of issues found. List<String> validateSdkWellFormed() { - if (adbPath == null || !processManager.canRun(adbPath)) + if (adbPath == null || !processManager.canRun(adbPath)) { return <String>['Android SDK file not found: ${adbPath ?? 'adb'}.']; + } if (sdkVersions.isEmpty || latestVersion == null) { final StringBuffer msg = StringBuffer('No valid Android SDK platforms found in ${_platformsDir.path}.'); @@ -426,8 +436,9 @@ String getPlatformToolsPath(String binaryName) { final String path = fs.path.join(directory, 'platform-tools', binaryName); - if (fs.file(path).existsSync()) + if (fs.file(path).existsSync()) { return path; + } return null; } @@ -438,8 +449,9 @@ final List<String> searchFolders = <String>['emulator', 'tools']; for (final String folder in searchFolders) { final String path = fs.path.join(directory, folder, binaryName); - if (fs.file(path).existsSync()) + if (fs.file(path).existsSync()) { return path; + } } return null; } @@ -447,8 +459,9 @@ String getAvdManagerPath() { final String binaryName = platform.isWindows ? 'avdmanager.bat' : 'avdmanager'; final String path = fs.path.join(directory, 'tools', 'bin', binaryName); - if (fs.file(path).existsSync()) + if (fs.file(path).existsSync()) { return path; + } return null; } @@ -502,8 +515,9 @@ buildToolsVersion ??= Version.primary(buildTools); - if (buildToolsVersion == null) + if (buildToolsVersion == null) { return null; + } return AndroidSdkVersion._( this, @@ -576,8 +590,9 @@ /// Returns the version of the Android SDK manager tool or null if not found. String get sdkManagerVersion { - if (!processManager.canRun(sdkManagerPath)) + if (!processManager.canRun(sdkManagerPath)) { throwToolExit('Android sdkmanager not found. Update to the latest Android SDK to resolve this.'); + } final RunResult result = processUtils.runSync( <String>[sdkManagerPath, '--version'], environment: sdkManagerEnv, @@ -615,11 +630,13 @@ String get aaptPath => getBuildToolsPath('aapt'); List<String> validateSdkWellFormed() { - if (_exists(androidJarPath) != null) + if (_exists(androidJarPath) != null) { return <String>[_exists(androidJarPath)]; + } - if (_canRun(aaptPath) != null) + if (_canRun(aaptPath) != null) { return <String>[_canRun(aaptPath)]; + } return <String>[]; } @@ -639,14 +656,16 @@ String toString() => '[${sdk.directory}, SDK version $sdkLevel, build-tools $buildToolsVersionName]'; String _exists(String path) { - if (!fs.isFileSync(path)) + if (!fs.isFileSync(path)) { return 'Android SDK file not found: $path.'; + } return null; } String _canRun(String path) { - if (!processManager.canRun(path)) + if (!processManager.canRun(path)) { return 'Android SDK file not found: $path.'; + } return null; } }
diff --git a/packages/flutter_tools/lib/src/android/android_studio.dart b/packages/flutter_tools/lib/src/android/android_studio.dart index 82e6b4b..04e3474 100644 --- a/packages/flutter_tools/lib/src/android/android_studio.dart +++ b/packages/flutter_tools/lib/src/android/android_studio.dart
@@ -55,8 +55,9 @@ final String versionString = plistValues[PlistParser.kCFBundleShortVersionStringKey]; Version version; - if (versionString != null) + if (versionString != null) { version = Version.parse(versionString); + } String pathsSelectorValue; final Map<String, dynamic> jvmOptions = plistValues['JVMOptions']; @@ -140,8 +141,9 @@ @override int compareTo(AndroidStudio other) { final int result = version.compareTo(other.version); - if (result == 0) + if (result == 0) { return directory.compareTo(other.directory); + } return result; } @@ -150,8 +152,9 @@ final String configuredStudio = config.getValue('android-studio-dir'); if (configuredStudio != null) { String configuredStudioPath = configuredStudio; - if (platform.isMacOS && !configuredStudioPath.endsWith('Contents')) + if (platform.isMacOS && !configuredStudioPath.endsWith('Contents')) { configuredStudioPath = fs.path.join(configuredStudioPath, 'Contents'); + } return AndroidStudio(configuredStudioPath, configured: configuredStudio); } @@ -173,8 +176,9 @@ final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[]; void _checkForStudio(String path) { - if (!fs.isDirectorySync(path)) + if (!fs.isDirectorySync(path)) { return; + } try { final Iterable<Directory> directories = fs .directory(path) @@ -220,8 +224,9 @@ bool _hasStudioAt(String path, { Version newerThan }) { return studios.any((AndroidStudio studio) { - if (studio.directory != path) + if (studio.directory != path) { return false; + } if (newerThan != null) { return studio.version.compareTo(newerThan) >= 0; }
diff --git a/packages/flutter_tools/lib/src/android/gradle.dart b/packages/flutter_tools/lib/src/android/gradle.dart index 2d6f93b..049065a 100644 --- a/packages/flutter_tools/lib/src/android/gradle.dart +++ b/packages/flutter_tools/lib/src/android/gradle.dart
@@ -477,8 +477,9 @@ final FlutterManifest manifest = project.manifest; - if (androidSdk != null) + if (androidSdk != null) { changeIfNecessary('sdk.dir', escapePath(androidSdk.directory)); + } changeIfNecessary('flutter.sdk', escapePath(Cache.flutterRoot)); @@ -490,8 +491,9 @@ changeIfNecessary('flutter.versionCode', buildNumber?.toString()); } - if (changed) + if (changed) { settings.writeContents(localProperties); + } } /// Writes standard Android local properties to the specified [properties] file. @@ -652,16 +654,18 @@ status.stop(); flutterUsage.sendTiming('build', 'gradle-v1', Duration(milliseconds: sw.elapsedMilliseconds)); - if (exitCode != 0) + if (exitCode != 0) { throwToolExit('Gradle build failed: $exitCode', exitCode: exitCode); + } printStatus('Built ${fs.path.relative(project.android.gradleAppOutV1File.path)}.'); } String _hex(List<int> bytes) { final StringBuffer result = StringBuffer(); - for (int part in bytes) + for (int part in bytes) { result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); + } return result.toString(); } @@ -735,18 +739,24 @@ } assert(buildInfo.trackWidgetCreation != null); command.add('-Ptrack-widget-creation=${buildInfo.trackWidgetCreation}'); - if (buildInfo.extraFrontEndOptions != null) + if (buildInfo.extraFrontEndOptions != null) { command.add('-Pextra-front-end-options=${buildInfo.extraFrontEndOptions}'); - if (buildInfo.extraGenSnapshotOptions != null) + } + if (buildInfo.extraGenSnapshotOptions != null) { command.add('-Pextra-gen-snapshot-options=${buildInfo.extraGenSnapshotOptions}'); - if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty) + } + if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty) { command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); - if (buildInfo.fileSystemScheme != null) + } + if (buildInfo.fileSystemScheme != null) { command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}'); - if (androidBuildInfo.splitPerAbi) + } + if (androidBuildInfo.splitPerAbi) { command.add('-Psplit-per-abi=true'); - if (androidBuildInfo.proguard) + } + if (androidBuildInfo.proguard) { command.add('-Pproguard=true'); + } if (androidBuildInfo.targetArchs.isNotEmpty) { final String targetPlatforms = androidBuildInfo.targetArchs .map(getPlatformNameForAndroidArch).join(','); @@ -814,8 +824,9 @@ if (!isBuildingBundle) { final Iterable<File> apkFiles = findApkFiles(project, androidBuildInfo); - if (apkFiles.isEmpty) + if (apkFiles.isEmpty) { throwToolExit('Gradle build failed to produce an Android package.'); + } // Copy the first APK to app.apk, so `flutter run`, `flutter install`, etc. can find it. // TODO(blasten): Handle multiple APKs. apkFiles.first.copySync(project.apkDirectory.childFile('app.apk').path); @@ -836,8 +847,9 @@ } } else { final File bundleFile = findBundleFile(project, buildInfo); - if (bundleFile == null) + if (bundleFile == null) { throwToolExit('Gradle build failed to produce an Android bundle package.'); + } String appSize; if (buildInfo.mode == BuildMode.debug) { @@ -853,28 +865,32 @@ @visibleForTesting Iterable<File> findApkFiles(GradleProject project, AndroidBuildInfo androidBuildInfo) { final Iterable<String> apkFileNames = project.apkFilesFor(androidBuildInfo); - if (apkFileNames.isEmpty) + if (apkFileNames.isEmpty) { return const <File>[]; + } return apkFileNames.expand<File>((String apkFileName) { File apkFile = project.apkDirectory.childFile(apkFileName); - if (apkFile.existsSync()) + if (apkFile.existsSync()) { return <File>[apkFile]; + } final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String modeName = camelCase(buildInfo.modeName); apkFile = project.apkDirectory .childDirectory(modeName) .childFile(apkFileName); - if (apkFile.existsSync()) + if (apkFile.existsSync()) { return <File>[apkFile]; + } if (buildInfo.flavor != null) { // Android Studio Gradle plugin v3 adds flavor to path. apkFile = project.apkDirectory .childDirectory(buildInfo.flavor) .childDirectory(modeName) .childFile(apkFileName); - if (apkFile.existsSync()) + if (apkFile.existsSync()) { return <File>[apkFile]; + } } return const <File>[]; }); @@ -949,8 +965,9 @@ final Match match = _assembleTaskPattern.matchAsPrefix(s); if (match != null) { final String variant = match.group(1).toLowerCase(); - if (!variant.endsWith('test')) + if (!variant.endsWith('test')) { variants.add(variant); + } } } final Set<String> buildTypes = <String>{}; @@ -966,8 +983,9 @@ } } } - if (productFlavors.isEmpty) + if (productFlavors.isEmpty) { buildTypes.addAll(variants); + } return GradleProject( buildTypes.toList(), productFlavors.toList(), @@ -1002,33 +1020,36 @@ String _buildTypeFor(BuildInfo buildInfo) { final String modeName = camelCase(buildInfo.modeName); - if (buildTypes.contains(modeName.toLowerCase())) + if (buildTypes.contains(modeName.toLowerCase())) { return modeName; + } return null; } String _productFlavorFor(BuildInfo buildInfo) { - if (buildInfo.flavor == null) + if (buildInfo.flavor == null) { return productFlavors.isEmpty ? '' : null; - else if (productFlavors.contains(buildInfo.flavor)) + } else if (productFlavors.contains(buildInfo.flavor)) { return buildInfo.flavor; - else - return null; + } + return null; } String assembleTaskFor(BuildInfo buildInfo) { final String buildType = _buildTypeFor(buildInfo); final String productFlavor = _productFlavorFor(buildInfo); - if (buildType == null || productFlavor == null) + if (buildType == null || productFlavor == null) { return null; + } return 'assemble${toTitleCase(productFlavor)}${toTitleCase(buildType)}'; } Iterable<String> apkFilesFor(AndroidBuildInfo androidBuildInfo) { final String buildType = _buildTypeFor(androidBuildInfo.buildInfo); final String productFlavor = _productFlavorFor(androidBuildInfo.buildInfo); - if (buildType == null || productFlavor == null) + if (buildType == null || productFlavor == null) { return const <String>[]; + } final String flavorString = productFlavor.isEmpty ? '' : '-' + productFlavor; if (androidBuildInfo.splitPerAbi) { @@ -1043,16 +1064,18 @@ String bundleTaskFor(BuildInfo buildInfo) { final String buildType = _buildTypeFor(buildInfo); final String productFlavor = _productFlavorFor(buildInfo); - if (buildType == null || productFlavor == null) + if (buildType == null || productFlavor == null) { return null; + } return 'bundle${toTitleCase(productFlavor)}${toTitleCase(buildType)}'; } String aarTaskFor(BuildInfo buildInfo) { final String buildType = _buildTypeFor(buildInfo); final String productFlavor = _productFlavorFor(buildInfo); - if (buildType == null || productFlavor == null) + if (buildType == null || productFlavor == null) { return null; + } return 'assembleAar${toTitleCase(productFlavor)}${toTitleCase(buildType)}'; } }
diff --git a/packages/flutter_tools/lib/src/application_package.dart b/packages/flutter_tools/lib/src/application_package.dart index 59c577f..2345aa7 100644 --- a/packages/flutter_tools/lib/src/application_package.dart +++ b/packages/flutter_tools/lib/src/application_package.dart
@@ -501,8 +501,9 @@ ApkManifestData._(this._data); static ApkManifestData parseFromXmlDump(String data) { - if (data == null || data.trim().isEmpty) + if (data == null || data.trim().isEmpty) { return null; + } final List<String> lines = data.split('\n'); assert(lines.length > 3);
diff --git a/packages/flutter_tools/lib/src/artifacts.dart b/packages/flutter_tools/lib/src/artifacts.dart index 0459f09..157410e 100644 --- a/packages/flutter_tools/lib/src/artifacts.dart +++ b/packages/flutter_tools/lib/src/artifacts.dart
@@ -336,12 +336,15 @@ } TargetPlatform get _currentHostPlatform { - if (platform.isMacOS) + if (platform.isMacOS) { return TargetPlatform.darwin_x64; - if (platform.isLinux) + } + if (platform.isLinux) { return TargetPlatform.linux_x64; - if (platform.isWindows) + } + if (platform.isWindows) { return TargetPlatform.windows_x64; + } throw UnimplementedError('Host OS not supported.'); } } @@ -439,8 +442,9 @@ final String genSnapshotName = _artifactToFileName(Artifact.genSnapshot); for (String clangDir in clangDirs) { final String genSnapshotPath = fs.path.join(engineOutPath, clangDir, genSnapshotName); - if (processManager.canRun(genSnapshotPath)) + if (processManager.canRun(genSnapshotPath)) { return genSnapshotPath; + } } throw Exception('Unable to find $genSnapshotName'); }
diff --git a/packages/flutter_tools/lib/src/asset.dart b/packages/flutter_tools/lib/src/asset.dart index 737c9c7..0e066e4 100644 --- a/packages/flutter_tools/lib/src/asset.dart +++ b/packages/flutter_tools/lib/src/asset.dart
@@ -81,12 +81,14 @@ @override bool needsBuild({ String manifestPath = defaultManifestPath }) { - if (_lastBuildTimestamp == null) + if (_lastBuildTimestamp == null) { return true; + } final FileStat stat = fs.file(manifestPath).statSync(); - if (stat.type == FileSystemEntityType.notFound) + if (stat.type == FileSystemEntityType.notFound) { return true; + } for (Directory directory in _wildcardDirectories.values) { final DateTime dateTime = directory.statSync().modified; @@ -119,8 +121,9 @@ printError('$e'); return 1; } - if (flutterManifest == null) + if (flutterManifest == null) { return 1; + } // If the last build time isn't set before this early return, empty pubspecs will // hang on hot reload, as the incremental dill files will never be copied to the @@ -164,11 +167,13 @@ if (package != null && package.scheme == 'file') { final String packageManifestPath = fs.path.fromUri(package.resolve('../pubspec.yaml')); final FlutterManifest packageFlutterManifest = FlutterManifest.createFromPath(packageManifestPath); - if (packageFlutterManifest == null) + if (packageFlutterManifest == null) { continue; + } // Skip the app itself - if (packageFlutterManifest.appName == flutterManifest.appName) + if (packageFlutterManifest.appName == flutterManifest.appName) { continue; + } final String packageBasePath = fs.path.dirname(packageManifestPath); final Map<_Asset, List<_Asset>> packageAssets = _parseAssets( @@ -179,8 +184,9 @@ packageName: packageName, ); - if (packageAssets == null) + if (packageAssets == null) { return 1; + } assetVariants.addAll(packageAssets); fonts.addAll(_parseFonts( @@ -262,8 +268,9 @@ /// The delta between what the entryUri is and the relativeUri (e.g., /// packages/flutter_gallery). Uri get symbolicPrefixUri { - if (entryUri == relativeUri) + if (entryUri == relativeUri) { return null; + } final int index = entryUri.path.indexOf(relativeUri.path); return index == -1 ? null : Uri(path: entryUri.path.substring(0, index)); } @@ -273,10 +280,12 @@ @override bool operator ==(dynamic other) { - if (identical(other, this)) + if (identical(other, this)) { return true; - if (other.runtimeType != runtimeType) + } + if (other.runtimeType != runtimeType) { return false; + } final _Asset otherAsset = other; return otherAsset.baseDir == baseDir && otherAsset.relativeUri == relativeUri @@ -410,8 +419,9 @@ for (_Asset main in sortedKeys) { final List<String> variants = <String>[]; - for (_Asset variant in assetVariants[main]) + for (_Asset variant in assetVariants[main]) { variants.add(variant.entryUri.path); + } jsonObject[main.entryUri.path] = variants; } return DevFSStringContent(json.encode(jsonObject)); @@ -494,22 +504,25 @@ final String assetName = fs.path.basename(assetPath); final String directory = fs.path.dirname(assetPath); - if (!fs.directory(directory).existsSync()) + if (!fs.directory(directory).existsSync()) { return const <String>[]; + } if (_cache[directory] == null) { final List<String> paths = <String>[]; for (FileSystemEntity entity in fs.directory(directory).listSync(recursive: true)) { final String path = entity.path; - if (fs.isFileSync(path) && !_excluded.any((String exclude) => path.startsWith(exclude))) + if (fs.isFileSync(path) && !_excluded.any((String exclude) => path.startsWith(exclude))) { paths.add(path); + } } final Map<String, List<String>> variants = <String, List<String>>{}; for (String path in paths) { final String variantName = fs.path.basename(path); - if (directory == fs.path.dirname(path)) + if (directory == fs.path.dirname(path)) { continue; + } variants[variantName] ??= <String>[]; variants[variantName].add(path); } @@ -669,8 +682,9 @@ // The asset is referenced in the pubspec.yaml as // 'packages/PACKAGE_NAME/PATH/TO/ASSET . final _Asset packageAsset = _resolvePackageAsset(assetUri, packageMap); - if (packageAsset != null) + if (packageAsset != null) { return packageAsset; + } } return _Asset(
diff --git a/packages/flutter_tools/lib/src/base/build.dart b/packages/flutter_tools/lib/src/base/build.dart index 3e8062d..1b2203e 100644 --- a/packages/flutter_tools/lib/src/base/build.dart +++ b/packages/flutter_tools/lib/src/base/build.dart
@@ -288,8 +288,9 @@ printTrace('Compiling Dart to kernel: $mainPath'); - if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty) + if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty) { printTrace('Extra front-end options: $extraFrontEndOptions'); + } final String depfilePath = fs.path.join(outputPath, 'kernel_compile.d'); final KernelCompiler kernelCompiler = await kernelCompilerFactory.create(flutterProject); @@ -319,8 +320,9 @@ } bool _isValidAotPlatform(TargetPlatform platform, BuildMode buildMode) { - if (buildMode == BuildMode.debug) + if (buildMode == BuildMode.debug) { return false; + } return const <TargetPlatform>[ TargetPlatform.android_arm, TargetPlatform.android_arm64,
diff --git a/packages/flutter_tools/lib/src/base/config.dart b/packages/flutter_tools/lib/src/base/config.dart index 0fef57d..e16ba3d 100644 --- a/packages/flutter_tools/lib/src/base/config.dart +++ b/packages/flutter_tools/lib/src/base/config.dart
@@ -10,8 +10,9 @@ class Config { Config([File configFile]) { _configFile = configFile ?? fs.file(fs.path.join(_userHomeDir(), '.flutter_settings')); - if (_configFile.existsSync()) + if (_configFile.existsSync()) { _values = json.decode(_configFile.readAsStringSync()); + } } static Config get instance => context.get<Config>();
diff --git a/packages/flutter_tools/lib/src/base/context.dart b/packages/flutter_tools/lib/src/base/context.dart index a21bd45..e3f2438 100644 --- a/packages/flutter_tools/lib/src/base/context.dart +++ b/packages/flutter_tools/lib/src/base/context.dart
@@ -81,8 +81,9 @@ /// If the generator ends up triggering a reentrant call, it signals a /// dependency cycle, and a [ContextDependencyCycleException] will be thrown. dynamic _generateIfNecessary(Type type, Map<Type, Generator> generators) { - if (!generators.containsKey(type)) + if (!generators.containsKey(type)) { return null; + } return _values.putIfAbsent(type, () { _reentrantChecks ??= <Type>[]; @@ -99,8 +100,9 @@ return _boxNull(generators[type]()); } finally { _reentrantChecks.removeLast(); - if (_reentrantChecks.isEmpty) + if (_reentrantChecks.isEmpty) { _reentrantChecks = null; + } } }); } @@ -120,8 +122,9 @@ @Deprecated('use get<T> instead for type safety.') Object operator [](Type type) { dynamic value = _generateIfNecessary(type, _overrides); - if (value == null && _parent != null) + if (value == null && _parent != null) { value = _parent[type]; + } return _unboxNull(value ?? _generateIfNecessary(type, _fallbacks)); } @@ -164,14 +167,18 @@ AppContext ctx = this; while (ctx != null) { buf.write('AppContext'); - if (ctx.name != null) + if (ctx.name != null) { buf.write('[${ctx.name}]'); - if (ctx._overrides.isNotEmpty) + } + if (ctx._overrides.isNotEmpty) { buf.write('\n$indent overrides: [${ctx._overrides.keys.join(', ')}]'); - if (ctx._fallbacks.isNotEmpty) + } + if (ctx._fallbacks.isNotEmpty) { buf.write('\n$indent fallbacks: [${ctx._fallbacks.keys.join(', ')}]'); - if (ctx._parent != null) + } + if (ctx._parent != null) { buf.write('\n$indent parent: '); + } ctx = ctx._parent; indent += ' '; }
diff --git a/packages/flutter_tools/lib/src/base/file_system.dart b/packages/flutter_tools/lib/src/base/file_system.dart index 3f7dadb..2283fe0 100644 --- a/packages/flutter_tools/lib/src/base/file_system.dart +++ b/packages/flutter_tools/lib/src/base/file_system.dart
@@ -55,8 +55,9 @@ /// Create the ancestor directories of a file path if they do not already exist. void ensureDirectoryExists(String filePath) { final String dirPath = fs.path.dirname(filePath); - if (fs.isDirectorySync(dirPath)) + if (fs.isDirectorySync(dirPath)) { return; + } try { fs.directory(dirPath).createSync(recursive: true); } on FileSystemException catch (e) { @@ -76,11 +77,13 @@ void onFileCopied(File srcFile, File destFile), } ) { - if (!srcDir.existsSync()) + if (!srcDir.existsSync()) { throw Exception('Source directory "${srcDir.path}" does not exist, nothing to copy'); + } - if (!destDir.existsSync()) + if (!destDir.existsSync()) { destDir.createSync(recursive: true); + } for (FileSystemEntity entity in srcDir.listSync()) { final String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename); @@ -122,8 +125,9 @@ throwToolExit('Invalid record-to location: $dirname ("$basename" exists as non-directory)'); break; case FileSystemEntityType.directory: - if (_kLocalFs.directory(location).listSync(followLinks: false).isNotEmpty) + if (_kLocalFs.directory(location).listSync(followLinks: false).isNotEmpty) { throwToolExit('Invalid record-to location: $dirname ("$basename" is not empty)'); + } break; case FileSystemEntityType.notFound: _kLocalFs.directory(location).createSync(recursive: true); @@ -140,8 +144,9 @@ /// If the target directory does not exist, a [ToolExit] will be thrown. Directory getReplaySource(String dirname, String basename) { final Directory dir = _kLocalFs.directory(_kLocalFs.path.join(dirname, basename)); - if (!dir.existsSync()) + if (!dir.existsSync()) { throwToolExit('Invalid replay-from location: $dirname ("$basename" does not exist)'); + } return dir; } @@ -166,8 +171,9 @@ /// /// Returns false, if [entity] exists, but [referenceFile] does not. bool isOlderThanReference({ @required FileSystemEntity entity, @required File referenceFile }) { - if (!entity.existsSync()) + if (!entity.existsSync()) { return true; + } return referenceFile.existsSync() && referenceFile.lastModifiedSync().isAfter(entity.statSync().modified); }
diff --git a/packages/flutter_tools/lib/src/base/fingerprint.dart b/packages/flutter_tools/lib/src/base/fingerprint.dart index 663a254..4ff434a 100644 --- a/packages/flutter_tools/lib/src/base/fingerprint.dart +++ b/packages/flutter_tools/lib/src/base/fingerprint.dart
@@ -61,15 +61,18 @@ } try { final File fingerprintFile = fs.file(fingerprintPath); - if (!fingerprintFile.existsSync()) + if (!fingerprintFile.existsSync()) { return false; + } - if (!_depfilePaths.every(fs.isFileSync)) + if (!_depfilePaths.every(fs.isFileSync)) { return false; + } final List<String> paths = _getPaths(); - if (!paths.every(fs.isFileSync)) + if (!paths.every(fs.isFileSync)) { return false; + } final Fingerprint oldFingerprint = Fingerprint.fromJson(fingerprintFile.readAsStringSync()); final Fingerprint newFingerprint = buildFingerprint(); @@ -110,8 +113,9 @@ Fingerprint.fromBuildInputs(Map<String, String> properties, Iterable<String> inputPaths) { final Iterable<File> files = inputPaths.map<File>(fs.file); final Iterable<File> missingInputs = files.where((File file) => !file.existsSync()); - if (missingInputs.isNotEmpty) + if (missingInputs.isNotEmpty) { throw ArgumentError('Missing input files:\n' + missingInputs.join('\n')); + } _checksums = <String, String>{}; for (File file in files) { @@ -129,8 +133,9 @@ final Map<String, dynamic> content = json.decode(jsonData); final String version = content['version']; - if (version != FlutterVersion.instance.frameworkRevision) + if (version != FlutterVersion.instance.frameworkRevision) { throw ArgumentError('Incompatible fingerprint version: $version'); + } _checksums = content['files']?.cast<String,String>() ?? <String, String>{}; _properties = content['properties']?.cast<String,String>() ?? <String, String>{}; } @@ -146,10 +151,12 @@ @override bool operator==(dynamic other) { - if (identical(other, this)) + if (identical(other, this)) { return true; - if (other.runtimeType != runtimeType) + } + if (other.runtimeType != runtimeType) { return false; + } final Fingerprint typedOther = other; return _equalMaps(typedOther._checksums, _checksums) && _equalMaps(typedOther._properties, _properties);
diff --git a/packages/flutter_tools/lib/src/base/flags.dart b/packages/flutter_tools/lib/src/base/flags.dart index b4e3ab1..25aaa06 100644 --- a/packages/flutter_tools/lib/src/base/flags.dart +++ b/packages/flutter_tools/lib/src/base/flags.dart
@@ -36,10 +36,11 @@ dynamic operator [](String key) { final ArgResults commandResults = _globalResults.command; final Iterable<String> options = commandResults?.options; - if (options != null && options.contains(key)) + if (options != null && options.contains(key)) { return commandResults[key]; - else if (_globalResults.options.contains(key)) + } else if (_globalResults.options.contains(key)) { return _globalResults[key]; + } return null; }
diff --git a/packages/flutter_tools/lib/src/base/io.dart b/packages/flutter_tools/lib/src/base/io.dart index dde26e1..e7aea0a 100644 --- a/packages/flutter_tools/lib/src/base/io.dart +++ b/packages/flutter_tools/lib/src/base/io.dart
@@ -164,8 +164,9 @@ @override Stream<ProcessSignal> watch() { - if (platform.isWindows) + if (platform.isWindows) { return const Stream<ProcessSignal>.empty(); + } return super.watch(); } }
diff --git a/packages/flutter_tools/lib/src/base/logger.dart b/packages/flutter_tools/lib/src/base/logger.dart index c44d739..5a6460a 100644 --- a/packages/flutter_tools/lib/src/base/logger.dart +++ b/packages/flutter_tools/lib/src/base/logger.dart
@@ -167,12 +167,14 @@ _status?.pause(); message ??= ''; message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap); - if (emphasis == true) + if (emphasis == true) { message = terminal.bolden(message); + } message = terminal.color(message, color ?? TerminalColor.red); stderr.writeln(message); - if (stackTrace != null) + if (stackTrace != null) { stderr.writeln(stackTrace.toString()); + } _status?.resume(); } @@ -189,12 +191,15 @@ _status?.pause(); message ??= ''; message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap); - if (emphasis == true) + if (emphasis == true) { message = terminal.bolden(message); - if (color != null) + } + if (color != null) { message = terminal.color(message, color); - if (newline != false) + } + if (newline != false) { message = '$message\n'; + } writeToStdOut(message); _status?.resume(); } @@ -307,10 +312,11 @@ int hangingIndent, bool wrap, }) { - if (newline != false) + if (newline != false) { _status.writeln(wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap)); - else + } else { _status.write(wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap)); + } } @override @@ -414,8 +420,9 @@ } void _emit(_LogType type, String message, [ StackTrace stackTrace ]) { - if (message.trim().isEmpty) + if (message.trim().isEmpty) { return; + } final int millis = stopwatch.elapsedMilliseconds; stopwatch.reset(); @@ -426,8 +433,9 @@ prefix = ''.padLeft(prefixWidth); } else { prefix = '+$millis ms'.padLeft(prefixWidth); - if (millis >= 100) + if (millis >= 100) { prefix = terminal.bolden(prefix); + } } prefix = '[$prefix] '; @@ -436,8 +444,9 @@ if (type == _LogType.error) { parent.printError(prefix + terminal.bolden(indentMessage)); - if (stackTrace != null) + if (stackTrace != null) { parent.printError(indent + stackTrace.toString().replaceAll('\n', '\n$indent')); + } } else if (type == _LogType.status) { parent.printStatus(prefix + terminal.bolden(indentMessage)); } else { @@ -480,8 +489,13 @@ VoidCallback onFinish, SlowWarningCallback slowWarningCallback, }) { - if (terminal.supportsColor) - return AnsiSpinner(timeout: timeout, onFinish: onFinish, slowWarningCallback: slowWarningCallback)..start(); + if (terminal.supportsColor) { + return AnsiSpinner( + timeout: timeout, + onFinish: onFinish, + slowWarningCallback: slowWarningCallback, + )..start(); + } return SilentStatus(timeout: timeout, onFinish: onFinish)..start(); } @@ -497,8 +511,9 @@ @protected String get elapsedTime { - if (timeout == null || timeout > timeoutConfiguration.fastOperation) + if (timeout == null || timeout > timeoutConfiguration.fastOperation) { return getElapsedAsSeconds(_stopwatch.elapsed); + } return getElapsedAsMilliseconds(_stopwatch.elapsed); } @@ -528,8 +543,9 @@ void finish() { assert(_stopwatch.isRunning); _stopwatch.stop(); - if (onFinish != null) + if (onFinish != null) { onFinish(); + } } } @@ -572,8 +588,9 @@ @override void stop() { - if (!_messageShowingOnCurrentLine) + if (!_messageShowingOnCurrentLine) { _printMessage(); + } super.stop(); writeSummaryInformation(); stdout.write('\n'); @@ -582,8 +599,9 @@ @override void cancel() { super.cancel(); - if (_messageShowingOnCurrentLine) + if (_messageShowingOnCurrentLine) { stdout.write('\n'); + } } /// Prints a (minimum) 8 character padded time. @@ -596,8 +614,9 @@ void writeSummaryInformation() { assert(_messageShowingOnCurrentLine); stdout.write(elapsedTime.padLeft(_kTimePadding)); - if (seemsSlow) + if (seemsSlow) { stdout.write(' (!)'); + } } @override @@ -773,11 +792,13 @@ /// If [multilineOutput] is true, then it prints the message again on a new /// line before writing the elapsed time. void writeSummaryInformation() { - if (multilineOutput) + if (multilineOutput) { stdout.write('\n${'$message Done'.padRight(padding)}$_margin'); + } stdout.write(elapsedTime.padLeft(_kTimePadding)); - if (seemsSlow) + if (seemsSlow) { stdout.write(' (!)'); + } } void _clearStatus() {
diff --git a/packages/flutter_tools/lib/src/base/net.dart b/packages/flutter_tools/lib/src/base/net.dart index df14055..d77a812 100644 --- a/packages/flutter_tools/lib/src/base/net.dart +++ b/packages/flutter_tools/lib/src/base/net.dart
@@ -21,8 +21,9 @@ while (true) { attempts += 1; final List<int> result = await _attempt(url); - if (result != null) + if (result != null) { return result; + } if (maxAttempts != null && attempts >= maxAttempts) { printStatus('Download failed -- retry $attempts'); return null; @@ -30,8 +31,9 @@ printStatus('Download failed -- attempting retry $attempts in ' '$durationSeconds second${ durationSeconds == 1 ? "" : "s"}...'); await Future<void>.delayed(Duration(seconds: durationSeconds)); - if (durationSeconds < 64) + if (durationSeconds < 64) { durationSeconds *= 2; + } } }
diff --git a/packages/flutter_tools/lib/src/base/os.dart b/packages/flutter_tools/lib/src/base/os.dart index 8e1d714..c624aad 100644 --- a/packages/flutter_tools/lib/src/base/os.dart +++ b/packages/flutter_tools/lib/src/base/os.dart
@@ -41,8 +41,9 @@ /// if `which` was not able to locate the binary. File which(String execName) { final List<File> result = _which(execName); - if (result == null || result.isEmpty) + if (result == null || result.isEmpty) { return null; + } return result.first; } @@ -142,12 +143,14 @@ @override List<File> _which(String execName, { bool all = false }) { final List<String> command = <String>['which']; - if (all) + if (all) { command.add('-a'); + } command.add(execName); final ProcessResult result = processManager.runSync(command); - if (result.exitCode != 0) + if (result.exitCode != 0) { return const <File>[]; + } final String stdout = result.stdout; return stdout.trim().split('\n').map<File>((String path) => fs.file(path.trim())).toList(); } @@ -234,11 +237,13 @@ List<File> _which(String execName, { bool all = false }) { // `where` always returns all matches, not just the first one. final ProcessResult result = processManager.runSync(<String>['where', execName]); - if (result.exitCode != 0) + if (result.exitCode != 0) { return const <File>[]; + } final List<String> lines = result.stdout.trim().split('\n'); - if (all) + if (all) { return lines.map<File>((String path) => fs.file(path.trim())).toList(); + } return <File>[fs.file(lines.first.trim())]; } @@ -298,12 +303,14 @@ void _unpackArchive(Archive archive, Directory targetDirectory) { for (ArchiveFile archiveFile in archive.files) { // The archive package doesn't correctly set isFile. - if (!archiveFile.isFile || archiveFile.name.endsWith('/')) + if (!archiveFile.isFile || archiveFile.name.endsWith('/')) { continue; + } final File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name)); - if (!destFile.parent.existsSync()) + if (!destFile.parent.existsSync()) { destFile.parent.createSync(recursive: true); + } destFile.writeAsBytesSync(archiveFile.content); } } @@ -320,10 +327,11 @@ if (_name == null) { final ProcessResult result = processManager.runSync( <String>['ver'], runInShell: true); - if (result.exitCode == 0) + if (result.exitCode == 0) { _name = result.stdout.trim(); - else + } else { _name = super.name; + } } return _name; } @@ -340,11 +348,13 @@ const String kProjectRootSentinel = 'pubspec.yaml'; directory ??= fs.currentDirectory.path; while (true) { - if (fs.isFileSync(fs.path.join(directory, kProjectRootSentinel))) + if (fs.isFileSync(fs.path.join(directory, kProjectRootSentinel))) { return directory; + } final String parent = fs.path.dirname(directory); - if (directory == parent) + if (directory == parent) { return null; + } directory = parent; } }
diff --git a/packages/flutter_tools/lib/src/base/process.dart b/packages/flutter_tools/lib/src/base/process.dart index 99229fd..c012515 100644 --- a/packages/flutter_tools/lib/src/base/process.dart +++ b/packages/flutter_tools/lib/src/base/process.dart
@@ -126,10 +126,12 @@ @override String toString() { final StringBuffer out = StringBuffer(); - if (processResult.stdout.isNotEmpty) + if (processResult.stdout.isNotEmpty) { out.writeln(processResult.stdout); - if (processResult.stderr.isNotEmpty) + } + if (processResult.stderr.isNotEmpty) { out.writeln(processResult.stderr); + } return out.toString().trimRight(); } @@ -436,14 +438,16 @@ .transform<String>(const LineSplitter()) .where((String line) => filter == null || filter.hasMatch(line)) .listen((String line) { - if (mapFunction != null) + if (mapFunction != null) { line = mapFunction(line); + } if (line != null) { final String message = '$prefix$line'; - if (trace) + if (trace) { printTrace(message); - else + } else { printStatus(message, wrap: false); + } } }); final StreamSubscription<String> stderrSubscription = process.stderr @@ -451,10 +455,12 @@ .transform<String>(const LineSplitter()) .where((String line) => filter == null || filter.hasMatch(line)) .listen((String line) { - if (mapFunction != null) + if (mapFunction != null) { line = mapFunction(line); - if (line != null) + } + if (line != null) { printError('$prefix$line', wrap: false); + } }); // Wait for stdout to be fully processed @@ -504,10 +510,11 @@ Map<String, String> environment, ]) { if (allowReentrantFlutter) { - if (environment == null) + if (environment == null) { environment = <String, String>{'FLUTTER_ALREADY_LOCKED': 'true'}; - else + } else { environment['FLUTTER_ALREADY_LOCKED'] = 'true'; + } } return environment;
diff --git a/packages/flutter_tools/lib/src/base/terminal.dart b/packages/flutter_tools/lib/src/base/terminal.dart index 4f723cd..ed2e0ac 100644 --- a/packages/flutter_tools/lib/src/base/terminal.dart +++ b/packages/flutter_tools/lib/src/base/terminal.dart
@@ -117,8 +117,9 @@ String bolden(String message) { assert(message != null); - if (!supportsColor || message.isEmpty) + if (!supportsColor || message.isEmpty) { return message; + } final StringBuffer buffer = StringBuffer(); for (String line in message.split('\n')) { // If there were bolds or resetBolds in the string before, then nuke them: @@ -136,8 +137,9 @@ String color(String message, TerminalColor color) { assert(message != null); - if (!supportsColor || color == null || message.isEmpty) + if (!supportsColor || color == null || message.isEmpty) { return message; + } final StringBuffer buffer = StringBuffer(); final String colorCodes = _colorMap[color]; for (String line in message.split('\n')) { @@ -218,16 +220,18 @@ while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) { if (prompt != null) { printStatus(prompt, emphasis: true, newline: false); - if (displayAcceptedCharacters) + if (displayAcceptedCharacters) { printStatus(' [${charactersToDisplay.join("|")}]', newline: false); + } printStatus(': ', emphasis: true, newline: false); } choice = await keystrokes.first; printStatus(choice); } singleCharMode = false; - if (defaultChoiceIndex != null && choice == '\n') + if (defaultChoiceIndex != null && choice == '\n') { choice = acceptedCharacters[defaultChoiceIndex]; + } return choice; } }
diff --git a/packages/flutter_tools/lib/src/base/utils.dart b/packages/flutter_tools/lib/src/base/utils.dart index 2cfbf7a..382060d 100644 --- a/packages/flutter_tools/lib/src/base/utils.dart +++ b/packages/flutter_tools/lib/src/base/utils.dart
@@ -86,8 +86,9 @@ } String toTitleCase(String str) { - if (str.isEmpty) + if (str.isEmpty) { return str; + } return str.substring(0, 1).toUpperCase() + str.substring(1); } @@ -108,8 +109,9 @@ while (true) { final String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext'; final File file = fs.file(fs.path.join(dir.path, name)); - if (!file.existsSync()) + if (!file.existsSync()) { return file; + } i++; } } @@ -189,11 +191,13 @@ SettingsFile.parse(String contents) { for (String line in contents.split('\n')) { line = line.trim(); - if (line.startsWith('#') || line.isEmpty) + if (line.startsWith('#') || line.isEmpty) { continue; + } final int index = line.indexOf('='); - if (index != -1) + if (index != -1) { values[line.substring(0, index)] = line.substring(index + 1); + } } } @@ -270,8 +274,9 @@ Timer _timer; Future<void> _handleCallback() async { - if (_canceled) + if (_canceled) { return; + } try { await callback(); @@ -279,8 +284,9 @@ printTrace('Error from poller: $error'); } - if (!_canceled) + if (!_canceled) { _timer = Timer(pollingInterval, _handleCallback); + } } /// Cancels the poller.
diff --git a/packages/flutter_tools/lib/src/base/version.dart b/packages/flutter_tools/lib/src/base/version.dart index 80ad3f0..83021fe 100644 --- a/packages/flutter_tools/lib/src/base/version.dart +++ b/packages/flutter_tools/lib/src/base/version.dart
@@ -7,22 +7,27 @@ factory Version(int major, int minor, int patch, {String text}) { if (text == null) { text = major == null ? '0' : '$major'; - if (minor != null) + if (minor != null) { text = '$text.$minor'; - if (patch != null) + } + if (patch != null) { text = '$text.$patch'; + } } return Version._(major ?? 0, minor ?? 0, patch ?? 0, text); } Version._(this.major, this.minor, this.patch, this._text) { - if (major < 0) + if (major < 0) { throw ArgumentError('Major version must be non-negative.'); - if (minor < 0) + } + if (minor < 0) { throw ArgumentError('Minor version must be non-negative.'); - if (patch < 0) + } + if (patch < 0) { throw ArgumentError('Patch version must be non-negative.'); + } } /// Creates a new [Version] by parsing [text]. @@ -80,8 +85,9 @@ /// is ignored. @override bool operator ==(dynamic other) { - if (other is! Version) + if (other is! Version) { return false; + } return major == other.major && minor == other.minor && patch == other.patch; } @@ -95,10 +101,12 @@ @override int compareTo(Version other) { - if (major != other.major) + if (major != other.major) { return major.compareTo(other.major); - if (minor != other.minor) + } + if (minor != other.minor) { return minor.compareTo(other.minor); + } return patch.compareTo(other.patch); }
diff --git a/packages/flutter_tools/lib/src/build_info.dart b/packages/flutter_tools/lib/src/build_info.dart index cb7afb8..c406438 100644 --- a/packages/flutter_tools/lib/src/build_info.dart +++ b/packages/flutter_tools/lib/src/build_info.dart
@@ -414,12 +414,15 @@ } HostPlatform getCurrentHostPlatform() { - if (platform.isMacOS) + if (platform.isMacOS) { return HostPlatform.darwin_x64; - if (platform.isLinux) + } + if (platform.isLinux) { return HostPlatform.linux_x64; - if (platform.isWindows) + } + if (platform.isWindows) { return HostPlatform.windows_x64; + } printError('Unsupported host platform, defaulting to Linux'); @@ -430,8 +433,9 @@ String getBuildDirectory() { // TODO(johnmccutchan): Stop calling this function as part of setting // up command line argument processing. - if (context == null || config == null) + if (context == null || config == null) { return 'build'; + } final String buildDir = config.getValue('build-dir') ?? 'build'; if (fs.path.isAbsolute(buildDir)) {
diff --git a/packages/flutter_tools/lib/src/bundle.dart b/packages/flutter_tools/lib/src/bundle.dart index 573f985..cd5abb8 100644 --- a/packages/flutter_tools/lib/src/bundle.dart +++ b/packages/flutter_tools/lib/src/bundle.dart
@@ -79,8 +79,9 @@ DevFSContent kernelContent; if (!precompiledSnapshot) { - if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty) + if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty) { printTrace('Extra front-end options: $extraFrontEndOptions'); + } ensureDirectoryExists(applicationKernelFilePath); final KernelCompiler kernelCompiler = await kernelCompilerFactory.create(flutterProject); final CompilerOutput compilerOutput = await kernelCompiler.compile( @@ -109,8 +110,9 @@ packagesPath: packagesPath, reportLicensedPackages: reportLicensedPackages, ); - if (assets == null) + if (assets == null) { throwToolExit('Error building assets', exitCode: 1); + } await assemble( buildMode: buildMode, @@ -141,8 +143,9 @@ includeDefaultFonts: includeDefaultFonts, reportLicensedPackages: reportLicensedPackages, ); - if (result != 0) + if (result != 0) { return null; + } return assetBundle; } @@ -177,8 +180,9 @@ Directory bundleDir, Map<String, DevFSContent> assetEntries, ) async { - if (bundleDir.existsSync()) + if (bundleDir.existsSync()) { bundleDir.deleteSync(recursive: true); + } bundleDir.createSync(recursive: true); // Limit number of open files to avoid running out of file descriptors.
diff --git a/packages/flutter_tools/lib/src/cache.dart b/packages/flutter_tools/lib/src/cache.dart index 4054aee..af4d749 100644 --- a/packages/flutter_tools/lib/src/cache.dart +++ b/packages/flutter_tools/lib/src/cache.dart
@@ -138,8 +138,9 @@ /// POSIX flock semantics). Long-lived commands should release the lock by /// calling [Cache.releaseLockEarly] once they are no longer touching the cache. static Future<void> lock() async { - if (!_lockEnabled) + if (!_lockEnabled) { return; + } assert(_lock == null); final File lockFile = fs.file(fs.path.join(flutterRoot, 'bin', 'cache', 'lockfile')); @@ -170,8 +171,9 @@ /// Releases the lock. This is not necessary unless the process is long-lived. static void releaseLockEarly() { - if (!_lockEnabled || _lock == null) + if (!_lockEnabled || _lock == null) { return; + } _lock.closeSync(); _lock = null; } @@ -212,10 +214,11 @@ /// Return the top-level directory in the cache; this is `bin/cache`. Directory getRoot() { - if (_rootOverride != null) + if (_rootOverride != null) { return fs.directory(fs.path.join(_rootOverride.path, 'bin', 'cache')); - else + } else { return fs.directory(fs.path.join(flutterRoot, 'bin', 'cache')); + } } /// Return a directory in the cache dir. For `pkg`, this will return `bin/cache/pkg`. @@ -435,8 +438,9 @@ String get _storageBaseUrl { final String overrideUrl = platform.environment['FLUTTER_STORAGE_BASE_URL']; - if (overrideUrl == null) + if (overrideUrl == null) { return 'https://storage.googleapis.com'; + } _maybeWarnAboutStorageOverride(overrideUrl); return overrideUrl; } @@ -485,8 +489,9 @@ bool _hasWarnedAboutStorageOverride = false; void _maybeWarnAboutStorageOverride(String overrideUrl) { - if (_hasWarnedAboutStorageOverride) + if (_hasWarnedAboutStorageOverride) { return; + } logger.printStatus( 'Flutter assets will be downloaded from $overrideUrl. Make sure you trust this source!', emphasis: true, @@ -882,12 +887,14 @@ } for (String scriptName in _gradleScripts) { final File scriptFile = fs.file(fs.path.join(wrapperDir.path, scriptName)); - if (!scriptFile.existsSync()) + if (!scriptFile.existsSync()) { return false; + } } final File gradleWrapperJar = fs.file(fs.path.join(wrapperDir.path, _gradleWrapper)); - if (!gradleWrapperJar.existsSync()) + if (!gradleWrapperJar.existsSync()) { return false; + } return true; } }
diff --git a/packages/flutter_tools/lib/src/commands/analyze_base.dart b/packages/flutter_tools/lib/src/commands/analyze_base.dart index 00ddbf0..cff8b56 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_base.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_base.dart
@@ -56,14 +56,16 @@ /// Return true if [fileList] contains a path that resides inside the Flutter repository. /// If [fileList] is empty, then return true if the current directory resides inside the Flutter repository. bool inRepo(List<String> fileList) { - if (fileList == null || fileList.isEmpty) + if (fileList == null || fileList.isEmpty) { fileList = <String>[fs.path.current]; + } final String root = fs.path.normalize(fs.path.absolute(Cache.flutterRoot)); final String prefix = root + fs.path.separator; for (String file in fileList) { file = fs.path.normalize(fs.path.absolute(file)); - if (file == root || file.startsWith(prefix)) + if (file == root || file.startsWith(prefix)) { return true; + } } return false; } @@ -87,8 +89,9 @@ for (List<String> targetSources in values.values) { for (String source in targetSources) { assert(fs.path.isAbsolute(source)); - if (fs.path.isWithin(Cache.flutterRoot, source)) + if (fs.path.isWithin(Cache.flutterRoot, source)) { return true; + } } } return false; @@ -103,8 +106,9 @@ bool canonical = false; for (String source in values[target]) { result.writeln(' $source'); - if (source == canonicalSource) + if (source == canonicalSource) { canonical = true; + } } if (canonical) { result.writeln(' (This is the actual package definition, so it is considered the canonical "right answer".)'); @@ -144,8 +148,9 @@ // Ensure that we only add `analyzer` and dependent packages defined in the vended SDK (and referred to with a local // fs.path. directive). Analyzer package versions reached via transitive dependencies (e.g., via `test`) are ignored // since they would produce spurious conflicts. - if (!_vendedSdkPackages.contains(packageName) || packagePath.startsWith('..')) + if (!_vendedSdkPackages.contains(packageName) || packagePath.startsWith('..')) { add(packageName, fs.path.normalize(fs.path.absolute(directory.path, packagePath)), dotPackagesPath); + } } } } @@ -215,8 +220,9 @@ Map<String, String> asPackageMap() { final Map<String, String> result = <String, String>{}; - for (String package in packages.keys) + for (String package in packages.keys) { result[package] = packages[package].target; + } return result; } }
diff --git a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart index a82cdd7..35647d7 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart
@@ -64,19 +64,22 @@ final int exitCode = await server.onExit; final String message = 'Analysis server exited with code $exitCode.'; - if (exitCode != 0) + if (exitCode != 0) { throwToolExit(message, exitCode: exitCode); + } printStatus(message); - if (server.didServerErrorOccur) + if (server.didServerErrorOccur) { throwToolExit('Server error(s) occurred.'); + } } void _handleAnalysisStatus(AnalysisServer server, bool isAnalyzing) { if (isAnalyzing) { analysisStatus?.cancel(); - if (!firstAnalysis) + if (!firstAnalysis) { printStatus('\n'); + } analysisStatus = logger.startProgress('Analyzing $analysisTarget...', timeout: timeoutConfiguration.slowOperation); analyzedPaths.clear(); analysisTimer = Stopwatch()..start(); @@ -112,8 +115,9 @@ for (AnalysisError error in errors) { printStatus(error.toString()); - if (error.code != null) + if (error.code != null) { printTrace('error code: ${error.code}'); + } } dumpErrors(errors.map<String>((AnalysisError error) => error.toLegacyString())); @@ -123,16 +127,17 @@ final int issueDiff = issueCount - lastErrorCount; lastErrorCount = issueCount; - if (firstAnalysis) + if (firstAnalysis) { errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found'; - else if (issueDiff > 0) + } else if (issueDiff > 0) { errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found ($issueDiff new)'; - else if (issueDiff < 0) + } else if (issueDiff < 0) { errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found (${-issueDiff} fixed)'; - else if (issueCount != 0) + } else if (issueCount != 0) { errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found'; - else + } else { errorsMessage = 'no issues found'; + } String dartdocMessage; if (undocumentedMembers == 1) {
diff --git a/packages/flutter_tools/lib/src/commands/analyze_once.dart b/packages/flutter_tools/lib/src/commands/analyze_once.dart index 9f164f0..7f7b381 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_once.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_once.dart
@@ -57,15 +57,18 @@ final PackageDependencyTracker dependencies = PackageDependencyTracker(); dependencies.checkForConflictingDependencies(repoPackages, dependencies); directories.addAll(repoRoots); - if (argResults.wasParsed('current-package') && argResults['current-package']) + if (argResults.wasParsed('current-package') && argResults['current-package']) { directories.add(currentDirectory); + } } else { - if (argResults['current-package']) + if (argResults['current-package']) { directories.add(currentDirectory); + } } - if (directories.isEmpty) + if (directories.isEmpty) { throwToolExit('Nothing to analyze.', exitCode: 0); + } // analyze all final Completer<void> analysisCompleter = Completer<void>(); @@ -118,22 +121,26 @@ final int undocumentedMembers = errors.where((AnalysisError error) { return error.code == 'public_member_api_docs'; }).length; - if (!argResults['dartdocs']) + if (!argResults['dartdocs']) { errors.removeWhere((AnalysisError error) => error.code == 'public_member_api_docs'); + } // emit benchmarks - if (isBenchmarking) + if (isBenchmarking) { writeBenchmark(timer, errors.length, undocumentedMembers); + } // --write dumpErrors(errors.map<String>((AnalysisError error) => error.toLegacyString())); // report errors - if (errors.isNotEmpty && argResults['preamble']) + if (errors.isNotEmpty && argResults['preamble']) { printStatus(''); + } errors.sort(); - for (AnalysisError error in errors) + for (AnalysisError error in errors) { printStatus(error.toString(), hangingIndent: 7); + } final String seconds = (timer.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
diff --git a/packages/flutter_tools/lib/src/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index 404db38..6435f14 100644 --- a/packages/flutter_tools/lib/src/commands/attach.dart +++ b/packages/flutter_tools/lib/src/commands/attach.dart
@@ -109,8 +109,9 @@ final String description = 'Attach to a running application.'; int get debugPort { - if (argResults['debug-port'] == null) + if (argResults['debug-port'] == null) { return null; + } try { return int.parse(argResults['debug-port']); } catch (error) { @@ -137,8 +138,9 @@ @override Future<void> validateCommand() async { await super.validateCommand(); - if (await findTargetDevice() == null) + if (await findTargetDevice() == null) { throwToolExit(null); + } debugPort; if (debugPort == null && debugUri == null && argResults.wasParsed(FlutterCommand.ipv6Flag)) { throwToolExit( @@ -209,8 +211,9 @@ if (device is FuchsiaDevice) { attachLogger = true; final String module = argResults['module']; - if (module == null) + if (module == null) { throwToolExit('\'--module\' is required for attaching to a Fuchsia device'); + } usesIpv6 = device.ipv6; FuchsiaIsolateDiscoveryProtocol isolateDiscoveryProtocol; try {
diff --git a/packages/flutter_tools/lib/src/commands/build_aot.dart b/packages/flutter_tools/lib/src/commands/build_aot.dart index f572442..5f15243 100644 --- a/packages/flutter_tools/lib/src/commands/build_aot.dart +++ b/packages/flutter_tools/lib/src/commands/build_aot.dart
@@ -74,8 +74,9 @@ Future<FlutterCommandResult> runCommand() async { final String targetPlatform = argResults['target-platform']; final TargetPlatform platform = getTargetPlatformForName(targetPlatform); - if (platform == null) + if (platform == null) { throwToolExit('Unknown platform: $targetPlatform'); + } final bool bitcode = argResults['bitcode']; final BuildMode buildMode = getBuildMode(); @@ -121,8 +122,9 @@ // Determine which iOS architectures to build for. final Iterable<DarwinArch> buildArchs = argResults['ios-arch'].map<DarwinArch>(getIOSArchForName); final Map<DarwinArch, String> iosBuilds = <DarwinArch, String>{}; - for (DarwinArch arch in buildArchs) + for (DarwinArch arch in buildArchs) { iosBuilds[arch] = fs.path.join(outputPath, getNameForDarwinArch(arch)); + } // Generate AOT snapshot and compile to arch-specific App.framework. final Map<DarwinArch, Future<int>> exitCodes = <DarwinArch, Future<int>>{}; @@ -186,8 +188,9 @@ } status?.stop(); - if (outputPath == null) + if (outputPath == null) { throwToolExit(null); + } final String builtMessage = 'Built to $outputPath${fs.path.separator}.'; if (argResults['quiet']) {
diff --git a/packages/flutter_tools/lib/src/commands/build_ios.dart b/packages/flutter_tools/lib/src/commands/build_ios.dart index f82dab9..c32e1f3 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios.dart
@@ -59,13 +59,15 @@ final bool forSimulator = argResults['simulator']; defaultBuildMode = forSimulator ? BuildMode.debug : BuildMode.release; - if (getCurrentHostPlatform() != HostPlatform.darwin_x64) + if (getCurrentHostPlatform() != HostPlatform.darwin_x64) { throwToolExit('Building for iOS is only supported on the Mac.'); + } final BuildableIOSApp app = await applicationPackages.getPackageForPlatform(TargetPlatform.ios); - if (app == null) + if (app == null) { throwToolExit('Application not configured for iOS'); + } final bool shouldCodesign = argResults['codesign']; @@ -74,8 +76,9 @@ 'have to manually codesign before deploying to device.'); } final BuildInfo buildInfo = getBuildInfo(); - if (forSimulator && !buildInfo.supportsSimulator) + if (forSimulator && !buildInfo.supportsSimulator) { throwToolExit('${toTitleCase(buildInfo.friendlyModeName)} mode is not supported for simulators.'); + } final String logTarget = forSimulator ? 'simulator' : 'device'; @@ -94,8 +97,9 @@ throwToolExit('Encountered error while building for $logTarget.'); } - if (result.output != null) + if (result.output != null) { printStatus('Built ${result.output}.'); + } return null; }
diff --git a/packages/flutter_tools/lib/src/commands/channel.dart b/packages/flutter_tools/lib/src/commands/channel.dart index bef80ac..e52174e 100644 --- a/packages/flutter_tools/lib/src/commands/channel.dart +++ b/packages/flutter_tools/lib/src/commands/channel.dart
@@ -65,21 +65,25 @@ <String>['git', 'branch', '-r'], workingDirectory: Cache.flutterRoot, mapFunction: (String line) { - if (verbose) + if (verbose) { rawOutput.add(line); + } final List<String> split = line.split('/'); - if (split.length < 2) + if (split.length < 2) { return null; + } final String branchName = split[1]; if (seenChannels.contains(branchName)) { return null; } seenChannels.add(branchName); - if (branchName == currentBranch) + if (branchName == currentBranch) { return '* $branchName'; + } if (!branchName.startsWith('HEAD ') && - (showAll || FlutterVersion.officialChannels.contains(branchName))) + (showAll || FlutterVersion.officialChannels.contains(branchName))) { return ' $branchName'; + } return null; }, );
diff --git a/packages/flutter_tools/lib/src/commands/config.dart b/packages/flutter_tools/lib/src/commands/config.dart index 0da5400..c113603 100644 --- a/packages/flutter_tools/lib/src/commands/config.dart +++ b/packages/flutter_tools/lib/src/commands/config.dart
@@ -86,8 +86,9 @@ } return ' $key: ${config.getValue(key)} $configFooter'; }).join('\n'); - if (values.isEmpty) + if (values.isEmpty) { values = ' No settings have been configured.'; + } return '\nSettings:\n$values\n\n' 'Analytics reporting is currently ${flutterUsage.enabled ? 'enabled' : 'disabled'}.'; @@ -119,14 +120,17 @@ printStatus('Analytics reporting ${value ? 'enabled' : 'disabled'}.'); } - if (argResults.wasParsed('android-sdk')) + if (argResults.wasParsed('android-sdk')) { _updateConfig('android-sdk', argResults['android-sdk']); + } - if (argResults.wasParsed('android-studio-dir')) + if (argResults.wasParsed('android-studio-dir')) { _updateConfig('android-studio-dir', argResults['android-studio-dir']); + } - if (argResults.wasParsed('clear-ios-signing-cert')) + if (argResults.wasParsed('clear-ios-signing-cert')) { _updateConfig('ios-signing-cert', ''); + } if (argResults.wasParsed('build-dir')) { final String buildDir = argResults['build-dir']; @@ -147,8 +151,9 @@ } } - if (argResults.arguments.isEmpty) + if (argResults.arguments.isEmpty) { printStatus(usage); + } return null; }
diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 86ede6a..89098fc 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart
@@ -180,11 +180,13 @@ // many of the files could be missing, and we can't really tell definitively. _ProjectType _determineTemplateType(Directory projectDir) { yaml.YamlMap loadMetadata(Directory projectDir) { - if (!projectDir.existsSync()) + if (!projectDir.existsSync()) { return null; + } final File metadataFile = fs.file(fs.path.join(projectDir.absolute.path, '.metadata')); - if (!metadataFile.existsSync()) + if (!metadataFile.existsSync()) { return null; + } return yaml.loadYaml(metadataFile.readAsStringSync()); } @@ -293,8 +295,9 @@ return null; } - if (argResults.rest.isEmpty) + if (argResults.rest.isEmpty) { throwToolExit('No option specified for the output directory.\n$usage', exitCode: 2); + } if (argResults.rest.length > 1) { String message = 'Multiple output directories specified.'; @@ -307,9 +310,10 @@ throwToolExit(message, exitCode: 2); } - if (Cache.flutterRoot == null) + if (Cache.flutterRoot == null) { throwToolExit('Neither the --flutter-root command line flag nor the FLUTTER_ROOT environment ' 'variable was specified. Unable to find package:flutter.', exitCode: 2); + } await Cache.instance.updateAll(<DevelopmentArtifact>{ DevelopmentArtifact.universal }); @@ -317,12 +321,14 @@ final String flutterPackagesDirectory = fs.path.join(flutterRoot, 'packages'); final String flutterPackagePath = fs.path.join(flutterPackagesDirectory, 'flutter'); - if (!fs.isFileSync(fs.path.join(flutterPackagePath, 'pubspec.yaml'))) + if (!fs.isFileSync(fs.path.join(flutterPackagePath, 'pubspec.yaml'))) { throwToolExit('Unable to find package:flutter in $flutterPackagePath', exitCode: 2); + } final String flutterDriverPackagePath = fs.path.join(flutterRoot, 'packages', 'flutter_driver'); - if (!fs.isFileSync(fs.path.join(flutterDriverPackagePath, 'pubspec.yaml'))) + if (!fs.isFileSync(fs.path.join(flutterDriverPackagePath, 'pubspec.yaml'))) { throwToolExit('Unable to find package:flutter_driver in $flutterDriverPackagePath', exitCode: 2); + } final Directory projectDir = fs.directory(argResults.rest.first); final String projectDirPath = fs.path.normalize(projectDir.absolute.path); @@ -358,13 +364,15 @@ } String error = _validateProjectDir(projectDirPath, flutterRoot: flutterRoot, overwrite: argResults['overwrite']); - if (error != null) + if (error != null) { throwToolExit(error); + } final String projectName = argResults['project-name'] ?? fs.path.basename(projectDirPath); error = _validateProjectName(projectName); - if (error != null) + if (error != null) { throwToolExit(error); + } final Map<String, dynamic> templateContext = _templateContext( organization: organization, @@ -751,8 +759,9 @@ '${overwrite ? ' Refusing to overwrite a file with a directory.' : ''}'; } - if (overwrite) + if (overwrite) { return null; + } final FileSystemEntityType type = fs.typeSync(dirPath);
diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index 4dc734c..afc49ce 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart
@@ -62,8 +62,9 @@ daemonCommand: this, notifyingLogger: notifyingLogger); final int code = await daemon.onExit; - if (code != 0) + if (code != 0) { throwToolExit('Daemon exited with non-zero exit code: $code', exitCode: code); + } }, overrides: <Type, Generator>{ Logger: () => notifyingLogger, @@ -95,8 +96,9 @@ _commandSubscription = commandStream.listen( _handleRequest, onDone: () { - if (!_onExitCompleter.isCompleted) + if (!_onExitCompleter.isCompleted) { _onExitCompleter.complete(0); + } }, ); } @@ -134,13 +136,15 @@ try { final String method = request['method']; - if (!method.contains('.')) + if (!method.contains('.')) { throw 'method not understood: $method'; + } final String prefix = method.substring(0, method.indexOf('.')); final String name = method.substring(method.indexOf('.') + 1); - if (_domainMap[prefix] == null) + if (_domainMap[prefix] == null) { throw 'no domain for method: $method'; + } _domainMap[prefix].handleCommand(name, id, request['params'] ?? const <String, dynamic>{}); } catch (error, trace) { @@ -156,13 +160,15 @@ void shutdown({ dynamic error }) { _commandSubscription?.cancel(); - for (Domain domain in _domainMap.values) + for (Domain domain in _domainMap.values) { domain.dispose(); + } if (!_onExitCompleter.isCompleted) { - if (error == null) + if (error == null) { _onExitCompleter.complete(0); - else + } else { _onExitCompleter.completeError(error); + } } } } @@ -185,8 +191,9 @@ void handleCommand(String command, dynamic id, Map<String, dynamic> args) { Future<dynamic>.sync(() { - if (_handlers.containsKey(command)) + if (_handlers.containsKey(command)) { return _handlers[command](args); + } throw 'command not understood: $name.$command'; }).then<dynamic>((dynamic result) { if (result == null) { @@ -205,37 +212,44 @@ void sendEvent(String name, [ dynamic args ]) { final Map<String, dynamic> map = <String, dynamic>{'event': name}; - if (args != null) + if (args != null) { map['params'] = _toJsonable(args); + } _send(map); } void _send(Map<String, dynamic> map) => daemon._send(map); String _getStringArg(Map<String, dynamic> args, String name, { bool required = false }) { - if (required && !args.containsKey(name)) + if (required && !args.containsKey(name)) { throw '$name is required'; + } final dynamic val = args[name]; - if (val != null && val is! String) + if (val != null && val is! String) { throw '$name is not a String'; + } return val; } bool _getBoolArg(Map<String, dynamic> args, String name, { bool required = false }) { - if (required && !args.containsKey(name)) + if (required && !args.containsKey(name)) { throw '$name is required'; + } final dynamic val = args[name]; - if (val != null && val is! bool) + if (val != null && val is! bool) { throw '$name is not a bool'; + } return val; } int _getIntArg(Map<String, dynamic> args, String name, { bool required = false }) { - if (required && !args.containsKey(name)) + if (required && !args.containsKey(name)) { throw '$name is required'; + } final dynamic val = args[name]; - if (val != null && val is! int) + if (val != null && val is! int) { throw '$name is not an int'; + } return val; } @@ -267,8 +281,9 @@ print(message.message); } else if (message.level == 'error') { stderr.writeln(message.message); - if (message.stackTrace != null) + if (message.stackTrace != null) { stderr.writeln(message.stackTrace.toString().trimRight()); + } } } else { if (message.stackTrace != null) { @@ -495,8 +510,9 @@ 'port': info.httpUri?.port ?? info.wsUri.port, 'wsUri': info.wsUri.toString(), }; - if (info.baseUri != null) + if (info.baseUri != null) { params['baseUri'] = info.baseUri; + } _sendAppEvent(app, 'debugPort', params); }, )); @@ -540,11 +556,13 @@ final String restartReason = _getStringArg(args, 'reason'); final AppInstance app = _getApp(appId); - if (app == null) + if (app == null) { throw "app '$appId' not found"; + } - if (_inProgressHotReload != null) + if (_inProgressHotReload != null) { throw 'hot restart already in progress'; + } _inProgressHotReload = app._runInZone<OperationResult>(this, () { return app.restart(fullRestart: fullRestart, pauseAfterRestart: pauseAfterRestart, reason: restartReason); @@ -569,16 +587,19 @@ final Map<String, dynamic> params = args['params'] == null ? <String, dynamic>{} : castStringKeyedMap(args['params']); final AppInstance app = _getApp(appId); - if (app == null) + if (app == null) { throw "app '$appId' not found"; + } final Map<String, dynamic> result = await app.runner .invokeFlutterExtensionRpcRawOnFirstIsolate(methodName, params: params); - if (result == null) + if (result == null) { throw 'method not available: $methodName'; + } - if (result.containsKey('error')) + if (result.containsKey('error')) { throw result['error']; + } return result; } @@ -587,8 +608,9 @@ final String appId = _getStringArg(args, 'appId', required: true); final AppInstance app = _getApp(appId); - if (app == null) + if (app == null) { throw "app '$appId' not found"; + } return app.stop().then<bool>( (void value) => true, @@ -605,8 +627,9 @@ final String appId = _getStringArg(args, 'appId', required: true); final AppInstance app = _getApp(appId); - if (app == null) + if (app == null) { throw "app '$appId' not found"; + } return app.detach().then<bool>( (void value) => true, @@ -651,8 +674,9 @@ } void addDeviceDiscoverer(DeviceDiscovery discoverer) { - if (!discoverer.supportsPlatform) + if (!discoverer.supportsPlatform) { return; + } _discoverers.add(discoverer); if (discoverer is PollingDeviceDiscovery) { @@ -694,15 +718,17 @@ /// Enable device events. Future<void> enable(Map<String, dynamic> args) { - for (PollingDeviceDiscovery discoverer in _discoverers) + for (PollingDeviceDiscovery discoverer in _discoverers) { discoverer.startPolling(); + } return Future<void>.value(); } /// Disable device events. Future<void> disable(Map<String, dynamic> args) { - for (PollingDeviceDiscovery discoverer in _discoverers) + for (PollingDeviceDiscovery discoverer in _discoverers) { discoverer.stopPolling(); + } return Future<void>.value(); } @@ -713,8 +739,9 @@ int hostPort = _getIntArg(args, 'hostPort'); final Device device = await daemon.deviceDomain._getDevice(deviceId); - if (device == null) + if (device == null) { throw "device '$deviceId' not found"; + } hostPort = await device.portForwarder.forward(devicePort, hostPort: hostPort); @@ -728,24 +755,27 @@ final int hostPort = _getIntArg(args, 'hostPort', required: true); final Device device = await daemon.deviceDomain._getDevice(deviceId); - if (device == null) + if (device == null) { throw "device '$deviceId' not found"; + } return device.portForwarder.unforward(ForwardedPort(hostPort, devicePort)); } @override void dispose() { - for (PollingDeviceDiscovery discoverer in _discoverers) + for (PollingDeviceDiscovery discoverer in _discoverers) { discoverer.dispose(); + } } /// Return the device matching the deviceId field in the args. Future<Device> _getDevice(String deviceId) async { for (PollingDeviceDiscovery discoverer in _discoverers) { final Device device = (await discoverer.devices).firstWhere((Device device) => device.id == deviceId, orElse: () => null); - if (device != null) + if (device != null) { return device; + } } return null; } @@ -769,8 +799,9 @@ } dynamic _toEncodable(dynamic object) { - if (object is OperationResult) + if (object is OperationResult) { return _operationResultToMap(object); + } return object; } @@ -804,12 +835,15 @@ } dynamic _toJsonable(dynamic obj) { - if (obj is String || obj is int || obj is bool || obj is Map<dynamic, dynamic> || obj is List<dynamic> || obj == null) + if (obj is String || obj is int || obj is bool || obj is Map<dynamic, dynamic> || obj is List<dynamic> || obj == null) { return obj; - if (obj is OperationResult) + } + if (obj is OperationResult) { return obj; - if (obj is ToolExit) + } + if (obj is ToolExit) { return obj.message; + } return '$obj'; } @@ -1061,17 +1095,19 @@ } void _sendLogEvent(Map<String, dynamic> event) { - if (domain == null) + if (domain == null) { printStatus('event sent after app closed: $event'); - else + } else { domain._sendAppEvent(app, 'log', event); + } } void _sendProgressEvent(Map<String, dynamic> event) { - if (domain == null) + if (domain == null) { printStatus('event sent after app closed: $event'); - else + } else { domain._sendAppEvent(app, 'progress', event); + } } }
diff --git a/packages/flutter_tools/lib/src/commands/drive.dart b/packages/flutter_tools/lib/src/commands/drive.dart index e63377e..9bee5e8 100644 --- a/packages/flutter_tools/lib/src/commands/drive.dart +++ b/packages/flutter_tools/lib/src/commands/drive.dart
@@ -94,15 +94,18 @@ @override Future<FlutterCommandResult> runCommand() async { final String testFile = _getTestFile(); - if (testFile == null) + if (testFile == null) { throwToolExit(null); + } _device = await findTargetDevice(); - if (device == null) + if (device == null) { throwToolExit(null); + } - if (await fs.type(testFile) != FileSystemEntityType.file) + if (await fs.type(testFile) != FileSystemEntityType.file) { throwToolExit('Test file not found: $testFile'); + } String observatoryUri; if (argResults['use-existing-app'] == null) { @@ -119,8 +122,9 @@ } final LaunchResult result = await appStarter(this); - if (result == null) + if (result == null) { throwToolExit('Application failed to start. Will not run test. Quitting.', exitCode: 1); + } observatoryUri = result.observatoryUri.toString(); } else { printStatus('Will connect to already running application instance.'); @@ -132,8 +136,9 @@ try { await testRunner(<String>[testFile], observatoryUri); } catch (error, stackTrace) { - if (error is ToolExit) + if (error is ToolExit) { rethrow; + } throwToolExit('CAUGHT EXCEPTION: $error\n$stackTrace'); } finally { if (argResults['keep-app-running'] ?? (argResults['use-existing-app'] != null)) { @@ -148,8 +153,9 @@ } String _getTestFile() { - if (argResults['driver'] != null) + if (argResults['driver'] != null) { return argResults['driver']; + } // If the --driver argument wasn't provided, then derive the value from // the target file. @@ -240,14 +246,16 @@ if (command.shouldBuild) { printTrace('Installing application package.'); - if (await command.device.isAppInstalled(package)) + if (await command.device.isAppInstalled(package)) { await command.device.uninstallApp(package); + } await command.device.installApp(package); } final Map<String, dynamic> platformArgs = <String, dynamic>{}; - if (command.traceStartup) + if (command.traceStartup) { platformArgs['trace-startup'] = command.traceStartup; + } printTrace('Starting application.'); @@ -302,8 +310,9 @@ ], environment: <String, String>{'VM_SERVICE_URL': observatoryUri}, ); - if (result != 0) + if (result != 0) { throwToolExit('Driver tests failed: $result', exitCode: result); + } }
diff --git a/packages/flutter_tools/lib/src/commands/install.dart b/packages/flutter_tools/lib/src/commands/install.dart index 5e0d43c..93ed7d3 100644 --- a/packages/flutter_tools/lib/src/commands/install.dart +++ b/packages/flutter_tools/lib/src/commands/install.dart
@@ -28,8 +28,9 @@ Future<void> validateCommand() async { await super.validateCommand(); device = await findTargetDevice(); - if (device == null) + if (device == null) { throwToolExit('No target device found'); + } } @override @@ -40,21 +41,24 @@ printStatus('Installing $package to $device...'); - if (!await installApp(device, package)) + if (!await installApp(device, package)) { throwToolExit('Install failed'); + } return null; } } Future<bool> installApp(Device device, ApplicationPackage package, { bool uninstall = true }) async { - if (package == null) + if (package == null) { return false; + } if (uninstall && await device.isAppInstalled(package)) { printStatus('Uninstalling old version...'); - if (!await device.uninstallApp(package)) + if (!await device.uninstallApp(package)) { printError('Warning: uninstalling old version failed'); + } } return device.installApp(package);
diff --git a/packages/flutter_tools/lib/src/commands/logs.dart b/packages/flutter_tools/lib/src/commands/logs.dart index 7eaf9cf..503147c 100644 --- a/packages/flutter_tools/lib/src/commands/logs.dart +++ b/packages/flutter_tools/lib/src/commands/logs.dart
@@ -42,8 +42,9 @@ @override Future<FlutterCommandResult> runCommand() async { - if (argResults['clear']) + if (argResults['clear']) { device.clearLogs(); + } final DeviceLogReader logReader = device.getLogReader(); @@ -78,8 +79,9 @@ // Wait for the log reader to be finished. final int result = await exitCompleter.future; await subscription.cancel(); - if (result != 0) + if (result != 0) { throwToolExit('Error listening to $logReader logs.'); + } return null; }
diff --git a/packages/flutter_tools/lib/src/commands/make_host_app_editable.dart b/packages/flutter_tools/lib/src/commands/make_host_app_editable.dart index e217953..668c47f 100644 --- a/packages/flutter_tools/lib/src/commands/make_host_app_editable.dart +++ b/packages/flutter_tools/lib/src/commands/make_host_app_editable.dart
@@ -37,8 +37,9 @@ Future<void> validateCommand() async { await super.validateCommand(); _project = FlutterProject.current(); - if (!_project.isModule) + if (!_project.isModule) { throw ToolExit("Only projects created using 'flutter create -t module' can have their host apps made editable."); + } } @override
diff --git a/packages/flutter_tools/lib/src/commands/packages.dart b/packages/flutter_tools/lib/src/commands/packages.dart index cbcdd61..fdfe70e 100644 --- a/packages/flutter_tools/lib/src/commands/packages.dart +++ b/packages/flutter_tools/lib/src/commands/packages.dart
@@ -112,8 +112,9 @@ @override Future<FlutterCommandResult> runCommand() async { - if (argResults.rest.length > 1) + if (argResults.rest.length > 1) { throwToolExit('Too many arguments.\n$usage'); + } final String workingDirectory = argResults.rest.length == 1 ? argResults.rest[0] : null; final String target = findProjectRoot(workingDirectory);
diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 4bcb839..f93b4da 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart
@@ -195,12 +195,13 @@ Future<String> get usagePath async { final String command = await super.usagePath; - if (devices == null) + if (devices == null) { return command; - else if (devices.length > 1) + } + if (devices.length > 1) { return '$command/all'; - else - return '$command/${getNameForTargetPlatform(await devices[0].targetPlatform)}'; + } + return '$command/${getNameForTargetPlatform(await devices[0].targetPlatform)}'; } @override @@ -246,8 +247,9 @@ @override bool get shouldRunPub { // If we are running with a prebuilt application, do not run pub. - if (runningWithPrebuiltApplication) + if (runningWithPrebuiltApplication) { return false; + } return super.shouldRunPub; } @@ -268,13 +270,16 @@ Future<void> validateCommand() async { // When running with a prebuilt application, no command validation is // necessary. - if (!runningWithPrebuiltApplication) + if (!runningWithPrebuiltApplication) { await super.validateCommand(); + } devices = await findAllTargetDevices(); - if (devices == null) + if (devices == null) { throwToolExit(null); - if (deviceManager.hasSpecifiedAllDevices && runningWithPrebuiltApplication) + } + if (deviceManager.hasSpecifiedAllDevices && runningWithPrebuiltApplication) { throwToolExit('Using -d all with --use-application-binary is not supported'); + } } DebuggingOptions _createDebuggingOptions() { @@ -316,8 +321,9 @@ writePidFile(argResults['pid-file']); if (argResults['machine']) { - if (devices.length > 1) + if (devices.length > 1) { throwToolExit('--machine does not support -d all.'); + } final Daemon daemon = Daemon(stdinCommandStream, stdoutCommandResponse, notifyingLogger: NotifyingLogger(), logToStdout: true); AppInstance app; @@ -340,8 +346,9 @@ } final DateTime appStartedTime = systemClock.now(); final int result = await app.runner.waitForAppToFinish(); - if (result != 0) + if (result != 0) { throwToolExit(null, exitCode: result); + } return FlutterCommandResult( ExitStatus.success, timingLabelParts: <String>['daemon'], @@ -380,8 +387,9 @@ if (hotMode) { for (Device device in devices) { - if (!device.supportsHotReload) + if (!device.supportsHotReload) { throwToolExit('Hot reload is not supported by ${device.name}. Run with --no-hot.'); + } } }
diff --git a/packages/flutter_tools/lib/src/commands/screenshot.dart b/packages/flutter_tools/lib/src/commands/screenshot.dart index bda6f33..b175456 100644 --- a/packages/flutter_tools/lib/src/commands/screenshot.dart +++ b/packages/flutter_tools/lib/src/commands/screenshot.dart
@@ -81,8 +81,9 @@ @override Future<FlutterCommandResult> runCommand() async { File outputFile; - if (argResults.wasParsed(_kOut)) + if (argResults.wasParsed(_kOut)) { outputFile = fs.file(argResults[_kOut]); + } switch (argResults[_kType]) { case _kDeviceType:
diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index e6319b5..1041436 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart
@@ -164,8 +164,9 @@ // We don't scan the entire package, only the test/ subdirectory, so that // files with names like like "hit_test.dart" don't get run. workDir = fs.directory('test'); - if (!workDir.existsSync()) + if (!workDir.existsSync()) { throwToolExit('Test directory "${workDir.path}" not found.'); + } files = _findTests(workDir).toList(); if (files.isEmpty) { throwToolExit( @@ -242,13 +243,18 @@ ); if (collector != null) { - if (!await collector.collectCoverageData( - argResults['coverage-path'], mergeCoverageData: argResults['merge-coverage'])) + final bool collectionResult = await collector.collectCoverageData( + argResults['coverage-path'], + mergeCoverageData: argResults['merge-coverage'], + ); + if (!collectionResult) { throwToolExit(null); + } } - if (result != 0) + if (result != 0) { throwToolExit(null); + } return const FlutterCommandResult(ExitStatus.success); }
diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart index a441bc4..93cd33d 100644 --- a/packages/flutter_tools/lib/src/commands/update_packages.dart +++ b/packages/flutter_tools/lib/src/commands/update_packages.dart
@@ -160,8 +160,9 @@ // all dependencies in the pubspec sorted lexically. final Map<String, String> checksumDependencies = <String, String>{}; for (PubspecLine data in pubspec.inputData) { - if (data is PubspecDependency && data.kind == DependencyKind.normal) + if (data is PubspecDependency && data.kind == DependencyKind.normal) { checksumDependencies[data.name] = data.version; + } } final String checksum = _computeChecksum(checksumDependencies.keys, (String name) => checksumDependencies[name]); if (checksum != pubspec.checksum.value) { @@ -235,8 +236,9 @@ // already implicitly pin since we pull down one version of the // Flutter and Dart SDKs, so we track which those are here so that we // can omit them from our list of pinned dependencies later. - if (dependency.kind != DependencyKind.normal) + if (dependency.kind != DependencyKind.normal) { specialDependencies.add(dependency.name); + } } } @@ -308,8 +310,9 @@ // to specific versions because they are explicitly pinned by their // constraints. Here we list the names we earlier established we didn't // need to pin because they come from the Dart or Flutter SDKs. - for (PubspecYaml pubspec in pubspecs) + for (PubspecYaml pubspec in pubspecs) { pubspec.apply(tree, specialDependencies); + } // Now that the pubspec.yamls are updated, we run "pub get" on each one so // that the various packages are ready to use. This is what "flutter @@ -338,10 +341,12 @@ @required String to, @required PubDependencyTree tree, }) { - if (!tree.contains(from)) + if (!tree.contains(from)) { throwToolExit('Package $from not found in the dependency tree.'); - if (!tree.contains(to)) + } + if (!tree.contains(to)) { throwToolExit('Package $to not found in the dependency tree.'); + } final Queue<_DependencyLink> traversalQueue = Queue<_DependencyLink>(); final Set<String> visited = <String>{}; @@ -350,10 +355,12 @@ traversalQueue.addFirst(_DependencyLink(from: null, to: from)); while (traversalQueue.isNotEmpty) { final _DependencyLink link = traversalQueue.removeLast(); - if (link.to == to) + if (link.to == to) { paths.add(link); - if (link.from != null) + } + if (link.from != null) { visited.add(link.from.to); + } for (String dependency in tree._dependencyTree[link.to]) { if (!visited.contains(dependency)) { traversalQueue.addFirst(_DependencyLink(from: link, to: dependency)); @@ -366,8 +373,9 @@ while (path != null) { buf.write('${path.to}'); path = path.from; - if (path != null) + if (path != null) { buf.write(' <- '); + } } printStatus(buf.toString(), wrap: false); } @@ -488,15 +496,17 @@ if (header != null) { // It is! section = header.section; // The parser determined what kind of section it is. if (section == Section.header) { - if (header.name == 'name') + if (header.name == 'name') { packageName = header.value; - else if (header.name == 'version') + } else if (header.name == 'version') { packageVersion = header.value; + } } else if (section == Section.dependencies) { // If we're entering the "dependencies" section, we want to make sure that // it's the first section (of those we care about) that we've seen so far. - if (seenMain) + if (seenMain) { throw 'Two dependencies sections found in $filename. There should only be one.'; + } if (seenDev) { throw 'The dependencies section was after the dev_dependencies section in $filename. ' 'To enable one-pass processing, the dependencies section must come before the ' @@ -506,8 +516,9 @@ } else if (section == Section.devDependencies) { // Similarly, if we're entering the dev_dependencies section, we should verify // that we've not seen one already. - if (seenDev) + if (seenDev) { throw 'Two dev_dependencies sections found in $filename. There should only be one.'; + } seenDev = true; } result.add(header); @@ -546,8 +557,9 @@ // // First, make sure it's a unique dependency. Listing dependencies // twice doesn't make sense. - if (masterDependencies.containsKey(dependency.name)) + if (masterDependencies.containsKey(dependency.name)) { throw '$filename contains two dependencies on ${dependency.name}.'; + } masterDependencies[dependency.name] = dependency; } else { // If we _are_ in the overrides section, then go tell the version @@ -608,16 +620,18 @@ // magic comment flagging them as auto-generated transitive dependencies // that we added in a previous run. for (PubspecLine data in inputData) { - if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive && !data.isDevDependency) + if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive && !data.isDevDependency) { yield data; + } } } /// This returns all regular dependencies and all dev dependencies. Iterable<PubspecDependency> get allDependencies sync* { for (PubspecLine data in inputData) { - if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive) + if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive) { yield data; + } } } @@ -650,10 +664,12 @@ // If we're leaving one of the sections in which we can list transitive // dependencies, then remember this as the current last known valid // place to insert our transitive dependencies. - if (section == Section.dependencies) + if (section == Section.dependencies) { endOfDirectDependencies = output.length; - if (section == Section.devDependencies) + } + if (section == Section.devDependencies) { endOfDevDependencies = output.length; + } section = data.section; // track which section we're now in. output.add(data.line); // insert the header into the output } else if (data is PubspecDependency) { @@ -682,8 +698,9 @@ // unmodified. If there was an additional line (e.g. an "sdk: // flutter" line) then we output that too. output.add(data.line); - if (data.lockLine != null) + if (data.lockLine != null) { output.add(data.lockLine); + } } // Remember that we've dealt with this dependency so we don't // mention it again when doing the transitive dependencies. @@ -705,8 +722,9 @@ default: // In other sections, pass everything through in its original form. output.add(data.line); - if (data.lockLine != null) + if (data.lockLine != null) { output.add(data.lockLine); + } break; } } else { @@ -741,20 +759,24 @@ // Create a new set to hold the list of packages we've already processed, so // that we don't redundantly process them multiple times. final Set<String> done = <String>{}; - for (String package in directDependencies) + for (String package in directDependencies) { transitiveDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied)); - for (String package in devDependencies) + } + for (String package in devDependencies) { transitiveDevDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied)); + } // Sort each dependency block lexically so that we don't get noisy diffs when upgrading. final List<String> transitiveDependenciesAsList = transitiveDependencies.toList()..sort(); final List<String> transitiveDevDependenciesAsList = transitiveDevDependencies.toList()..sort(); // Add a line for each transitive dependency and transitive dev dependency using our magic string to recognize them later. - for (String package in transitiveDependenciesAsList) + for (String package in transitiveDependenciesAsList) { transitiveDependencyOutput.add(' $package: ${versions.versionFor(package)} $kTransitiveMagicString'); - for (String package in transitiveDevDependenciesAsList) + } + for (String package in transitiveDevDependenciesAsList) { transitiveDevDependencyOutput.add(' $package: ${versions.versionFor(package)} $kTransitiveMagicString'); + } // Build a sorted list of all dependencies for the checksum. final Set<String> checksumDependencies = <String>{ @@ -785,8 +807,9 @@ ..add('$kDependencyChecksum$checksumString'); // Remove trailing lines. - while (output.last.isEmpty) + while (output.last.isEmpty) { output.removeLast(); + } // Output the result to the pubspec.yaml file, skipping leading and // duplicate blank lines and removing trailing spaces. @@ -795,8 +818,9 @@ for (String line in output) { line = line.trimRight(); if (line == '') { - if (!hadBlankLine) + if (!hadBlankLine) { contents.writeln(''); + } hadBlankLine = true; } else { contents.writeln(line); @@ -833,8 +857,9 @@ /// be found on this line. This is a value that [_computeChecksum] cannot return. static PubspecChecksum parse(String line) { final List<String> tokens = line.split(kDependencyChecksum); - if (tokens.length != 2) + if (tokens.length != 2) { return PubspecChecksum(null, line); + } return PubspecChecksum(tokens.last.trim(), line); } } @@ -877,11 +902,13 @@ // * has contents before the colon // We also try to recognize which of the kinds of Sections it is // by comparing those contents against known strings. - if (line.startsWith(' ')) + if (line.startsWith(' ')) { return null; + } final String strippedLine = _stripComments(line); - if (!strippedLine.contains(':') || strippedLine.length <= 1) + if (!strippedLine.contains(':') || strippedLine.length <= 1) { return null; + } final List<String> parts = strippedLine.split(':'); final String sectionName = parts.first; final String value = parts.last.trim(); @@ -906,8 +933,9 @@ /// first "#". static String _stripComments(String line) { final int hashIndex = line.indexOf('#'); - if (hashIndex < 0) + if (hashIndex < 0) { return line.trimRight(); + } return line.substring(0, hashIndex).trimRight(); } } @@ -943,14 +971,17 @@ // // We remember the trailing comment, if any, so that we can reconstruct the // line later. We forget the specified version range, if any. - if (line.length < 4 || line.startsWith(' ') || !line.startsWith(' ')) + if (line.length < 4 || line.startsWith(' ') || !line.startsWith(' ')) { return null; + } final int colonIndex = line.indexOf(':'); final int hashIndex = line.indexOf('#'); - if (colonIndex < 3) // two spaces at 0 and 1, a character at 2 + if (colonIndex < 3) { // two spaces at 0 and 1, a character at 2 return null; - if (hashIndex >= 0 && hashIndex < colonIndex) + } + if (hashIndex >= 0 && hashIndex < colonIndex) { return null; + } final String package = line.substring(2, colonIndex).trimRight(); assert(package.isNotEmpty); assert(line.startsWith(' $package')); @@ -1012,13 +1043,15 @@ /// - Using a "path" dependency that points somewhere in the Flutter /// repository other than the "bin" directory. bool get pointsToSdk { - if (_kind == DependencyKind.sdk) + if (_kind == DependencyKind.sdk) { return true; + } if (_kind == DependencyKind.path && !fs.path.isWithin(fs.path.join(Cache.flutterRoot, 'bin'), _lockTarget) && - fs.path.isWithin(Cache.flutterRoot, _lockTarget)) + fs.path.isWithin(Cache.flutterRoot, _lockTarget)) { return true; + } return false; } @@ -1072,8 +1105,9 @@ assert(kind != DependencyKind.unknown); break; case DependencyKind.normal: - if (!_kManuallyPinnedDependencies.containsKey(name)) + if (!_kManuallyPinnedDependencies.containsKey(name)) { dependencies.writeln(' $name: any'); + } break; case DependencyKind.path: if (_lockIsOverride) { @@ -1129,9 +1163,11 @@ printStatus(' - $package: $version'); } } - for (PubspecDependency dependency in dependencies) - if (!dependency.pointsToSdk) + for (PubspecDependency dependency in dependencies) { + if (!dependency.pointsToSdk) { dependency.describeForFakePubspec(result, overrides); + } + } result.write(overrides.toString()); return result.toString(); } @@ -1178,8 +1214,9 @@ if (message.startsWith('- ')) { final int space2 = message.indexOf(' ', 2); int space3 = message.indexOf(' ', space2 + 1); - if (space3 < 0) + if (space3 < 0) { space3 = message.length; + } final String package = message.substring(2, space2); if (!contains(package)) { // Some packages get listed in the dependency overrides section too. @@ -1222,8 +1259,9 @@ } for (String dependency in _dependencyTree[package]) { if (!seen.contains(dependency)) { - if (!exclude.contains(dependency)) + if (!exclude.contains(dependency)) { yield dependency; + } seen.add(dependency); yield* getTransitiveDependenciesFor(dependency, seen: seen, exclude: exclude); } @@ -1245,8 +1283,9 @@ for (String name in sortedNames) { final String version = getVersion(name); assert(version != ''); - if (version == null) + if (version == null) { continue; + } final String value = '$name: $version'; // Each code unit is 16 bits. for (int codeUnit in value.codeUnits) {
diff --git a/packages/flutter_tools/lib/src/compile.dart b/packages/flutter_tools/lib/src/compile.dart index 3985501..3b5258b 100644 --- a/packages/flutter_tools/lib/src/compile.dart +++ b/packages/flutter_tools/lib/src/compile.dart
@@ -278,10 +278,12 @@ '--strong', '--target=$targetModel', ]; - if (trackWidgetCreation) + if (trackWidgetCreation) { command.add('--track-widget-creation'); - if (!linkPlatformKernelIn) + } + if (!linkPlatformKernelIn) { command.add('--no-link-platform'); + } if (aot) { command.add('--aot'); command.add('--tfa'); @@ -319,8 +321,9 @@ command.addAll(<String>[ '--platform', platformDill]); } - if (extraFrontEndOptions != null) + if (extraFrontEndOptions != null) { command.addAll(extraFrontEndOptions); + } command.add(mainUri?.toString() ?? mainPath); @@ -440,8 +443,9 @@ _unsafePackageSerialization = unsafePackageSerialization, _experimentalFlags = experimentalFlags { // This is a URI, not a file path, so the forward slash is correct even on Windows. - if (!_sdkRoot.endsWith('/')) + if (!_sdkRoot.endsWith('/')) { _sdkRoot = '$_sdkRoot/'; + } } final bool _trackWidgetCreation; @@ -646,8 +650,9 @@ // 'compile-expression' should be invoked after compiler has been started, // program was compiled. - if (_server == null) + if (_server == null) { return null; + } final String inputKey = Uuid().generateV4(); _server.stdin.writeln('compile-expression $inputKey'); @@ -723,8 +728,9 @@ String _doMapFilename(String filename, PackageUriMapper packageUriMapper) { if (packageUriMapper != null) { final Uri packageUri = packageUriMapper.map(filename); - if (packageUri != null) + if (packageUri != null) { return packageUri.toString(); + } } if (_fileSystemRoots != null) {
diff --git a/packages/flutter_tools/lib/src/dart/analysis.dart b/packages/flutter_tools/lib/src/dart/analysis.dart index 8fd62fd..b5eae82 100644 --- a/packages/flutter_tools/lib/src/dart/analysis.dart +++ b/packages/flutter_tools/lib/src/dart/analysis.dart
@@ -91,12 +91,13 @@ final dynamic params = response['params']; if (params is Map<dynamic, dynamic>) { - if (event == 'server.status') + if (event == 'server.status') { _handleStatus(response['params']); - else if (event == 'analysis.errors') + } else if (event == 'analysis.errors') { _handleAnalysisIssues(response['params']); - else if (event == 'server.error') + } else if (event == 'server.error') { _handleServerError(response['params']); + } } } else if (response['error'] != null) { // Fields are 'code', 'message', and 'stackTrace'. @@ -135,8 +136,9 @@ .map<Map<String, dynamic>>(castStringKeyedMap) .map<AnalysisError>((Map<String, dynamic> json) => AnalysisError(json)) .toList(); - if (!_errorsController.isClosed) + if (!_errorsController.isClosed) { _errorsController.add(FileAnalysisErrors(file, errors)); + } } Future<bool> dispose() async { @@ -203,15 +205,18 @@ @override int compareTo(AnalysisError other) { // Sort in order of file path, error location, severity, and message. - if (file != other.file) + if (file != other.file) { return file.compareTo(other.file); + } - if (offset != other.offset) + if (offset != other.offset) { return offset - other.offset; + } final int diff = other._severityLevel.index - _severityLevel.index; - if (diff != 0) + if (diff != 0) { return diff; + } return message.compareTo(other.message); }
diff --git a/packages/flutter_tools/lib/src/dart/package_map.dart b/packages/flutter_tools/lib/src/dart/package_map.dart index f1057d3..862d256 100644 --- a/packages/flutter_tools/lib/src/dart/package_map.dart +++ b/packages/flutter_tools/lib/src/dart/package_map.dart
@@ -52,21 +52,24 @@ final List<String> pathSegments = packageUri.pathSegments.toList(); final String packageName = pathSegments.removeAt(0); final Uri packageBase = map[packageName]; - if (packageBase == null) + if (packageBase == null) { return null; + } final String packageRelativePath = fs.path.joinAll(pathSegments); return packageBase.resolveUri(fs.path.toUri(packageRelativePath)); } String checkValid() { - if (fs.isFileSync(packagesPath)) + if (fs.isFileSync(packagesPath)) { return null; + } String message = '$packagesPath does not exist.'; final String pubspecPath = fs.path.absolute(fs.path.dirname(packagesPath), 'pubspec.yaml'); - if (fs.isFileSync(pubspecPath)) + if (fs.isFileSync(pubspecPath)) { message += '\nDid you run "flutter pub get" in this directory?'; - else + } else { message += '\nDid you run this command from the same directory as your pubspec.yaml file?'; + } return message; } }
diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index 2b25239..5badddd 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart
@@ -57,15 +57,18 @@ } bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) { - if (!dotPackages.existsSync()) + if (!dotPackages.existsSync()) { return true; + } final DateTime dotPackagesLastModified = dotPackages.lastModifiedSync(); - if (pubSpecYaml.lastModifiedSync().isAfter(dotPackagesLastModified)) + if (pubSpecYaml.lastModifiedSync().isAfter(dotPackagesLastModified)) { return true; + } final File flutterToolsStamp = Cache.instance.getStampFileFor('flutter_tools'); if (flutterToolsStamp.existsSync() && - flutterToolsStamp.lastModifiedSync().isAfter(dotPackagesLastModified)) + flutterToolsStamp.lastModifiedSync().isAfter(dotPackagesLastModified)) { return true; + } return false; } @@ -86,8 +89,9 @@ final File dotPackages = fs.file(fs.path.join(directory, '.packages')); if (!skipPubspecYamlCheck && !pubSpecYaml.existsSync()) { - if (!skipIfAbsent) + if (!skipIfAbsent) { throwToolExit('$directory: no pubspec.yaml found'); + } return; } @@ -119,8 +123,9 @@ } } - if (!dotPackages.existsSync()) + if (!dotPackages.existsSync()) { throwToolExit('$directory: pub did not create .packages file.'); + } if (dotPackages.lastModifiedSync().isBefore(pubSpecYaml.lastModifiedSync())) { throwToolExit('$directory: pub did not update .packages file (pubspec.yaml timestamp: ${pubSpecYaml.lastModifiedSync()}; .packages timestamp: ${dotPackages.lastModifiedSync()}).'); @@ -150,8 +155,9 @@ }) async { showTraceForErrors ??= isRunningOnBot; - if (showTraceForErrors) + if (showTraceForErrors) { arguments.insert(0, '--trace'); + } int attempts = 0; int duration = 1; int code; @@ -276,9 +282,10 @@ // Warning: You are using these overridden dependencies: // ! analyzer 0.29.0-alpha.0 from path ../../bin/cache/dart-sdk/lib/analyzer // ! front_end 0.1.0-alpha.0 from path ../../bin/cache/dart-sdk/lib/front_end - if (message == 'Warning: You are using these overridden dependencies:') + if (message == 'Warning: You are using these overridden dependencies:') { return null; - if (message.contains(_analyzerWarning)) + } if (message.contains(_analyzerWarning)) { return null; + } return message; }
diff --git a/packages/flutter_tools/lib/src/devfs.dart b/packages/flutter_tools/lib/src/devfs.dart index a084f93..c4ba45c 100644 --- a/packages/flutter_tools/lib/src/devfs.dart +++ b/packages/flutter_tools/lib/src/devfs.dart
@@ -110,8 +110,9 @@ bool get isModified { final FileStat _oldFileStat = _fileStat; _stat(); - if (_oldFileStat == null && _fileStat == null) + if (_oldFileStat == null && _fileStat == null) { return false; + } return _oldFileStat == null || _fileStat == null || _fileStat.modified.isAfter(_oldFileStat.modified); } @@ -119,8 +120,9 @@ bool isModifiedAfter(DateTime time) { final FileStat _oldFileStat = _fileStat; _stat(); - if (_oldFileStat == null && _fileStat == null) + if (_oldFileStat == null && _fileStat == null) { return false; + } return time == null || _oldFileStat == null || _fileStat == null @@ -129,8 +131,9 @@ @override int get size { - if (_fileStat == null) + if (_fileStat == null) { _stat(); + } // Can still be null if the file wasn't found. return _fileStat?.size ?? 0; } @@ -289,8 +292,9 @@ _startWrite(deviceUri, content); _inFlight += 1; } - if ((_inFlight == 0) && (!_completer.isCompleted) && _outstanding.isEmpty) + if ((_inFlight == 0) && (!_completer.isCompleted) && _outstanding.isEmpty) { _completer.complete(); + } } Future<void> _startWrite( @@ -394,8 +398,9 @@ _baseUri = await _operations.create(fsName); } on rpc.RpcException catch (rpcException) { // 1001 is kFileSystemAlreadyExists in //dart/runtime/vm/json_stream.h - if (rpcException.code != 1001) + if (rpcException.code != 1001) { rethrow; + } printTrace('DevFS: Creating failed. Destroying and trying again'); await destroy(); _baseUri = await _operations.create(fsName);
diff --git a/packages/flutter_tools/lib/src/device.dart b/packages/flutter_tools/lib/src/device.dart index 09f6cdb..795471f 100644 --- a/packages/flutter_tools/lib/src/device.dart +++ b/packages/flutter_tools/lib/src/device.dart
@@ -81,8 +81,9 @@ /// A user-specified device ID. String get specifiedDeviceId { - if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') + if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') { return null; + } return _specifiedDeviceId; } @@ -115,8 +116,9 @@ } // Match on a id or name starting with [deviceId]. - for (Device device in devices.where(startsWithDeviceId)) + for (Device device in devices.where(startsWithDeviceId)) { yield device; + } } /// Return the list of connected devices, filtered by any user-specified device id. @@ -421,10 +423,12 @@ @override bool operator ==(dynamic other) { - if (identical(this, other)) + if (identical(this, other)) { return true; - if (other is! Device) + } + if (other is! Device) { return false; + } return id == other.id; } @@ -432,8 +436,9 @@ String toString() => name; static Stream<String> descriptions(List<Device> devices) async* { - if (devices.isEmpty) + if (devices.isEmpty) { return; + } // Extract device information final List<List<String>> table = <List<String>>[]; @@ -541,8 +546,9 @@ @override String toString() { final StringBuffer buf = StringBuffer('started=$started'); - if (observatoryUri != null) + if (observatoryUri != null) { buf.write(', observatory=$observatoryUri'); + } return buf.toString(); } }
diff --git a/packages/flutter_tools/lib/src/doctor.dart b/packages/flutter_tools/lib/src/doctor.dart index 8e45bfb..3fe5dd3 100644 --- a/packages/flutter_tools/lib/src/doctor.dart +++ b/packages/flutter_tools/lib/src/doctor.dart
@@ -98,26 +98,33 @@ if (_workflows == null) { _workflows = <Workflow>[]; - if (iosWorkflow.appliesToHostPlatform) + if (iosWorkflow.appliesToHostPlatform) { _workflows.add(iosWorkflow); + } - if (androidWorkflow.appliesToHostPlatform) + if (androidWorkflow.appliesToHostPlatform) { _workflows.add(androidWorkflow); + } - if (fuchsiaWorkflow.appliesToHostPlatform) + if (fuchsiaWorkflow.appliesToHostPlatform) { _workflows.add(fuchsiaWorkflow); + } - if (linuxWorkflow.appliesToHostPlatform) + if (linuxWorkflow.appliesToHostPlatform) { _workflows.add(linuxWorkflow); + } - if (macOSWorkflow.appliesToHostPlatform) + if (macOSWorkflow.appliesToHostPlatform) { _workflows.add(macOSWorkflow); + } - if (windowsWorkflow.appliesToHostPlatform) + if (windowsWorkflow.appliesToHostPlatform) { _workflows.add(windowsWorkflow); + } - if (webWorkflow.appliesToHostPlatform) + if (webWorkflow.appliesToHostPlatform) { _workflows.add(webWorkflow); + } } return _workflows; @@ -232,8 +239,9 @@ /// Print information about the state of installed tooling. Future<bool> diagnose({ bool androidLicenses = false, bool verbose = true }) async { - if (androidLicenses) + if (androidLicenses) { return AndroidLicenseValidator.runLicenseManager(); + } if (!verbose) { printStatus('Doctor summary (to see all details, run flutter doctor -v):'); @@ -317,8 +325,9 @@ bool get canListAnything => workflows.any((Workflow workflow) => workflow.canListDevices); bool get canLaunchAnything { - if (FlutterTesterDevices.showFlutterTesterDevice) + if (FlutterTesterDevices.showFlutterTesterDevice) { return true; + } return workflows.any((Workflow workflow) => workflow.canLaunchDevices); } } @@ -640,10 +649,12 @@ static final Version kMinIdeaVersion = Version(2017, 1, 0); static Iterable<DoctorValidator> get installedValidators { - if (platform.isLinux || platform.isWindows) + if (platform.isLinux || platform.isWindows) { return IntelliJValidatorOnLinuxAndWindows.installed; - if (platform.isMacOS) + } + if (platform.isMacOS) { return IntelliJValidatorOnMac.installed; + } return <DoctorValidator>[]; } @@ -676,12 +687,14 @@ void _validateIntelliJVersion(List<ValidationMessage> messages, Version minVersion) { // Ignore unknown versions. - if (minVersion == Version.unknown) + if (minVersion == Version.unknown) { return; + } final Version installedVersion = Version.parse(version); - if (installedVersion == null) + if (installedVersion == null) { return; + } if (installedVersion < minVersion) { messages.add(ValidationMessage.error(userMessages.intellijMinimumVersion(minVersion.toString()))); @@ -700,8 +713,9 @@ static Iterable<DoctorValidator> get installed { final List<DoctorValidator> validators = <DoctorValidator>[]; - if (homeDirPath == null) + if (homeDirPath == null) { return validators; + } void addValidator(String title, String version, String installPath, String pluginsPath) { final IntelliJValidatorOnLinuxAndWindows validator = @@ -709,8 +723,9 @@ for (int index = 0; index < validators.length; ++index) { final DoctorValidator other = validators[index]; if (other is IntelliJValidatorOnLinuxAndWindows && validator.installPath == other.installPath) { - if (validator.version.compareTo(other.version) > 0) + if (validator.version.compareTo(other.version) > 0) { validators[index] = validator; + } return; } }
diff --git a/packages/flutter_tools/lib/src/emulator.dart b/packages/flutter_tools/lib/src/emulator.dart index dcbb538..879641e 100644 --- a/packages/flutter_tools/lib/src/emulator.dart +++ b/packages/flutter_tools/lib/src/emulator.dart
@@ -80,26 +80,29 @@ } final String device = await _getPreferredAvailableDevice(); - if (device == null) + if (device == null) { return CreateEmulatorResult(name, success: false, error: 'No device definitions are available'); + } final String sdkId = await _getPreferredSdkId(); - if (sdkId == null) + if (sdkId == null) { return CreateEmulatorResult(name, success: false, error: 'No suitable Android AVD system images are available. You may need to install these' ' using sdkmanager, for example:\n' ' sdkmanager "system-images;android-27;google_apis_playstore;x86"'); + } // Cleans up error output from avdmanager to make it more suitable to show // to flutter users. Specifically: // - Removes lines that say "null" (!) // - Removes lines that tell the user to use '--force' to overwrite emulators String cleanError(String error) { - if (error == null || error.trim() == '') + if (error == null || error.trim() == '') { return null; + } return error .split('\n') .where((String l) => l.trim() != 'null') @@ -226,10 +229,12 @@ @override bool operator ==(dynamic other) { - if (identical(this, other)) + if (identical(this, other)) { return true; - if (other is! Emulator) + } + if (other is! Emulator) { return false; + } return id == other.id; } @@ -239,8 +244,9 @@ String toString() => name; static List<String> descriptions(List<Emulator> emulators) { - if (emulators.isEmpty) + if (emulators.isEmpty) { return <String>[]; + } // Extract emulators information final List<List<String>> table = <List<String>>[];
diff --git a/packages/flutter_tools/lib/src/flutter_manifest.dart b/packages/flutter_tools/lib/src/flutter_manifest.dart index 1c3887f..247a21d 100644 --- a/packages/flutter_tools/lib/src/flutter_manifest.dart +++ b/packages/flutter_tools/lib/src/flutter_manifest.dart
@@ -27,8 +27,9 @@ /// Returns null on invalid manifest. Returns empty manifest on missing file. static FlutterManifest createFromPath(String path) { - if (path == null || !fs.isFileSync(path)) + if (path == null || !fs.isFileSync(path)) { return _createFromYaml(null); + } final String manifest = fs.file(path).readAsStringSync(); return createFromString(manifest); } @@ -41,8 +42,9 @@ static FlutterManifest _createFromYaml(dynamic yamlDocument) { final FlutterManifest pubspec = FlutterManifest._(); - if (yamlDocument != null && !_validate(yamlDocument)) + if (yamlDocument != null && !_validate(yamlDocument)) { return null; + } final Map<dynamic, dynamic> yamlMap = yamlDocument; if (yamlMap != null) { @@ -99,10 +101,10 @@ /// The build version name from the `pubspec.yaml` file. /// Can be null if version isn't set or has a wrong format. String get buildName { - if (appVersion != null && appVersion.contains('+')) + if (appVersion != null && appVersion.contains('+')) { return appVersion.split('+')?.elementAt(0); - else - return appVersion; + } + return appVersion; } /// The build version number from the `pubspec.yaml` file. @@ -150,8 +152,9 @@ /// module or plugin descriptor. Returns null, if there is no /// such declaration. String get androidPackage { - if (isModule) + if (isModule) { return _flutterDescriptor['module']['androidPackage']; + } if (isPlugin) { final YamlMap plugin = _flutterDescriptor['plugin']; if (plugin.containsKey('platforms')) { @@ -166,8 +169,9 @@ /// Returns the iOS bundle identifier declared by this manifest in its /// module descriptor. Returns null if there is no such declaration. String get iosBundleIdentifier { - if (isModule) + if (isModule) { return _flutterDescriptor['module']['iosBundleIdentifier']; + } return null; } @@ -202,8 +206,9 @@ } List<Font> _extractFonts() { - if (!_flutterDescriptor.containsKey('fonts')) + if (!_flutterDescriptor.containsKey('fonts')) { return <Font>[]; + } final List<Font> fonts = <Font>[]; for (Map<String, dynamic> fontFamily in _rawFontsDescriptor) { @@ -232,8 +237,9 @@ style: fontFile['style'], )); } - if (fontAssets.isNotEmpty) + if (fontAssets.isNotEmpty) { fonts.add(Font(fontFamily['family'], fontAssets)); + } } return fonts; } @@ -269,11 +275,13 @@ Map<String, dynamic> get descriptor { final Map<String, dynamic> descriptor = <String, dynamic>{}; - if (weight != null) + if (weight != null) { descriptor['weight'] = weight; + } - if (style != null) + if (style != null) { descriptor['style'] = style; + } descriptor['asset'] = assetUri.path; return descriptor;
diff --git a/packages/flutter_tools/lib/src/intellij/intellij.dart b/packages/flutter_tools/lib/src/intellij/intellij.dart index 4976613..ff42963 100644 --- a/packages/flutter_tools/lib/src/intellij/intellij.dart +++ b/packages/flutter_tools/lib/src/intellij/intellij.dart
@@ -46,8 +46,9 @@ bool _hasPackage(String packageName) { final String packagePath = fs.path.join(pluginsPath, packageName); - if (packageName.endsWith('.jar')) + if (packageName.endsWith('.jar')) { return fs.isFileSync(packagePath); + } return fs.isDirectorySync(packagePath); }
diff --git a/packages/flutter_tools/lib/src/ios/code_signing.dart b/packages/flutter_tools/lib/src/ios/code_signing.dart index b238435..677defd 100644 --- a/packages/flutter_tools/lib/src/ios/code_signing.dart +++ b/packages/flutter_tools/lib/src/ios/code_signing.dart
@@ -110,8 +110,9 @@ return null; } - if (isNotEmpty(buildSettings['PROVISIONING_PROFILE'])) + if (isNotEmpty(buildSettings['PROVISIONING_PROFILE'])) { return null; + } // If the user's environment is missing the tools needed to find and read // certificates, abandon. Tools should be pre-equipped on macOS. @@ -184,8 +185,9 @@ // Don't care about the result. unawaited(opensslProcess.stderr.drain<String>()); - if (await opensslProcess.exitCode != 0) + if (await opensslProcess.exitCode != 0) { return null; + } return <String, String>{ 'DEVELOPMENT_TEAM': _certificateOrganizationalUnitExtractionPattern @@ -201,8 +203,9 @@ throwToolExit('No development certificates available to code sign app for device deployment'); } - if (validCodeSigningIdentities.length == 1) + if (validCodeSigningIdentities.length == 1) { return validCodeSigningIdentities.first; + } if (validCodeSigningIdentities.length > 1) { final String savedCertChoice = config.getValue('ios-signing-cert'); @@ -218,8 +221,9 @@ // If terminal UI can't be used, just attempt with the first valid certificate // since we can't ask the user. - if (!terminal.usesTerminalUi) + if (!terminal.usesTerminalUi) { return validCodeSigningIdentities.first; + } final int count = validCodeSigningIdentities.length; printStatus(
diff --git a/packages/flutter_tools/lib/src/ios/devices.dart b/packages/flutter_tools/lib/src/ios/devices.dart index 3d0f1f5..803e416 100644 --- a/packages/flutter_tools/lib/src/ios/devices.dart +++ b/packages/flutter_tools/lib/src/ios/devices.dart
@@ -167,14 +167,16 @@ if (!platform.isMacOS) { throw UnsupportedError('Control of iOS devices or simulators only supported on Mac OS.'); } - if (!iMobileDevice.isInstalled) + if (!iMobileDevice.isInstalled) { return <IOSDevice>[]; + } final List<IOSDevice> devices = <IOSDevice>[]; for (String id in (await iMobileDevice.getAvailableDeviceIDs()).split('\n')) { id = id.trim(); - if (id.isEmpty) + if (id.isEmpty) { continue; + } try { final String deviceName = await iMobileDevice.getInfoForDevice(id, 'DeviceName'); @@ -287,8 +289,9 @@ return LaunchResult.failed(); } } else { - if (!await installApp(package)) + if (!await installApp(package)) { return LaunchResult.failed(); + } } // Step 2: Check that the application exists at the specified path. @@ -302,19 +305,22 @@ // Step 3: Attempt to install the application on the device. final List<String> launchArguments = <String>['--enable-dart-profiling']; - if (debuggingOptions.startPaused) + if (debuggingOptions.startPaused) { launchArguments.add('--start-paused'); + } - if (debuggingOptions.disableServiceAuthCodes) + if (debuggingOptions.disableServiceAuthCodes) { launchArguments.add('--disable-service-auth-codes'); + } if (debuggingOptions.dartFlags.isNotEmpty) { final String dartFlags = debuggingOptions.dartFlags; launchArguments.add('--dart-flags="$dartFlags"'); } - if (debuggingOptions.useTestFonts) + if (debuggingOptions.useTestFonts) { launchArguments.add('--use-test-fonts'); + } // "--enable-checked-mode" and "--verify-entry-points" should always be // passed when we launch debug build via "ios-deploy". However, we don't @@ -327,24 +333,29 @@ launchArguments.add('--verify-entry-points'); } - if (debuggingOptions.enableSoftwareRendering) + if (debuggingOptions.enableSoftwareRendering) { launchArguments.add('--enable-software-rendering'); + } - if (debuggingOptions.skiaDeterministicRendering) + if (debuggingOptions.skiaDeterministicRendering) { launchArguments.add('--skia-deterministic-rendering'); + } - if (debuggingOptions.traceSkia) + if (debuggingOptions.traceSkia) { launchArguments.add('--trace-skia'); + } - if (debuggingOptions.dumpSkpOnShaderCompilation) + if (debuggingOptions.dumpSkpOnShaderCompilation) { launchArguments.add('--dump-skp-on-shader-compilation'); + } if (debuggingOptions.verboseSystemLogs) { launchArguments.add('--verbose-logging'); } - if (platformArgs['trace-startup'] ?? false) + if (platformArgs['trace-startup'] ?? false) { launchArguments.add('--trace-startup'); + } final Status installStatus = logger.startProgress( 'Installing and launching...', @@ -547,8 +558,9 @@ _process.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_newLineHandler()); _process.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_newLineHandler()); _process.exitCode.whenComplete(() { - if (_linesController.hasListener) + if (_linesController.hasListener) { _linesController.close(); + } }); }); } @@ -604,8 +616,9 @@ @override Future<int> forward(int devicePort, { int hostPort }) async { final bool autoselect = hostPort == null || hostPort == 0; - if (autoselect) + if (autoselect) { hostPort = 1024; + } Process process; @@ -629,8 +642,9 @@ if (!connected) { if (autoselect) { hostPort += 1; - if (hostPort > 65535) + if (hostPort > 65535) { throw Exception('Could not find open port on host.'); + } } else { throw Exception('Port $hostPort is not available.'); }
diff --git a/packages/flutter_tools/lib/src/ios/ios_emulators.dart b/packages/flutter_tools/lib/src/ios/ios_emulators.dart index a3bd885..48d40ee 100644 --- a/packages/flutter_tools/lib/src/ios/ios_emulators.dart +++ b/packages/flutter_tools/lib/src/ios/ios_emulators.dart
@@ -56,8 +56,9 @@ } // First run with `-n` to force a device to boot if there isn't already one - if (!await launchSimulator(<String>['-n'])) + if (!await launchSimulator(<String>['-n'])) { return; + } // Run again to force it to Foreground (using -n doesn't force existing // devices to the foreground)
diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index 8749ec8..7fff383 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart
@@ -181,8 +181,9 @@ <MapEntry<String, String>>[cache.dyLdLibEntry] ), ); - if (result.exitCode != 0) + if (result.exitCode != 0) { throw ToolExit('idevice_id returned an error:\n${result.stderr}'); + } return result.stdout; } on ProcessException { throw ToolExit('Failed to invoke idevice_id. Run flutter doctor.'); @@ -203,8 +204,9 @@ <MapEntry<String, String>>[cache.dyLdLibEntry] ), ); - if (result.exitCode == 255 && result.stdout != null && result.stdout.contains('No device found')) + if (result.exitCode == 255 && result.stdout != null && result.stdout.contains('No device found')) { throw IOSDeviceNotFoundError('ideviceinfo could not find device:\n${result.stdout}. Try unlocking attached devices.'); + } if (result.exitCode == 255 && result.stderr != null && result.stderr.contains('Could not connect to lockdownd')) { if (result.stderr.contains('error code -${LockdownReturnCode.pairingDialogResponsePending.code}')) { throw const IOSDeviceNotTrustedError( @@ -219,8 +221,9 @@ ); } } - if (result.exitCode != 0) + if (result.exitCode != 0) { throw ToolExit('ideviceinfo returned an error:\n${result.stderr}'); + } return result.stdout.trim(); } on ProcessException { throw ToolExit('Failed to invoke ideviceinfo. Run flutter doctor.'); @@ -265,11 +268,13 @@ bool codesign = true, }) async { - if (!upgradePbxProjWithFlutterAssets(app.project)) + if (!upgradePbxProjWithFlutterAssets(app.project)) { return XcodeBuildResult(success: false); + } - if (!_checkXcodeVersion()) + if (!_checkXcodeVersion()) { return XcodeBuildResult(success: false); + } final XcodeProjectInfo projectInfo = await xcodeProjectInterpreter.getInfo(app.project.hostAppRoot.path); @@ -545,8 +550,9 @@ final String generatedXcconfigPath = fs.path.join(fs.currentDirectory.path, appPath, 'Flutter', 'Generated.xcconfig'); final File generatedXcconfigFile = fs.file(generatedXcconfigPath); - if (!generatedXcconfigFile.existsSync()) + if (!generatedXcconfigFile.existsSync()) { return null; + } return generatedXcconfigFile.readAsStringSync(); } @@ -636,8 +642,9 @@ const String _xcodeRequirement = 'Xcode $kXcodeRequiredVersionMajor.$kXcodeRequiredVersionMinor or greater is required to develop for iOS.'; bool _checkXcodeVersion() { - if (!platform.isMacOS) + if (!platform.isMacOS) { return false; + } if (!xcodeProjectInterpreter.isInstalled) { printError('Cannot find "xcodebuild". $_xcodeRequirement'); return false; @@ -711,8 +718,9 @@ for (final String line in lines) { final Match match = oldAssets.firstMatch(line); if (match != null) { - if (printedStatuses.add(match.group(1))) + if (printedStatuses.add(match.group(1))) { printStatus('Removing obsolete reference to ${match.group(1)} from ${project.hostAppBundleName}'); + } } else { buffer.writeln(line); }
diff --git a/packages/flutter_tools/lib/src/ios/plist_parser.dart b/packages/flutter_tools/lib/src/ios/plist_parser.dart index f626fe6..c873c3d 100644 --- a/packages/flutter_tools/lib/src/ios/plist_parser.dart +++ b/packages/flutter_tools/lib/src/ios/plist_parser.dart
@@ -28,10 +28,12 @@ Map<String, dynamic> parseFile(String plistFilePath) { assert(plistFilePath != null); const String executable = '/usr/bin/plutil'; - if (!fs.isFileSync(executable)) + if (!fs.isFileSync(executable)) { throw const FileNotFoundException(executable); - if (!fs.isFileSync(plistFilePath)) + } + if (!fs.isFileSync(plistFilePath)) { return const <String, dynamic>{}; + } final String normalizedPlistPath = fs.path.absolute(plistFilePath);
diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart index a8f912c..073716a 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart
@@ -47,8 +47,9 @@ static IOSSimulatorUtils get instance => context.get<IOSSimulatorUtils>(); Future<List<IOSSimulator>> getAttachedDevices() async { - if (!xcode.isInstalledAndMeetsVersionCheck) + if (!xcode.isInstalledAndMeetsVersionCheck) { return <IOSSimulator>[]; + } final List<SimDevice> connected = await SimControl.instance.getConnectedDevices(); return connected.map<IOSSimulator>((SimDevice device) { @@ -327,8 +328,9 @@ @override String supportMessage() { - if (isSupported()) + if (isSupported()) { return 'Supported'; + } return _supportMessage ?? 'Unknown'; } @@ -353,35 +355,42 @@ return LaunchResult.failed(); } } else { - if (!await installApp(package)) + if (!await installApp(package)) { return LaunchResult.failed(); + } } // Prepare launch arguments. final List<String> args = <String>['--enable-dart-profiling']; if (debuggingOptions.debuggingEnabled) { - if (debuggingOptions.buildInfo.isDebug) + if (debuggingOptions.buildInfo.isDebug) { args.addAll(<String>[ '--enable-checked-mode', '--verify-entry-points', ]); - if (debuggingOptions.startPaused) + } + if (debuggingOptions.startPaused) { args.add('--start-paused'); - if (debuggingOptions.disableServiceAuthCodes) + } + if (debuggingOptions.disableServiceAuthCodes) { args.add('--disable-service-auth-codes'); - if (debuggingOptions.skiaDeterministicRendering) + } + if (debuggingOptions.skiaDeterministicRendering) { args.add('--skia-deterministic-rendering'); - if (debuggingOptions.useTestFonts) + } + if (debuggingOptions.useTestFonts) { args.add('--use-test-fonts'); + } final int observatoryPort = debuggingOptions.observatoryPort ?? 0; args.add('--observatory-port=$observatoryPort'); } ProtocolDiscovery observatoryDiscovery; - if (debuggingOptions.debuggingEnabled) + if (debuggingOptions.debuggingEnabled) { observatoryDiscovery = ProtocolDiscovery.observatory( getLogReader(app: package), ipv6: ipv6); + } // Launch the updated application in the simulator. try { @@ -434,14 +443,16 @@ targetOverride: mainPath, buildForDevice: false, ); - if (!buildResult.success) + if (!buildResult.success) { throwToolExit('Could not build the application for the simulator.'); + } // Step 2: Assert that the Xcode project was successfully built. final Directory bundle = fs.directory(app.simulatorBundlePath); final bool bundleExists = bundle.existsSync(); - if (!bundleExists) + if (!bundleExists) { throwToolExit('Could not find the built application bundle at ${bundle.path}.'); + } // Step 3: Install the updated bundle to the simulator. await SimControl.instance.install(id, fs.path.absolute(bundle.path)); @@ -504,8 +515,9 @@ Future<void> ensureLogsExists() async { if (await sdkMajorVersion < 11) { final File logFile = fs.file(logFilePath); - if (!logFile.existsSync()) + if (!logFile.existsSync()) { logFile.writeAsBytesSync(<int>[]); + } } } @@ -594,8 +606,9 @@ // We don't want to wait for the process or its callback. Best effort // cleanup in the callback. unawaited(_deviceProcess.exitCode.whenComplete(() { - if (_linesController.hasListener) + if (_linesController.hasListener) { _linesController.close(); + } })); } @@ -618,39 +631,48 @@ final String content = match.group(4); // Filter out non-Flutter originated noise from the engine. - if (_appName != null && category != _appName) + if (_appName != null && category != _appName) { return null; + } - if (tag != null && tag != '(Flutter)') + if (tag != null && tag != '(Flutter)') { return null; + } // Filter out some messages that clearly aren't related to Flutter. - if (string.contains(': could not find icon for representation -> com.apple.')) + if (string.contains(': could not find icon for representation -> com.apple.')) { return null; + } // assertion failed: 15G1212 13E230: libxpc.dylib + 57882 [66C28065-C9DB-3C8E-926F-5A40210A6D1B]: 0x7d - if (content.startsWith('assertion failed: ') && content.contains(' libxpc.dylib ')) + if (content.startsWith('assertion failed: ') && content.contains(' libxpc.dylib ')) { return null; + } - if (_appName == null) + if (_appName == null) { return '$category: $content'; - else if (category == _appName) + } else if (category == _appName) { return content; + } return null; } - if (string.startsWith('Filtering the log data using ')) + if (string.startsWith('Filtering the log data using ')) { return null; + } - if (string.startsWith('Timestamp (process)[PID]')) + if (string.startsWith('Timestamp (process)[PID]')) { return null; + } - if (_lastMessageSingleRegex.matchAsPrefix(string) != null) + if (_lastMessageSingleRegex.matchAsPrefix(string) != null) { return null; + } - if (RegExp(r'assertion failed: .* libxpc.dylib .* 0x7d$').matchAsPrefix(string) != null) + if (RegExp(r'assertion failed: .* libxpc.dylib .* 0x7d$').matchAsPrefix(string) != null) { return null; + } return string; } @@ -665,13 +687,15 @@ if (_lastLine != null) { int repeat = int.parse(multi.group(1)); repeat = math.max(0, math.min(100, repeat)); - for (int i = 1; i < repeat; i++) + for (int i = 1; i < repeat; i++) { _linesController.add(_lastLine); + } } } else { _lastLine = _filterDeviceLine(line); - if (_lastLine != null) + if (_lastLine != null) { _linesController.add(_lastLine); + } } } @@ -682,12 +706,14 @@ void _onSystemLine(String line) { printTrace('[SYS LOG] $line'); - if (!_flutterRunnerRegex.hasMatch(line)) + if (!_flutterRunnerRegex.hasMatch(line)) { return; + } final String filteredLine = _filterSystemLog(line); - if (filteredLine == null) + if (filteredLine == null) { return; + } _linesController.add(filteredLine); } @@ -706,8 +732,9 @@ while (i < v1Fragments.length && i < v2Fragments.length) { final int v1Fragment = v1Fragments[i]; final int v2Fragment = v2Fragments[i]; - if (v1Fragment != v2Fragment) + if (v1Fragment != v2Fragment) { return v1Fragment.compareTo(v2Fragment); + } i += 1; } return v1Fragments.length.compareTo(v2Fragments.length); @@ -731,8 +758,9 @@ final int v1 = int.parse(m1[1]); final int v2 = int.parse(m2[1]); - if (v1 != v2) + if (v1 != v2) { return v1.compareTo(v2); + } // Sorted in the least preferred first order. const List<String> qualifiers = <String>['-Plus', '', 's-Plus', 's'];
diff --git a/packages/flutter_tools/lib/src/ios/xcodeproj.dart b/packages/flutter_tools/lib/src/ios/xcodeproj.dart index 8723faf..f8c3bd0 100644 --- a/packages/flutter_tools/lib/src/ios/xcodeproj.dart +++ b/packages/flutter_tools/lib/src/ios/xcodeproj.dart
@@ -136,8 +136,9 @@ xcodeBuildSettings.add('FLUTTER_APPLICATION_PATH=${fs.path.normalize(project.directory.path)}'); // Relative to FLUTTER_APPLICATION_PATH, which is [Directory.current]. - if (targetOverride != null) + if (targetOverride != null) { xcodeBuildSettings.add('FLUTTER_TARGET=$targetOverride'); + } // The build outputs directory, relative to FLUTTER_APPLICATION_PATH. xcodeBuildSettings.add('FLUTTER_BUILD_DIR=${buildDirOverride ?? getBuildDirectory()}'); @@ -219,8 +220,9 @@ } _versionText = result.stdout.trim().replaceAll('\n', ', '); final Match match = _versionRegex.firstMatch(versionText); - if (match == null) + if (match == null) { return; + } final String version = match.group(1); final List<String> components = version.split('.'); _majorVersion = int.parse(components[0]); @@ -234,22 +236,25 @@ String _versionText; String get versionText { - if (_versionText == null) + if (_versionText == null) { _updateVersion(); + } return _versionText; } int _majorVersion; int get majorVersion { - if (_majorVersion == null) + if (_majorVersion == null) { _updateVersion(); + } return _majorVersion; } int _minorVersion; int get minorVersion { - if (_minorVersion == null) + if (_minorVersion == null) { _updateVersion(); + } return _minorVersion; } @@ -367,8 +372,9 @@ /// project and target. String substituteXcodeVariables(String str, Map<String, String> xcodeBuildSettings) { final Iterable<Match> matches = _varExpr.allMatches(str); - if (matches.isEmpty) + if (matches.isEmpty) { return str; + } return str.replaceAllMapped(_varExpr, (Match m) => xcodeBuildSettings[m[1]] ?? m[0]); } @@ -400,8 +406,9 @@ } collector?.add(line.trim()); } - if (schemes.isEmpty) + if (schemes.isEmpty) { schemes.add('Runner'); + } return XcodeProjectInfo(targets, buildConfigurations, schemes); } @@ -425,10 +432,10 @@ /// The expected build configuration for [buildInfo] and [scheme]. static String expectedBuildConfigurationFor(BuildInfo buildInfo, String scheme) { final String baseConfiguration = _baseConfigurationFor(buildInfo); - if (buildInfo.flavor == null) + if (buildInfo.flavor == null) { return baseConfiguration; - else - return baseConfiguration + '-$scheme'; + } + return baseConfiguration + '-$scheme'; } /// Checks whether the [buildConfigurations] contains the specified string, without @@ -446,8 +453,9 @@ /// best match. String schemeFor(BuildInfo buildInfo) { final String expectedScheme = expectedSchemeFor(buildInfo); - if (schemes.contains(expectedScheme)) + if (schemes.contains(expectedScheme)) { return expectedScheme; + } return _uniqueMatch(schemes, (String candidate) { return candidate.toLowerCase() == expectedScheme.toLowerCase(); }); @@ -457,32 +465,35 @@ /// null, if there is no unique best match. String buildConfigurationFor(BuildInfo buildInfo, String scheme) { final String expectedConfiguration = expectedBuildConfigurationFor(buildInfo, scheme); - if (hasBuildConfiguratinForBuildMode(expectedConfiguration)) + if (hasBuildConfiguratinForBuildMode(expectedConfiguration)) { return expectedConfiguration; + } final String baseConfiguration = _baseConfigurationFor(buildInfo); return _uniqueMatch(buildConfigurations, (String candidate) { candidate = candidate.toLowerCase(); - if (buildInfo.flavor == null) + if (buildInfo.flavor == null) { return candidate == expectedConfiguration.toLowerCase(); - else - return candidate.contains(baseConfiguration.toLowerCase()) && candidate.contains(scheme.toLowerCase()); + } + return candidate.contains(baseConfiguration.toLowerCase()) && candidate.contains(scheme.toLowerCase()); }); } static String _baseConfigurationFor(BuildInfo buildInfo) { - if (buildInfo.isDebug) + if (buildInfo.isDebug) { return 'Debug'; - if (buildInfo.isProfile) + } + if (buildInfo.isProfile) { return 'Profile'; + } return 'Release'; } static String _uniqueMatch(Iterable<String> strings, bool matches(String s)) { final List<String> options = strings.where(matches).toList(); - if (options.length == 1) + if (options.length == 1) { return options.first; - else - return null; + } + return null; } @override
diff --git a/packages/flutter_tools/lib/src/macos/cocoapods.dart b/packages/flutter_tools/lib/src/macos/cocoapods.dart index 08e2057..d5beb70 100644 --- a/packages/flutter_tools/lib/src/macos/cocoapods.dart +++ b/packages/flutter_tools/lib/src/macos/cocoapods.dart
@@ -87,14 +87,16 @@ } try { final Version installedVersion = Version.parse(versionText); - if (installedVersion == null) + if (installedVersion == null) { return CocoaPodsStatus.unknownVersion; - if (installedVersion < Version.parse(cocoaPodsMinimumVersion)) + } + if (installedVersion < Version.parse(cocoaPodsMinimumVersion)) { return CocoaPodsStatus.belowMinimumVersion; - else if (installedVersion < Version.parse(cocoaPodsRecommendedVersion)) + } + if (installedVersion < Version.parse(cocoaPodsRecommendedVersion)) { return CocoaPodsStatus.belowRecommendedVersion; - else - return CocoaPodsStatus.recommended; + } + return CocoaPodsStatus.recommended; } on FormatException { return CocoaPodsStatus.notInstalled; } @@ -242,8 +244,9 @@ final String content = file.readAsStringSync(); final String include = '#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.${mode .toLowerCase()}.xcconfig"'; - if (!content.contains(include)) + if (!content.contains(include)) { file.writeAsStringSync('$include\n$content', flush: true); + } } } @@ -262,8 +265,9 @@ // 3. Pods/Manifest.lock doesn't exist (It is deleted when plugins change) // 4. Podfile.lock doesn't match Pods/Manifest.lock. bool _shouldRunPodInstall(XcodeBasedProject xcodeProject, bool dependenciesChanged) { - if (dependenciesChanged) + if (dependenciesChanged) { return true; + } final File podfileFile = xcodeProject.podfile; final File podfileLockFile = xcodeProject.podfileLock;
diff --git a/packages/flutter_tools/lib/src/macos/xcode.dart b/packages/flutter_tools/lib/src/macos/xcode.dart index 5ab06a0..39146cb 100644 --- a/packages/flutter_tools/lib/src/macos/xcode.dart +++ b/packages/flutter_tools/lib/src/macos/xcode.dart
@@ -37,8 +37,9 @@ } bool get isInstalled { - if (xcodeSelectPath == null || xcodeSelectPath.isEmpty) + if (xcodeSelectPath == null || xcodeSelectPath.isEmpty) { return false; + } return xcodeProjectInterpreter.isInstalled; } @@ -90,12 +91,15 @@ } bool get isVersionSatisfactory { - if (!xcodeProjectInterpreter.isInstalled) + if (!xcodeProjectInterpreter.isInstalled) { return false; - if (majorVersion > kXcodeRequiredVersionMajor) + } + if (majorVersion > kXcodeRequiredVersionMajor) { return true; - if (majorVersion == kXcodeRequiredVersionMajor) + } + if (majorVersion == kXcodeRequiredVersionMajor) { return minorVersion >= kXcodeRequiredVersionMinor; + } return false; } @@ -125,8 +129,9 @@ } String getSimulatorPath() { - if (xcodeSelectPath == null) + if (xcodeSelectPath == null) { return null; + } final List<String> searchPaths = <String>[ fs.path.join(xcodeSelectPath, 'Applications', 'Simulator.app'), ];
diff --git a/packages/flutter_tools/lib/src/macos/xcode_validator.dart b/packages/flutter_tools/lib/src/macos/xcode_validator.dart index 38329a9..b6dcc14 100644 --- a/packages/flutter_tools/lib/src/macos/xcode_validator.dart +++ b/packages/flutter_tools/lib/src/macos/xcode_validator.dart
@@ -24,8 +24,9 @@ messages.add(ValidationMessage(userMessages.xcodeLocation(xcode.xcodeSelectPath))); xcodeVersionInfo = xcode.versionText; - if (xcodeVersionInfo.contains(',')) + if (xcodeVersionInfo.contains(',')) { xcodeVersionInfo = xcodeVersionInfo.substring(0, xcodeVersionInfo.indexOf(',')); + } messages.add(ValidationMessage(xcode.versionText)); if (!xcode.isInstalledAndMeetsVersionCheck) { @@ -55,4 +56,4 @@ return ValidationResult(xcodeStatus, messages, statusInfo: xcodeVersionInfo); } -} \ No newline at end of file +}
diff --git a/packages/flutter_tools/lib/src/plugins.dart b/packages/flutter_tools/lib/src/plugins.dart index 1711ee6..0e42bcd 100644 --- a/packages/flutter_tools/lib/src/plugins.dart +++ b/packages/flutter_tools/lib/src/plugins.dart
@@ -189,14 +189,17 @@ Plugin _pluginFromPubspec(String name, Uri packageRoot) { final String pubspecPath = fs.path.fromUri(packageRoot.resolve('pubspec.yaml')); - if (!fs.isFileSync(pubspecPath)) + if (!fs.isFileSync(pubspecPath)) { return null; + } final dynamic pubspec = loadYaml(fs.file(pubspecPath).readAsStringSync()); - if (pubspec == null) + if (pubspec == null) { return null; + } final dynamic flutterConfig = pubspec['flutter']; - if (flutterConfig == null || !flutterConfig.containsKey('plugin')) + if (flutterConfig == null || !flutterConfig.containsKey('plugin')) { return null; + } final String packageRootPath = fs.path.fromUri(packageRoot); printTrace('Found plugin $name at $packageRootPath'); return Plugin.fromYaml(name, packageRootPath, flutterConfig['plugin']); @@ -215,8 +218,9 @@ packages.forEach((String name, Uri uri) { final Uri packageRoot = uri.resolve('..'); final Plugin plugin = _pluginFromPubspec(name, packageRoot); - if (plugin != null) + if (plugin != null) { plugins.add(plugin); + } }); return plugins; }
diff --git a/packages/flutter_tools/lib/src/project.dart b/packages/flutter_tools/lib/src/project.dart index 8322ab8..d613f20 100644 --- a/packages/flutter_tools/lib/src/project.dart +++ b/packages/flutter_tools/lib/src/project.dart
@@ -102,10 +102,10 @@ } String _organizationNameFromPackageName(String packageName) { - if (packageName != null && 0 <= packageName.lastIndexOf('.')) + if (packageName != null && 0 <= packageName.lastIndexOf('.')) { return packageName.substring(0, packageName.lastIndexOf('.')); - else - return null; + } + return null; } /// The iOS sub project of this project. @@ -302,8 +302,9 @@ /// This parent folder of `Runner.xcodeproj`. Directory get hostAppRoot { - if (!isModule || _editableDirectory.existsSync()) + if (!isModule || _editableDirectory.existsSync()) { return _editableDirectory; + } return ephemeralDirectory; } @@ -397,8 +398,9 @@ /// /// Returns null, if iOS tooling is unavailable. Map<String, String> get buildSettings { - if (!xcode.xcodeProjectInterpreter.isInstalled) + if (!xcode.xcodeProjectInterpreter.isInstalled) { return null; + } _buildSettings ??= xcode.xcodeProjectInterpreter.getBuildSettings(xcodeProject.path, _hostAppBundleName); @@ -409,8 +411,9 @@ Future<void> ensureReadyForPlatformSpecificTooling() async { _regenerateFromTemplateIfNeeded(); - if (!_flutterLibRoot.existsSync()) + if (!_flutterLibRoot.existsSync()) { return; + } await _updateGeneratedXcodeConfigIfNeeded(); } @@ -425,12 +428,14 @@ } void _regenerateFromTemplateIfNeeded() { - if (!isModule) + if (!isModule) { return; + } final bool pubspecChanged = isOlderThanReference(entity: ephemeralDirectory, referenceFile: parent.pubspecFile); final bool toolingChanged = Cache.instance.isOlderThanToolsStamp(ephemeralDirectory); - if (!pubspecChanged && !toolingChanged) + if (!pubspecChanged && !toolingChanged) { return; + } _deleteIfExistsSync(ephemeralDirectory); _overwriteFromTemplate(fs.path.join('module', 'ios', 'library'), ephemeralDirectory); // Add ephemeral host app, if a editable host app does not already exist. @@ -444,8 +449,9 @@ Future<void> makeHostAppEditable() async { assert(isModule); - if (_editableDirectory.existsSync()) + if (_editableDirectory.existsSync()) { throwToolExit('iOS host app is already editable. To start fresh, delete the ios/ folder.'); + } _deleteIfExistsSync(ephemeralDirectory); _overwriteFromTemplate(fs.path.join('module', 'ios', 'library'), ephemeralDirectory); _overwriteFromTemplate(fs.path.join('module', 'ios', 'host_app_ephemeral'), _editableDirectory); @@ -496,8 +502,9 @@ /// containing the `app/` subdirectory and the `settings.gradle` file that /// includes it in the overall Gradle project. Directory get hostAppGradleRoot { - if (!isModule || _editableHostAppDirectory.existsSync()) + if (!isModule || _editableHostAppDirectory.existsSync()) { return _editableHostAppDirectory; + } return ephemeralDirectory; } @@ -574,8 +581,9 @@ Future<void> makeHostAppEditable() async { assert(isModule); - if (_editableHostAppDirectory.existsSync()) + if (_editableHostAppDirectory.existsSync()) { throwToolExit('Android host app is already editable. To start fresh, delete the android/ folder.'); + } _regenerateLibrary(); _overwriteFromTemplate(fs.path.join('module', 'android', 'host_app_common'), _editableHostAppDirectory); _overwriteFromTemplate(fs.path.join('module', 'android', 'host_app_editable'), _editableHostAppDirectory); @@ -636,8 +644,9 @@ /// Deletes [directory] with all content. void _deleteIfExistsSync(Directory directory) { - if (directory.existsSync()) + if (directory.existsSync()) { directory.deleteSync(recursive: true); + } }
diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index f4b35b5..9a9b489 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart
@@ -116,8 +116,9 @@ Restart restart, CompileExpression compileExpression, }) async { - if (vmServices != null) + if (vmServices != null) { return; + } final List<VMService> localVmServices = List<VMService>(observatoryUris.length); for (int i = 0; i < observatoryUris.length; i += 1) { printTrace('Connecting to service protocol: ${observatoryUris[i]}'); @@ -133,17 +134,20 @@ } Future<void> refreshViews() async { - if (vmServices == null || vmServices.isEmpty) + if (vmServices == null || vmServices.isEmpty) { return Future<void>.value(null); + } final List<Future<void>> futures = <Future<void>>[]; - for (VMService service in vmServices) + for (VMService service in vmServices) { futures.add(service.vm.refreshViews(waitForViews: true)); + } await Future.wait(futures); } List<FlutterView> get views { - if (vmServices == null) + if (vmServices == null) { return <FlutterView>[]; + } return vmServices .where((VMService service) => !service.isClosed) @@ -158,8 +162,9 @@ } Future<void> getVMs() async { - for (VMService service in vmServices) + for (VMService service in vmServices) { await service.getVM(); + } } Future<void> exitApps() async { @@ -168,8 +173,9 @@ return; } final List<FlutterView> flutterViews = views; - if (flutterViews == null || flutterViews.isEmpty) + if (flutterViews == null || flutterViews.isEmpty) { return; + } final List<Future<void>> futures = <Future<void>>[]; // If any of the flutter views are paused, we might not be able to // cleanly exit since the service extension may not have been registered. @@ -237,48 +243,57 @@ } Future<void> debugDumpApp() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterDebugDumpApp(); + } } Future<void> debugDumpRenderTree() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterDebugDumpRenderTree(); + } } Future<void> debugDumpLayerTree() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterDebugDumpLayerTree(); + } } Future<void> debugDumpSemanticsTreeInTraversalOrder() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterDebugDumpSemanticsTreeInTraversalOrder(); + } } Future<void> debugDumpSemanticsTreeInInverseHitTestOrder() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterDebugDumpSemanticsTreeInInverseHitTestOrder(); + } } Future<void> toggleDebugPaintSizeEnabled() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterToggleDebugPaintSizeEnabled(); + } } Future<void> toggleDebugCheckElevationsEnabled() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterToggleDebugCheckElevationsEnabled(); + } } Future<void> debugTogglePerformanceOverlayOverride() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterTogglePerformanceOverlayOverride(); + } } Future<void> toggleWidgetInspector() async { - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterToggleWidgetInspector(); + } } Future<void> toggleProfileWidgetBuilds() async { @@ -298,8 +313,9 @@ to = 'iOS'; break; } - for (FlutterView view in views) + for (FlutterView view in views) { await view.uiIsolate.flutterPlatformOverride(to); + } return to; } @@ -313,14 +329,16 @@ return; } _loggingSubscription = logStream.listen((String line) { - if (!line.contains('Observatory listening on http')) + if (!line.contains('Observatory listening on http')) { printStatus(line, wrap: false); + } }); } Future<void> stopEchoingDeviceLog() async { - if (_loggingSubscription == null) + if (_loggingSubscription == null) { return; + } await _loggingSubscription.cancel(); _loggingSubscription = null; } @@ -346,8 +364,9 @@ if (package == null) { String message = 'No application found for $targetPlatform.'; final String hint = await getMissingPackageHintForPlatform(targetPlatform); - if (hint != null) + if (hint != null) { message += '\n$hint'; + } printError(message); return 1; } @@ -405,15 +424,17 @@ if (package == null) { String message = 'No application found for $targetPlatform.'; final String hint = await getMissingPackageHintForPlatform(targetPlatform); - if (hint != null) + if (hint != null) { message += '\n$hint'; + } printError(message); return 1; } final Map<String, dynamic> platformArgs = <String, dynamic>{}; - if (coldRunner.traceStartup != null) + if (coldRunner.traceStartup != null) { platformArgs['trace-startup'] = coldRunner.traceStartup; + } startEchoingDeviceLog(); @@ -483,10 +504,11 @@ } Future<void> updateReloadStatus(bool wasReloadSuccessful) async { - if (wasReloadSuccessful) + if (wasReloadSuccessful) { generator?.accept(); - else + } else { await generator?.reject(); + } } } @@ -635,63 +657,73 @@ Future<void> refreshViews() async { final List<Future<void>> futures = <Future<void>>[]; - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { futures.add(device.refreshViews()); + } await Future.wait(futures); } Future<void> debugDumpApp() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.debugDumpApp(); + } } Future<void> debugDumpRenderTree() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.debugDumpRenderTree(); + } } Future<void> debugDumpLayerTree() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.debugDumpLayerTree(); + } } Future<void> debugDumpSemanticsTreeInTraversalOrder() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.debugDumpSemanticsTreeInTraversalOrder(); + } } Future<void> debugDumpSemanticsTreeInInverseHitTestOrder() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.debugDumpSemanticsTreeInInverseHitTestOrder(); + } } Future<void> debugToggleDebugPaintSizeEnabled() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.toggleDebugPaintSizeEnabled(); + } } Future<void> debugToggleDebugCheckElevationsEnabled() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.toggleDebugCheckElevationsEnabled(); + } } Future<void> debugTogglePerformanceOverlayOverride() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.debugTogglePerformanceOverlayOverride(); + } } Future<void> debugToggleWidgetInspector() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { await device.toggleWidgetInspector(); + } } Future<void> debugToggleProfileWidgetBuilds() async { @@ -716,8 +748,9 @@ if (supportsServiceProtocol && isRunningDebug) { await device.refreshViews(); try { - for (FlutterView view in device.views) + for (FlutterView view in device.views) { await view.uiIsolate.flutterDebugAllowBanner(false); + } } catch (error) { status.cancel(); printError('Error communicating with Flutter on the device: $error'); @@ -729,8 +762,9 @@ } finally { if (supportsServiceProtocol && isRunningDebug) { try { - for (FlutterView view in device.views) + for (FlutterView view in device.views) { await view.uiIsolate.flutterDebugAllowBanner(true); + } } catch (error) { status.cancel(); printError('Error communicating with Flutter on the device: $error'); @@ -751,8 +785,9 @@ await refreshViews(); final String from = await flutterDevices[0].views[0].uiIsolate.flutterPlatformOverride(); String to; - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { to = await device.togglePlatform(from: from); + } printStatus('Switched operating system to $to'); } @@ -773,8 +808,9 @@ Restart restart, CompileExpression compileExpression, }) async { - if (!debuggingOptions.debuggingEnabled) + if (!debuggingOptions.debuggingEnabled) { throw 'The service protocol is not enabled.'; + } bool viewFound = false; for (FlutterDevice device in flutterDevices) { @@ -785,12 +821,14 @@ ); await device.getVMs(); await device.refreshViews(); - if (device.views.isNotEmpty) + if (device.views.isNotEmpty) { viewFound = true; + } } if (!viewFound) { - if (flutterDevices.length == 1) + if (flutterDevices.length == 1) { throw 'No Flutter view is available on ${flutterDevices.first.device.name}.'; + } throw 'No Flutter view is available on any device ' '(${flutterDevices.map<String>((FlutterDevice device) => device.device.name).join(', ')}).'; } @@ -824,15 +862,17 @@ // User requested the application exit. return; } - if (_finished.isCompleted) + if (_finished.isCompleted) { return; + } printStatus('Lost connection to device.'); _finished.complete(0); } void appFinished() { - if (_finished.isCompleted) + if (_finished.isCompleted) { return; + } printStatus('Application finished.'); _finished.complete(0); } @@ -854,8 +894,9 @@ Future<void> exitApp() async { final List<Future<void>> futures = <Future<void>>[]; - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { futures.add(device.exitApps()); + } await Future.wait(futures); appFinished(); } @@ -913,10 +954,10 @@ String findMainDartFile([ String target ]) { target ??= ''; final String targetPath = fs.path.absolute(target); - if (fs.isDirectorySync(targetPath)) + if (fs.isDirectorySync(targetPath)) { return fs.path.join(targetPath, 'lib', 'main.dart'); - else - return targetPath; + } + return targetPath; } Future<String> getMissingPackageHintForPlatform(TargetPlatform platform) async { @@ -965,8 +1006,9 @@ _cleanUp(signal); io.exit(0); }); - if (!residentRunner.supportsServiceProtocol || !residentRunner.supportsRestart) + if (!residentRunner.supportsServiceProtocol || !residentRunner.supportsRestart) { return; + } io.ProcessSignal.SIGUSR1.watch().listen(_handleSignal); io.ProcessSignal.SIGUSR2.watch().listen(_handleSignal); } @@ -1038,8 +1080,9 @@ return true; case 's': for (FlutterDevice device in residentRunner.flutterDevices) { - if (device.device.supportsScreenshot) + if (device.device.supportsScreenshot) { await residentRunner.screenshot(device); + } } return true; case 'r':
diff --git a/packages/flutter_tools/lib/src/run_cold.dart b/packages/flutter_tools/lib/src/run_cold.dart index ddfde2e..f8e5cd4 100644 --- a/packages/flutter_tools/lib/src/run_cold.dart +++ b/packages/flutter_tools/lib/src/run_cold.dart
@@ -52,8 +52,9 @@ if (!prebuiltMode) { if (!fs.isFileSync(mainPath)) { String message = 'Tried to run $mainPath, but that file does not exist.'; - if (target == null) + if (target == null) { message += '\nConsider using the -t option to specify the Dart file to start.'; + } printError(message); return 1; } @@ -64,8 +65,9 @@ coldRunner: this, route: route, ); - if (result != 0) + if (result != 0) { return result; + } } // Connect to observatory. @@ -89,8 +91,9 @@ printTrace('Application running.'); for (FlutterDevice device in flutterDevices) { - if (device.vmServices == null) + if (device.vmServices == null) { continue; + } device.initLogReader(); await device.refreshViews(); printTrace('Connected to ${device.device.name}'); @@ -111,8 +114,9 @@ appStartedCompleter?.complete(); - if (stayResident && !traceStartup) + if (stayResident && !traceStartup) { return waitForAppToFinish(); + } await cleanupAtFinish(); return 0; } @@ -203,8 +207,9 @@ Future<void> preExit() async { for (FlutterDevice device in flutterDevices) { // If we're running in release mode, stop the app using the device logic. - if (device.vmServices == null || device.vmServices.isEmpty) + if (device.vmServices == null || device.vmServices.isEmpty) { await device.device.stopApp(device.package); + } } await super.preExit(); }
diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index f9b590a..c577ec2 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart
@@ -164,8 +164,9 @@ return 2; } - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { device.initLogReader(); + } try { final List<Uri> baseUris = await _initDevFS(); if (connectionInfoCompleter != null) { @@ -188,17 +189,20 @@ 'hotReloadInitialDevFSSyncMilliseconds', initialUpdateDevFSsTimer.elapsed.inMilliseconds, ); - if (!devfsResult.success) + if (!devfsResult.success) { return 3; + } await refreshViews(); for (FlutterDevice device in flutterDevices) { // VM must have accepted the kernel binary, there will be no reload // report, so we let incremental compiler know that source code was accepted. - if (device.generator != null) + if (device.generator != null) { device.generator.accept(); - for (FlutterView view in device.views) + } + for (FlutterView view in device.views) { printTrace('Connected to $view.'); + } } appStartedCompleter?.complete(); @@ -226,8 +230,9 @@ } int result = 0; - if (stayResident) + if (stayResident) { result = await waitForAppToFinish(); + } await cleanupAtFinish(); return result; } @@ -240,8 +245,9 @@ }) async { if (!fs.isFileSync(mainPath)) { String message = 'Tried to run $mainPath, but that file does not exist.'; - if (target == null) + if (target == null) { message += '\nConsider using the -t option to specify the Dart file to start.'; + } printError(message); return 1; } @@ -284,8 +290,9 @@ if (rebuildBundle) { printTrace('Updating assets'); final int result = await assetBundle.build(); - if (result != 0) + if (result != 0) { return UpdateFSReport(success: false); + } } // Picking up first device's compiler as a source of truth - compilers @@ -315,8 +322,9 @@ } void _resetDirtyAssets() { - for (FlutterDevice device in flutterDevices) + for (FlutterDevice device in flutterDevices) { device.devFS.assetPathsToEvict.clear(); + } } Future<void> _cleanupDevFS() async { @@ -343,8 +351,9 @@ Uri assetsDirectoryUri, ) { final List<Future<void>> futures = <Future<void>>[]; - for (FlutterView view in device.views) + for (FlutterView view in device.views) { futures.add(view.runFromSource(entryUri, packagesUri, assetsDirectoryUri)); + } final Completer<void> completer = Completer<void>(); Future.wait(futures).whenComplete(() { completer.complete(null); }); return completer.future; @@ -367,9 +376,11 @@ await Future.wait(futures); if (benchmarkMode) { futures.clear(); - for (FlutterDevice device in flutterDevices) - for (FlutterView view in device.views) + for (FlutterDevice device in flutterDevices) { + for (FlutterView view in device.views) { futures.add(view.flushUIThreadTasks()); + } + } await Future.wait(futures); } } @@ -469,8 +480,9 @@ bool printErrors = true, }) { if (reloadReport == null) { - if (printErrors) + if (printErrors) { printError('Hot reload did not receive reload report.'); + } return false; } if (!(reloadReport['type'] == 'ReloadReport' && @@ -486,15 +498,17 @@ ) ) )) { - if (printErrors) + if (printErrors) { printError('Hot reload received invalid response: $reloadReport'); + } return false; } if (!reloadReport['success']) { if (printErrors) { printError('Hot reload was rejected:'); - for (Map<String, dynamic> notice in reloadReport['details']['notices']) + for (Map<String, dynamic> notice in reloadReport['details']['notices']) { printError('${notice['message']}'); + } } return false; } @@ -806,8 +820,9 @@ } } if (pausedIsolatesFound > 0) { - if (onSlow != null) + if (onSlow != null) { onSlow('${_describePausedIsolates(pausedIsolatesFound, serviceEventKind)}; interface might not update.'); + } if (reassembleViews.isEmpty) { printTrace('Skipping reassemble because all isolates are paused.'); return OperationResult(OperationResult.ok.code, reloadMessage); @@ -860,8 +875,9 @@ return; } shouldReportReloadTime = false; - if (onSlow != null) + if (onSlow != null) { onSlow('${_describePausedIsolates(postReloadPausedIsolatesFound, serviceEventKind)}.'); + } }, ); // Record time it took for Flutter to reassemble the application. @@ -898,8 +914,9 @@ _addBenchmarkData('hotReloadMillisecondsToFrame', reloadInMs); } // Only report timings if we reloaded a single view without any errors. - if ((reassembleViews.length == 1) && !failedReassemble && shouldReportReloadTime) + if ((reassembleViews.length == 1) && !failedReassemble && shouldReportReloadTime) { flutterUsage.sendTiming('hot', 'reload', reloadDuration); + } return OperationResult( failedReassemble ? 1 : OperationResult.ok.code, reloadMessage, @@ -964,8 +981,9 @@ printStatus(message); for (FlutterDevice device in flutterDevices) { final String dname = device.device.name; - for (Uri uri in device.observatoryUris) + for (Uri uri in device.observatoryUris) { printStatus('An Observatory debugger and profiler on $dname is available at: $uri'); + } } final String quitMessage = _didAttach ? 'To detach, press "d"; to quit, press "q".' @@ -981,8 +999,9 @@ Future<void> _evictDirtyAssets() { final List<Future<Map<String, dynamic>>> futures = <Future<Map<String, dynamic>>>[]; for (FlutterDevice device in flutterDevices) { - if (device.devFS.assetPathsToEvict.isEmpty) + if (device.devFS.assetPathsToEvict.isEmpty) { continue; + } if (device.views.first.uiIsolate == null) { printError('Application isolate not found for $device'); continue;
diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index 55d05d0..e22c692 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart
@@ -158,12 +158,13 @@ } String get targetFile { - if (argResults.wasParsed('target')) + if (argResults.wasParsed('target')) { return argResults['target']; - else if (argResults.rest.isNotEmpty) + } + if (argResults.rest.isNotEmpty) { return argResults.rest.first; - else - return bundle.defaultMainPath; + } + return bundle.defaultMainPath; } void usesPubOption() { @@ -299,8 +300,9 @@ BuildMode getBuildMode() { final List<bool> modeFlags = <bool>[argResults['debug'], argResults['profile'], argResults['release']]; - if (modeFlags.where((bool flag) => flag).length > 1) + if (modeFlags.where((bool flag) => flag).length > 1) { throw UsageException('Only one of --debug, --profile, or --release can be specified.', null); + } if (argResults['debug']) { return BuildMode.debug; } @@ -557,8 +559,9 @@ /// then print an error message and return null. Future<Device> findTargetDevice() async { List<Device> deviceList = await findAllTargetDevices(); - if (deviceList == null) + if (deviceList == null) { return null; + } if (deviceList.length > 1) { printStatus(userMessages.flutterSpecifyDevice); deviceList = await deviceManager.getAllConnectedDevices().toList(); @@ -585,15 +588,17 @@ // Validate the current package map only if we will not be running "pub get" later. if (parent?.name != 'pub' && !(_usesPubOption && argResults['pub'])) { final String error = PackageMap(PackageMap.globalPackagesPath).checkValid(); - if (error != null) + if (error != null) { throw ToolExit(error); + } } } if (_usesTargetOption) { final String targetPath = targetFile; - if (!fs.isFileSync(targetPath)) + if (!fs.isFileSync(targetPath)) { throw ToolExit(userMessages.flutterTargetFileMissing(targetPath)); + } } }
diff --git a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart index 5a16863..81227cd 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart
@@ -121,8 +121,9 @@ 'Defaults to \$$kFlutterRootEnvironmentVariableName if set, otherwise uses the parent ' 'of the directory that the "flutter" script itself is in.'); - if (verboseHelp) + if (verboseHelp) { argParser.addSeparator('Local build selection options (not normally required):'); + } argParser.addOption('local-engine-src-path', hide: !verboseHelp, @@ -138,8 +139,9 @@ 'Use this to select a specific version of the engine if you have built multiple engine targets.\n' 'This path is relative to --local-engine-src-path/out.'); - if (verboseHelp) + if (verboseHelp) { argParser.addSeparator('Options for testing the "flutter" tool itself:'); + } argParser.addOption('record-to', hide: !verboseHelp, @@ -179,11 +181,13 @@ } static String get defaultFlutterRoot { - if (platform.environment.containsKey(kFlutterRootEnvironmentVariableName)) + if (platform.environment.containsKey(kFlutterRootEnvironmentVariableName)) { return platform.environment[kFlutterRootEnvironmentVariableName]; + } try { - if (platform.script.scheme == 'data') + if (platform.script.scheme == 'data') { return '../..'; // we're running as a test + } if (platform.script.scheme == 'package') { final String packageConfigPath = Uri.parse(platform.packageConfig).toFilePath(); @@ -191,16 +195,20 @@ } final String script = platform.script.toFilePath(); - if (fs.path.basename(script) == kSnapshotFileName) + if (fs.path.basename(script) == kSnapshotFileName) { return fs.path.dirname(fs.path.dirname(fs.path.dirname(script))); - if (fs.path.basename(script) == kFlutterToolsScriptFileName) + } + if (fs.path.basename(script) == kFlutterToolsScriptFileName) { return fs.path.dirname(fs.path.dirname(fs.path.dirname(fs.path.dirname(script)))); + } // If run from a bare script within the repo. - if (script.contains('flutter/packages/')) + if (script.contains('flutter/packages/')) { return script.substring(0, script.indexOf('flutter/packages/') + 8); - if (script.contains('flutter/examples/')) + } + if (script.contains('flutter/examples/')) { return script.substring(0, script.indexOf('flutter/examples/') + 8); + } } catch (error) { // we don't have a logger at the time this is run // (which is why we don't use printTrace here) @@ -236,8 +244,9 @@ Future<void> run(Iterable<String> args) { // Have an invocation of 'build' print out it's sub-commands. // TODO(ianh): Move this to the Build command itself somehow. - if (args.length == 1 && args.first == 'build') + if (args.length == 1 && args.first == 'build') { args = <String>['build', '-h']; + } return super.run(args); } @@ -318,8 +327,9 @@ if (recordTo != null) { recordTo = recordTo.trim(); - if (recordTo.isEmpty) + if (recordTo.isEmpty) { throwToolExit(userMessages.runnerNoRecordTo); + } contextOverrides.addAll(<Type, dynamic>{ ProcessManager: getRecordingProcessManager(recordTo), FileSystem: getRecordingFileSystem(recordTo), @@ -330,8 +340,9 @@ if (replayFrom != null) { replayFrom = replayFrom.trim(); - if (replayFrom.isEmpty) + if (replayFrom.isEmpty) { throwToolExit(userMessages.runnerNoReplayFrom); + } contextOverrides.addAll(<Type, dynamic>{ ProcessManager: await getReplayProcessManager(replayFrom), FileSystem: getReplayFileSystem(replayFrom), @@ -360,11 +371,13 @@ body: () async { logger.quiet = topLevelResults['quiet']; - if (platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') + if (platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') { await Cache.lock(); + } - if (topLevelResults['suppress-analytics']) + if (topLevelResults['suppress-analytics']) { flutterUsage.suppressAnalytics = true; + } _checkFlutterCopy(); try { @@ -378,8 +391,9 @@ await FlutterVersion.instance.checkFlutterVersionFreshness(); } - if (topLevelResults.wasParsed('packages')) + if (topLevelResults.wasParsed('packages')) { PackageMap.globalPackagesPath = fs.path.normalize(fs.path.absolute(topLevelResults['packages'])); + } // See if the user specified a specific device. deviceManager.specifiedDeviceId = topLevelResults['device-id']; @@ -405,8 +419,9 @@ } String _tryEnginePath(String enginePath) { - if (fs.isDirectorySync(fs.path.join(enginePath, 'out'))) + if (fs.isDirectorySync(fs.path.join(enginePath, 'out'))) { return enginePath; + } return null; } @@ -505,8 +520,9 @@ } static List<String> _gatherProjectPaths(String rootPath) { - if (fs.isFileSync(fs.path.join(rootPath, '.dartignore'))) + if (fs.isFileSync(fs.path.join(rootPath, '.dartignore'))) { return <String>[]; + } final List<String> projectPaths = fs.directory(rootPath) @@ -519,8 +535,9 @@ }) .toList(); - if (fs.isFileSync(fs.path.join(rootPath, 'pubspec.yaml'))) + if (fs.isFileSync(fs.path.join(rootPath, 'pubspec.yaml'))) { projectPaths.add(rootPath); + } return projectPaths; } @@ -541,8 +558,9 @@ } final String parent = fs.path.dirname(directory); - if (parent == directory) + if (parent == directory) { break; + } directory = parent; }
diff --git a/packages/flutter_tools/lib/src/services.dart b/packages/flutter_tools/lib/src/services.dart index 7cd0a58..51a51dc 100644 --- a/packages/flutter_tools/lib/src/services.dart +++ b/packages/flutter_tools/lib/src/services.dart
@@ -17,8 +17,9 @@ dynamic _loadYamlFile(String path) { printTrace("Looking for YAML at '$path'"); - if (!fs.isFileSync(path)) + if (!fs.isFileSync(path)) { return null; + } final String manifestString = fs.file(path).readAsStringSync(); return loadYaml(manifestString); } @@ -69,8 +70,9 @@ } if (jars != null && serviceConfig['jars'] is Iterable) { - for (String jar in serviceConfig['jars']) + for (String jar in serviceConfig['jars']) { jars.add(fs.file(await getServiceFromUrl(jar, serviceRoot, service))); + } } } }
diff --git a/packages/flutter_tools/lib/src/template.dart b/packages/flutter_tools/lib/src/template.dart index 73701e7..5a9199a 100644 --- a/packages/flutter_tools/lib/src/template.dart +++ b/packages/flutter_tools/lib/src/template.dart
@@ -91,8 +91,9 @@ if (match != null) { final String platform = match.group(1); final String language = context['${platform}Language']; - if (language != match.group(2)) + if (language != match.group(2)) { return null; + } relativeDestinationPath = relativeDestinationPath.replaceAll('$platform-$language.tmpl', platform); } // Only build a web project if explicitly asked. @@ -114,21 +115,25 @@ finalDestinationPath = finalDestinationPath .replaceAll('androidIdentifier', androidIdentifier.replaceAll('.', pathSeparator)); } - if (projectName != null) + if (projectName != null) { finalDestinationPath = finalDestinationPath.replaceAll('projectName', projectName); - if (pluginClass != null) + } + if (pluginClass != null) { finalDestinationPath = finalDestinationPath.replaceAll('pluginClass', pluginClass); + } return finalDestinationPath; } _templateFilePaths.forEach((String relativeDestinationPath, String absoluteSourcePath) { final bool withRootModule = context['withRootModule'] ?? false; - if (!withRootModule && absoluteSourcePath.contains('flutter_root')) + if (!withRootModule && absoluteSourcePath.contains('flutter_root')) { return; + } final String finalDestinationPath = renderPath(relativeDestinationPath); - if (finalDestinationPath == null) + if (finalDestinationPath == null) { return; + } final File finalDestinationFile = fs.file(finalDestinationPath); final String relativePathForLogging = fs.path.relative(finalDestinationFile.path); @@ -137,17 +142,20 @@ if (finalDestinationFile.existsSync()) { if (overwriteExisting) { finalDestinationFile.deleteSync(recursive: true); - if (printStatusWhenWriting) + if (printStatusWhenWriting) { printStatus(' $relativePathForLogging (overwritten)'); + } } else { // The file exists but we cannot overwrite it, move on. - if (printStatusWhenWriting) + if (printStatusWhenWriting) { printTrace(' $relativePathForLogging (existing - skipped)'); + } return; } } else { - if (printStatusWhenWriting) + if (printStatusWhenWriting) { printStatus(' $relativePathForLogging (created)'); + } } fileCount++;
diff --git a/packages/flutter_tools/lib/src/test/coverage_collector.dart b/packages/flutter_tools/lib/src/test/coverage_collector.dart index 1ce8a9d..ed3bdf6 100644 --- a/packages/flutter_tools/lib/src/test/coverage_collector.dart +++ b/packages/flutter_tools/lib/src/test/coverage_collector.dart
@@ -78,8 +78,9 @@ }); final Future<void> collectionComplete = collect(observatoryUri, libraryPredicate) .then<void>((Map<String, dynamic> result) { - if (result == null) + if (result == null) { throw Exception('Failed to collect coverage.'); + } data = result; }); await Future.any<void>(<Future<void>>[ processComplete, collectionComplete ]); @@ -122,8 +123,9 @@ ); status.stop(); printTrace('coverage information collection complete'); - if (coverageData == null) + if (coverageData == null) { return false; + } final File coverageFile = fs.file(coveragePath) ..createSync(recursive: true) @@ -139,10 +141,11 @@ if (os.which('lcov') == null) { String installMessage = 'Please install lcov.'; - if (platform.isLinux) + if (platform.isLinux) { installMessage = 'Consider running "sudo apt-get install lcov".'; - else if (platform.isMacOS) + } else if (platform.isMacOS) { installMessage = 'Consider running "brew install lcov".'; + } printError('Missing "lcov" tool. Unable to merge coverage data.\n$installMessage'); return false; } @@ -156,8 +159,9 @@ '--add-tracefile', sourceFile.path, '--output-file', coverageFile.path, ]); - if (result.exitCode != 0) + if (result.exitCode != 0) { return false; + } } finally { tempDir.deleteSync(recursive: true); }
diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 77a7b4e..10d1368 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart
@@ -418,8 +418,9 @@ }); final Completer<WebSocket> webSocket = Completer<WebSocket>(); server.listen((HttpRequest request) { - if (!webSocket.isCompleted) - webSocket.complete(WebSocketTransformer.upgrade(request)); + if (!webSocket.isCompleted) { + webSocket.complete(WebSocketTransformer.upgrade(request)); + } }, onError: (dynamic error, dynamic stack) { // If you reach here, it's unlikely we're going to be able to really handle this well. @@ -823,8 +824,9 @@ // // I mention this only so that you won't be tempted, as I was, to apply // the obvious simplification to this code and remove this entire feature. - if (observatoryPort != null) + if (observatoryPort != null) { command.add('--observatory-port=$observatoryPort'); + } if (startPaused) { command.add('--start-paused'); }
diff --git a/packages/flutter_tools/lib/src/test/runner.dart b/packages/flutter_tools/lib/src/test/runner.dart index 67aed19..a4e5111 100644 --- a/packages/flutter_tools/lib/src/test/runner.dart +++ b/packages/flutter_tools/lib/src/test/runner.dart
@@ -96,8 +96,9 @@ // Configure package:test to use the Flutter engine for child processes. final String shellPath = artifacts.getArtifactPath(Artifact.flutterTester); - if (!processManager.canRun(shellPath)) + if (!processManager.canRun(shellPath)) { throwToolExit('Cannot find Flutter shell at $shellPath'); + } final InternetAddressType serverType = ipv6 ? InternetAddressType.IPv6 : InternetAddressType.IPv4;
diff --git a/packages/flutter_tools/lib/src/tester/flutter_tester.dart b/packages/flutter_tools/lib/src/tester/flutter_tester.dart index 0bc0e57..50870f2 100644 --- a/packages/flutter_tools/lib/src/tester/flutter_tester.dart +++ b/packages/flutter_tools/lib/src/tester/flutter_tester.dart
@@ -115,8 +115,9 @@ } final String shellPath = artifacts.getArtifactPath(Artifact.flutterTester); - if (!fs.isFileSync(shellPath)) + if (!fs.isFileSync(shellPath)) { throwToolExit('Cannot find Flutter shell at $shellPath'); + } final List<String> command = <String>[ shellPath, @@ -126,12 +127,15 @@ '--packages=${PackageMap.globalPackagesPath}', ]; if (debuggingOptions.debuggingEnabled) { - if (debuggingOptions.startPaused) + if (debuggingOptions.startPaused) { command.add('--start-paused'); - if (debuggingOptions.disableServiceAuthCodes) + } + if (debuggingOptions.disableServiceAuthCodes) { command.add('--disable-service-auth-codes'); - if (debuggingOptions.hasObservatoryPort) + } + if (debuggingOptions.hasObservatoryPort) { command.add('--observatory-port=${debuggingOptions.observatoryPort}'); + } } // Build assets and perform initial compilation. @@ -175,8 +179,9 @@ _logReader.addLine(line); }); - if (!debuggingOptions.debuggingEnabled) + if (!debuggingOptions.debuggingEnabled) { return LaunchResult.succeeded(); + } final ProtocolDiscovery observatoryDiscovery = ProtocolDiscovery.observatory( getLogReader(), @@ -248,8 +253,9 @@ class _NoopPortForwarder extends DevicePortForwarder { @override Future<int> forward(int devicePort, { int hostPort }) { - if (hostPort != null && hostPort != devicePort) + if (hostPort != null && hostPort != devicePort) { throw 'Forwarding to a different port is not supported by flutter tester'; + } return Future<int>.value(devicePort); }
diff --git a/packages/flutter_tools/lib/src/tracing.dart b/packages/flutter_tools/lib/src/tracing.dart index f208305..bba004a 100644 --- a/packages/flutter_tools/lib/src/tracing.dart +++ b/packages/flutter_tools/lib/src/tracing.dart
@@ -57,8 +57,9 @@ break; } } - if (!done) + if (!done) { await whenFirstFrameRendered.future; + } } catch (exception) { status.cancel(); rethrow; @@ -138,8 +139,9 @@ final int timeToFirstFrameMicros = firstFrameBuiltTimestampMicros - engineEnterTimestampMicros; traceInfo['timeToFirstFrameMicros'] = timeToFirstFrameMicros; message = 'Time to first frame: ${timeToFirstFrameMicros ~/ 1000}ms.'; - if (frameworkInitTimestampMicros != null) + if (frameworkInitTimestampMicros != null) { traceInfo['timeAfterFrameworkInitMicros'] = firstFrameBuiltTimestampMicros - frameworkInitTimestampMicros; + } } traceInfoFile.writeAsStringSync(toPrettyJson(traceInfo));
diff --git a/packages/flutter_tools/lib/src/version.dart b/packages/flutter_tools/lib/src/version.dart index df4185e..7a73194 100644 --- a/packages/flutter_tools/lib/src/version.dart +++ b/packages/flutter_tools/lib/src/version.dart
@@ -177,16 +177,18 @@ .split('\n') .map<String>((String name) => name.trim()) // to account for OS-specific line-breaks .toList(); - if (remotes.contains(_versionCheckRemote)) + if (remotes.contains(_versionCheckRemote)) { await _run(<String>['git', 'remote', 'remove', _versionCheckRemote]); + } } static FlutterVersion get instance => context.get<FlutterVersion>(); /// Return a short string for the version (e.g. `master/0.0.59-pre.92`, `scroll_refactor/a76bc8e22b`). String getVersionString({ bool redactUnknownBranches = false }) { - if (frameworkVersion != 'unknown') + if (frameworkVersion != 'unknown') { return '${getBranchName(redactUnknownBranches: redactUnknownBranches)}/$frameworkVersion'; + } return '${getBranchName(redactUnknownBranches: redactUnknownBranches)}/$frameworkRevisionShort'; } @@ -201,8 +203,10 @@ }(); if (redactUnknownBranches || _branch.isEmpty) { // Only return the branch names we know about; arbitrary branch names might contain PII. - if (!officialChannels.contains(_branch) && !obsoleteBranches.containsKey(_branch)) + if (!officialChannels.contains(_branch) && + !obsoleteBranches.containsKey(_branch)) { return '[user-branch]'; + } } return _branch; } @@ -378,8 +382,9 @@ final Duration timeSinceLastCheck = _clock.now().difference(versionCheckStamp.lastTimeVersionWasChecked); // Don't ping the server too often. Return cached value if it's fresh. - if (timeSinceLastCheck < checkAgeConsideredUpToDate) + if (timeSinceLastCheck < checkAgeConsideredUpToDate) { return versionCheckStamp.lastKnownRemoteVersion; + } } // Cache is empty or it's been a while since the last server ping. Ping the server. @@ -465,14 +470,17 @@ }) async { final Map<String, String> jsonData = toJson(); - if (newTimeVersionWasChecked != null) + if (newTimeVersionWasChecked != null) { jsonData['lastTimeVersionWasChecked'] = '$newTimeVersionWasChecked'; + } - if (newKnownRemoteVersion != null) + if (newKnownRemoteVersion != null) { jsonData['lastKnownRemoteVersion'] = '$newKnownRemoteVersion'; + } - if (newTimeWarningWasPrinted != null) + if (newTimeWarningWasPrinted != null) { jsonData['lastTimeWarningWasPrinted'] = '$newTimeWarningWasPrinted'; + } const JsonEncoder prettyJsonEncoder = JsonEncoder.withIndent(' '); Cache.instance.setStampFor(flutterVersionCheckStampFile, prettyJsonEncoder.convert(jsonData)); @@ -489,14 +497,17 @@ final Map<String, String> jsonData = <String, String>{}; - if (updateTimeVersionWasChecked != null) + if (updateTimeVersionWasChecked != null) { jsonData['lastTimeVersionWasChecked'] = '$updateTimeVersionWasChecked'; + } - if (updateKnownRemoteVersion != null) + if (updateKnownRemoteVersion != null) { jsonData['lastKnownRemoteVersion'] = '$updateKnownRemoteVersion'; + } - if (updateTimeWarningWasPrinted != null) + if (updateTimeWarningWasPrinted != null) { jsonData['lastTimeWarningWasPrinted'] = '$updateTimeWarningWasPrinted'; + } return jsonData; } @@ -524,8 +535,9 @@ String _runSync(List<String> command, { bool lenient = true }) { final ProcessResult results = processManager.runSync(command, workingDirectory: Cache.flutterRoot); - if (results.exitCode == 0) + if (results.exitCode == 0) { return results.stdout.trim(); + } if (!lenient) { throw VersionCheckError( @@ -551,8 +563,9 @@ Future<String> _run(List<String> command) async { final ProcessResult results = await processManager.run(command, workingDirectory: Cache.flutterRoot); - if (results.exitCode == 0) + if (results.exitCode == 0) { return results.stdout.trim(); + } throw VersionCheckError( 'Command exited with code ${results.exitCode}: ${command.join(' ')}\n' @@ -561,8 +574,9 @@ } String _shortGitRevision(String revision) { - if (revision == null) + if (revision == null) { return ''; + } return revision.length > 10 ? revision.substring(0, 10) : revision; } @@ -610,15 +624,18 @@ } String frameworkVersionFor(String revision) { - if (x == null || y == null || z == null || !revision.startsWith(hash)) + if (x == null || y == null || z == null || !revision.startsWith(hash)) { return '0.0.0-unknown'; + } if (commits == 0) { - if (hotfix != null) + if (hotfix != null) { return '$x.$y.$z+hotfix.$hotfix'; + } return '$x.$y.$z'; } - if (hotfix != null) + if (hotfix != null) { return '$x.$y.$z+hotfix.${hotfix + 1}-pre.$commits'; + } return '$x.$y.${z + 1}-pre.$commits'; } }
diff --git a/packages/flutter_tools/lib/src/vmservice.dart b/packages/flutter_tools/lib/src/vmservice.dart index d095b3e..a5af8de 100644 --- a/packages/flutter_tools/lib/src/vmservice.dart +++ b/packages/flutter_tools/lib/src/vmservice.dart
@@ -72,15 +72,17 @@ printTrace('Exception attempting to connect to Observatory: $e'); printTrace('This was attempt #$attempts. Will retry in $delay.'); - if (attempts == 10) + if (attempts == 10) { printStatus('This is taking longer than expected...'); + } // Delay next attempt. await Future<void>.delayed(delay); // Back off exponentially, up to 1600ms per attempt. - if (delay < const Duration(seconds: 1)) + if (delay < const Duration(seconds: 1)) { delay *= 2; + } } final WebSocketConnector constructor = context.get<WebSocketConnector>() ?? io.WebSocket.connect; @@ -121,12 +123,15 @@ final bool force = params.asMap['force'] ?? false; final bool pause = params.asMap['pause'] ?? false; - if (isolateId is! String || isolateId.isEmpty) + if (isolateId is! String || isolateId.isEmpty) { throw rpc.RpcException.invalidParams('Invalid \'isolateId\': $isolateId'); - if (force is! bool) + } + if (force is! bool) { throw rpc.RpcException.invalidParams('Invalid \'force\': $force'); - if (pause is! bool) + } + if (pause is! bool) { throw rpc.RpcException.invalidParams('Invalid \'pause\': $pause'); + } try { await reloadSources(isolateId, force: force, pause: pause); @@ -149,8 +154,9 @@ _peer.registerMethod('hotRestart', (rpc.Parameters params) async { final bool pause = params.asMap['pause'] ?? false; - if (pause is! bool) + if (pause is! bool) { throw rpc.RpcException.invalidParams('Invalid \'pause\': $pause'); + } try { await restart(pause: pause); @@ -185,13 +191,15 @@ if (compileExpression != null) { _peer.registerMethod('compileExpression', (rpc.Parameters params) async { final String isolateId = params['isolateId'].asString; - if (isolateId is! String || isolateId.isEmpty) + if (isolateId is! String || isolateId.isEmpty) { throw rpc.RpcException.invalidParams( 'Invalid \'isolateId\': $isolateId'); + } final String expression = params['expression'].asString; - if (expression is! String || expression.isEmpty) + if (expression is! String || expression.isEmpty) { throw rpc.RpcException.invalidParams( 'Invalid \'expression\': $expression'); + } final List<String> definitions = List<String>.from(params['definitions'].asList); final List<String> typeDefinitions = @@ -399,8 +407,9 @@ dynamic collection, ServiceObjectOwner owner, ) { - if (collection is ServiceMap) + if (collection is ServiceMap) { return; + } if (collection is Map<String, dynamic>) { _upgradeMap(collection, owner); } else if (collection is List) { @@ -444,11 +453,13 @@ ServiceObjectOwner owner, Map<String, dynamic> map, ) { - if (map == null) + if (map == null) { return null; + } - if (!_isServiceMap(map)) + if (!_isServiceMap(map)) { throw VMServiceObjectLoadError('Expected a service map', map); + } final String type = _stripRef(map['type']); @@ -506,8 +517,9 @@ /// If this is not already loaded, load it. Otherwise reload. Future<ServiceObject> load() async { - if (loaded) + if (loaded) { return this; + } return reload(); } @@ -527,8 +539,9 @@ // We should always reload the VM. // We can't reload objects without an id. // We shouldn't reload an immutable and already loaded object. - if (!isVM && (!hasId || (immutable && loaded))) + if (!isVM && (!hasId || (immutable && loaded))) { return this; + } if (_inProgressReload == null) { final Completer<ServiceObject> completer = Completer<ServiceObject>(); @@ -695,8 +708,9 @@ @override void _update(Map<String, dynamic> map, bool mapIsRef) { - if (mapIsRef) + if (mapIsRef) { return; + } // Upgrade the collection. A side effect of this call is that any new // isolates in the map are created and added to the isolate cache. @@ -704,8 +718,9 @@ _loaded = true; _pid = map['pid']; - if (map['_heapAllocatedMemoryUsage'] != null) + if (map['_heapAllocatedMemoryUsage'] != null) { _heapAllocatedMemoryUsage = map['_heapAllocatedMemoryUsage']; + } _maxRSS = map['_maxRSS']; _embedder = map['_embedder']; @@ -766,8 +781,9 @@ void _removeDeadIsolates(List<Isolate> newIsolates) { // Build a set of new isolates. final Set<String> newIsolateSet = <String>{}; - for (Isolate iso in newIsolates) + for (Isolate iso in newIsolates) { newIsolateSet.add(iso.id); + } // Remove any old isolates which no longer exist. final List<String> toRemove = <String>[]; @@ -844,8 +860,9 @@ static String _truncate(String message, int width, String ellipsis) { assert(ellipsis.length < width); - if (message.length <= width) + if (message.length <= width) { return message; + } return message.substring(0, width - ellipsis.length) + ellipsis; } @@ -978,8 +995,9 @@ Future<void> refreshViews({ bool waitForViews = false }) async { assert(waitForViews != null); assert(loaded); - if (!isFlutterEngine) + if (!isFlutterEngine) { return; + } int failCount = 0; while (true) { _viewCache.clear(); @@ -988,11 +1006,13 @@ // This message updates all the views of every isolate. await vmService.vm.invokeRpc<ServiceObject>( '_flutter.listViews', truncateLogs: false); - if (_viewCache.values.isNotEmpty || !waitForViews) + if (_viewCache.values.isNotEmpty || !waitForViews) { return; + } failCount += 1; - if (failCount == 5) // waited 200ms + if (failCount == 5) { // waited 200ms printStatus('Flutter is taking longer than expected to report its views. Still trying...'); + } await Future<void>.delayed(const Duration(milliseconds: 50)); await reload(); } @@ -1005,8 +1025,9 @@ } List<FlutterView> allViewsWithName(String isolateFilter) { - if (_viewCache.values.isEmpty) + if (_viewCache.values.isEmpty) { return null; + } return _viewCache.values.where( (FlutterView v) => v.uiIsolate.name.contains(isolateFilter) ).toList(); @@ -1081,8 +1102,9 @@ @override ServiceObject getFromMap(Map<String, dynamic> map) { - if (map == null) + if (map == null) { return null; + } final String mapType = _stripRef(map['type']); if (mapType == 'Isolate') { // There are sometimes isolate refs in ServiceEvents. @@ -1097,8 +1119,9 @@ } // Build the object from the map directly. serviceObject = ServiceObject._fromMap(this, map); - if ((serviceObject != null) && serviceObject.canCache) + if ((serviceObject != null) && serviceObject.canCache) { _cache[mapId] = serviceObject; + } return serviceObject; } @@ -1135,8 +1158,9 @@ @override void _update(Map<String, dynamic> map, bool mapIsRef) { - if (mapIsRef) + if (mapIsRef) { return; + } _loaded = true; final int startTimeMillis = map['startTime']; @@ -1199,8 +1223,9 @@ return await invokeRpcRaw(method, params: params); } on rpc.RpcException catch (e) { // If an application is not using the framework - if (e.code == rpc_error_code.METHOD_NOT_FOUND) + if (e.code == rpc_error_code.METHOD_NOT_FOUND) { return null; + } rethrow; } } @@ -1279,8 +1304,9 @@ Future<List<int>> flutterDebugSaveCompilationTrace() async { final Map<String, dynamic> result = await invokeFlutterExtensionRpcRaw('ext.flutter.saveCompilationTrace'); - if (result != null && result['value'] is List<dynamic>) + if (result != null && result['value'] is List<dynamic>) { return result['value'].cast<int>(); + } return null; } @@ -1294,8 +1320,9 @@ 'ext.flutter.platformOverride', params: platform != null ? <String, dynamic>{'value': platform} : <String, String>{}, ); - if (result != null && result['value'] is String) + if (result != null && result['value'] is String) { return result['value']; + } return 'unknown'; } @@ -1393,8 +1420,9 @@ // launch errors. if (event.kind == ServiceEvent.kIsolateRunnable) { printTrace('Isolate is runnable.'); - if (!completer.isCompleted) + if (!completer.isCompleted) { completer.complete(); + } } }); await owner.vm.runInView(viewId,
diff --git a/packages/flutter_tools/lib/src/vmservice_record_replay.dart b/packages/flutter_tools/lib/src/vmservice_record_replay.dart index dcf04a2..3bb7b23 100644 --- a/packages/flutter_tools/lib/src/vmservice_record_replay.dart +++ b/packages/flutter_tools/lib/src/vmservice_record_replay.dart
@@ -225,8 +225,9 @@ } void send(_Request request) { - if (!_transactions.containsKey(request.id)) + if (!_transactions.containsKey(request.id)) { throw ArgumentError('No matching invocation found'); + } final _Transaction transaction = _transactions.remove(request.id); // TODO(tvolkert): validate that `transaction.request` matches `request` if (transaction.response == null) { @@ -237,8 +238,9 @@ exit(0); } else { _controller.add(json.encoder.convert(transaction.response.data)); - if (_transactions.isEmpty) + if (_transactions.isEmpty) { _controller.close(); + } } } @@ -266,8 +268,9 @@ @override void add(String data) { - if (_completer.isCompleted) + if (_completer.isCompleted) { throw StateError('Sink already closed'); + } channel.send(_Request.fromString(data)); }
diff --git a/packages/flutter_tools/lib/src/vscode/vscode.dart b/packages/flutter_tools/lib/src/vscode/vscode.dart index 0eab763..d04ea6b 100644 --- a/packages/flutter_tools/lib/src/vscode/vscode.dart +++ b/packages/flutter_tools/lib/src/vscode/vscode.dart
@@ -66,8 +66,9 @@ fs.path.join(installPath, 'resources', 'app', 'package.json'); final String versionString = _getVersionFromPackageJson(packageJsonPath); Version version; - if (versionString != null) + if (versionString != null) { version = Version.parse(versionString); + } return VsCode._(installPath, extensionDirectory, version: version, edition: edition); } @@ -86,15 +87,17 @@ Iterable<ValidationMessage> get validationMessages => _validationMessages; static List<VsCode> allInstalled() { - if (platform.isMacOS) + if (platform.isMacOS) { return _installedMacOS(); - else if (platform.isWindows) + } + if (platform.isWindows) { return _installedWindows(); - else if (platform.isLinux) + } + if (platform.isLinux) { return _installedLinux(); - else - // VS Code isn't supported on the other platforms. - return <VsCode>[]; + } + // VS Code isn't supported on the other platforms. + return <VsCode>[]; } // macOS: @@ -216,8 +219,9 @@ 'VS Code ($version)${_extensionVersion != Version.unknown ? ', Flutter ($_extensionVersion)' : ''}'; static String _getVersionFromPackageJson(String packageJsonPath) { - if (!fs.isFileSync(packageJsonPath)) + if (!fs.isFileSync(packageJsonPath)) { return null; + } final String jsonString = fs.file(packageJsonPath).readAsStringSync(); final Map<String, dynamic> jsonObject = json.decode(jsonString); return jsonObject['version'];
diff --git a/packages/flutter_tools/test/general.shard/base/build_test.dart b/packages/flutter_tools/test/general.shard/base/build_test.dart index d767d9a..f2f3701 100644 --- a/packages/flutter_tools/test/general.shard/base/build_test.dart +++ b/packages/flutter_tools/test/general.shard/base/build_test.dart
@@ -58,8 +58,9 @@ _depfilePath = depfilePath; _additionalArgs = additionalArgs.toList(); - if (!succeed) + if (!succeed) { return 1; + } outputs.forEach((String filePath, String fileContent) { fs.file(filePath).writeAsString(fileContent); });
diff --git a/packages/flutter_tools/test/general.shard/commands/daemon_test.dart b/packages/flutter_tools/test/general.shard/commands/daemon_test.dart index d00242d..f779433 100644 --- a/packages/flutter_tools/test/general.shard/commands/daemon_test.dart +++ b/packages/flutter_tools/test/general.shard/commands/daemon_test.dart
@@ -26,8 +26,9 @@ }); tearDown(() { - if (daemon != null) + if (daemon != null) { return daemon.shutdown(); + } notifyingLogger.dispose(); });
diff --git a/packages/flutter_tools/test/general.shard/commands/packages_test.dart b/packages/flutter_tools/test/general.shard/commands/packages_test.dart index 426bc61..7bb57e5 100644 --- a/packages/flutter_tools/test/general.shard/commands/packages_test.dart +++ b/packages/flutter_tools/test/general.shard/commands/packages_test.dart
@@ -191,8 +191,9 @@ ].expand<String>((List<String> list) => list); for (String path in allFiles) { final File file = fs.file(fs.path.join(projectPath, path)); - if (file.existsSync()) + if (file.existsSync()) { file.deleteSync(); + } } }
diff --git a/packages/flutter_tools/test/general.shard/commands/test_test.dart b/packages/flutter_tools/test/general.shard/commands/test_test.dart index fc0f664..4a8bfd6 100644 --- a/packages/flutter_tools/test/general.shard/commands/test_test.dart +++ b/packages/flutter_tools/test/general.shard/commands/test_test.dart
@@ -74,8 +74,9 @@ Cache.flutterRoot = '../..'; final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory, extraArguments: const <String>['--name', 'inc.*de']); - if (!result.stdout.contains('+1: All tests passed')) + if (!result.stdout.contains('+1: All tests passed')) { fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n'); + } expect(result.exitCode, 0); }); @@ -83,8 +84,9 @@ Cache.flutterRoot = '../..'; final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory, extraArguments: const <String>['--plain-name', 'include']); - if (!result.stdout.contains('+1: All tests passed')) + if (!result.stdout.contains('+1: All tests passed')) { fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n'); + } expect(result.exitCode, 0); }); @@ -96,10 +98,12 @@ (!result.stdout.contains('test 0: starting shell process')) || (!result.stdout.contains('test 0: deleting temporary directory')) || (!result.stdout.contains('test 0: finished')) || - (!result.stdout.contains('test package returned with exit code 0'))) + (!result.stdout.contains('test package returned with exit code 0'))) { fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n'); - if (result.stderr.isNotEmpty) + } + if (result.stderr.isNotEmpty) { fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n'); + } expect(result.exitCode, 0); }); @@ -111,10 +115,12 @@ (!result.stdout.contains('test 0: starting shell process')) || (!result.stdout.contains('test 0: deleting temporary directory')) || (!result.stdout.contains('test 0: finished')) || - (!result.stdout.contains('test package returned with exit code 0'))) + (!result.stdout.contains('test package returned with exit code 0'))) { fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n'); - if (result.stderr.isNotEmpty) + } + if (result.stderr.isNotEmpty) { fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n'); + } expect(result.exitCode, 0); }); @@ -131,11 +137,13 @@ exitCode ??= isNonZero; final String fullTestExpectation = fs.path.join(testDirectory, '${testName}_expectation.txt'); final File expectationFile = fs.file(fullTestExpectation); - if (!expectationFile.existsSync()) + if (!expectationFile.existsSync()) { fail('missing expectation file: $expectationFile'); + } - while (_testExclusionLock != null) + while (_testExclusionLock != null) { await _testExclusionLock; + } final ProcessResult exec = await _runFlutterTest( testName, @@ -146,10 +154,12 @@ expect(exec.exitCode, exitCode); final List<String> output = exec.stdout.split('\n'); - if (output.first == 'Waiting for another flutter command to release the startup lock...') + if (output.first == 'Waiting for another flutter command to release the startup lock...') { output.removeAt(0); - if (output.first.startsWith('Running "flutter pub get" in')) + } + if (output.first.startsWith('Running "flutter pub get" in')) { output.removeAt(0); + } output.add('<<stderr>>'); output.addAll(exec.stderr.split('\n')); final List<String> expectations = fs.file(fullTestExpectation).readAsLinesSync(); @@ -198,8 +208,9 @@ outputLineNumber += 1; } expect(allowSkip, isFalse); - if (!haveSeenStdErrMarker) + if (!haveSeenStdErrMarker) { expect(exec.stderr, ''); + } } Future<ProcessResult> _runFlutterTest( @@ -214,14 +225,16 @@ // Test everything in the directory. testPath = testDirectory; final Directory directoryToTest = fs.directory(testPath); - if (!directoryToTest.existsSync()) + if (!directoryToTest.existsSync()) { fail('missing test directory: $directoryToTest'); + } } else { // Test just a specific test file. testPath = fs.path.join(testDirectory, '${testName}_test.dart'); final File testFile = fs.file(testPath); - if (!testFile.existsSync()) + if (!testFile.existsSync()) { fail('missing test file: $testFile'); + } } final List<String> args = <String>[ @@ -233,8 +246,9 @@ testPath ]; - while (_testExclusionLock != null) + while (_testExclusionLock != null) { await _testExclusionLock; + } final Completer<void> testExclusionCompleter = Completer<void>(); _testExclusionLock = testExclusionCompleter.future;
diff --git a/packages/flutter_tools/test/general.shard/crash_reporting_test.dart b/packages/flutter_tools/test/general.shard/crash_reporting_test.dart index cd90886..75f014e 100644 --- a/packages/flutter_tools/test/general.shard/crash_reporting_test.dart +++ b/packages/flutter_tools/test/general.shard/crash_reporting_test.dart
@@ -286,8 +286,9 @@ .split('--$boundary') .map<List<String>>((String part) { final Match nameMatch = RegExp(r'name="(.*)"').firstMatch(part); - if (nameMatch == null) + if (nameMatch == null) { return null; + } final String name = nameMatch[1]; final String value = part.split('\n').skip(2).join('\n').trim(); return <String>[name, value];
diff --git a/packages/flutter_tools/test/general.shard/devfs_test.dart b/packages/flutter_tools/test/general.shard/devfs_test.dart index 0230408..90d919a 100644 --- a/packages/flutter_tools/test/general.shard/devfs_test.dart +++ b/packages/flutter_tools/test/general.shard/devfs_test.dart
@@ -302,8 +302,9 @@ } void _cleanupTempDirs() { - while (_tempDirs.isNotEmpty) + while (_tempDirs.isNotEmpty) { tryToDelete(_tempDirs.removeLast()); + } } Future<void> _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async {
diff --git a/packages/flutter_tools/test/general.shard/ios/devices_test.dart b/packages/flutter_tools/test/general.shard/ios/devices_test.dart index a05f1d0..f27f54a 100644 --- a/packages/flutter_tools/test/general.shard/ios/devices_test.dart +++ b/packages/flutter_tools/test/general.shard/ios/devices_test.dart
@@ -648,8 +648,9 @@ List<Workflow> get workflows { if (_workflows == null) { _workflows = <Workflow>[]; - if (iosWorkflow.appliesToHostPlatform) + if (iosWorkflow.appliesToHostPlatform) { _workflows.add(iosWorkflow); + } } return _workflows; }
diff --git a/packages/flutter_tools/test/general.shard/utils_test.dart b/packages/flutter_tools/test/general.shard/utils_test.dart index 9a2cb33..b74b47f 100644 --- a/packages/flutter_tools/test/general.shard/utils_test.dart +++ b/packages/flutter_tools/test/general.shard/utils_test.dart
@@ -157,10 +157,11 @@ final Completer<Duration> completer = Completer<Duration>(); DateTime firstTime; poller = Poller(() async { - if (firstTime == null) + if (firstTime == null) { firstTime = DateTime.now(); - else + } else { completer.complete(DateTime.now().difference(firstTime)); + } // introduce a delay await Future<void>.delayed(kShortDelay);
diff --git a/packages/flutter_tools/test/general.shard/vmservice_test.dart b/packages/flutter_tools/test/general.shard/vmservice_test.dart index 308b4c8..437bad0 100644 --- a/packages/flutter_tools/test/general.shard/vmservice_test.dart +++ b/packages/flutter_tools/test/general.shard/vmservice_test.dart
@@ -74,8 +74,9 @@ @override Future<dynamic> sendRequest(String method, [ dynamic parameters ]) async { - if (method == 'getVM') + if (method == 'getVM') { await _getVMLatch; + } await Future<void>.delayed(Duration.zero); returnedFromSendRequest += 1; if (method == 'getVM') {
diff --git a/packages/flutter_tools/test/integration.shard/test_data/project.dart b/packages/flutter_tools/test/integration.shard/test_data/project.dart index 69a2b3c..b58f1f8 100644 --- a/packages/flutter_tools/test/integration.shard/test_data/project.dart +++ b/packages/flutter_tools/test/integration.shard/test_data/project.dart
@@ -28,8 +28,9 @@ int lineContaining(String contents, String search) { final int index = contents.split('\n').indexWhere((String l) => l.contains(search)); - if (index == -1) + if (index == -1) { throw Exception("Did not find '$search' inside the file"); + } return index + 1; // first line is line 1, not line 0 } }
diff --git a/packages/flutter_tools/test/integration.shard/test_driver.dart b/packages/flutter_tools/test/integration.shard/test_driver.dart index 4039cc3..6a046b0 100644 --- a/packages/flutter_tools/test/integration.shard/test_driver.dart +++ b/packages/flutter_tools/test/integration.shard/test_driver.dart
@@ -71,8 +71,9 @@ } else { lastTime = time; } - if (_printDebugOutputToStdOut) + if (_printDebugOutputToStdOut) { print('$time$_logPrefix$line'); + } } Future<void> _setupProcess( @@ -82,10 +83,12 @@ File pidFile, }) async { final String flutterBin = fs.path.join(getFlutterRoot(), 'bin', 'flutter'); - if (withDebugger) + if (withDebugger) { arguments.add('--start-paused'); - if (_printDebugOutputToStdOut) + } + if (_printDebugOutputToStdOut) { arguments.add('--verbose'); + } if (pidFile != null) { arguments.addAll(<String>['--pid-file', pidFile.path]); } @@ -149,8 +152,9 @@ Future<int> quit() => _killGracefully(); Future<int> _killGracefully() async { - if (_processPid == null) + if (_processPid == null) { return -1; + } _debugPrint('Sending SIGTERM to $_processPid..'); ProcessSignal.SIGTERM.send(_processPid); return _process.exitCode.timeout(quitTimeout, onTimeout: _killForcefully); @@ -216,8 +220,9 @@ && event.kind.startsWith('Pause'); }) .listen((Event event) { - if (!pauseEvent.isCompleted) + if (!pauseEvent.isCompleted) { pauseEvent.complete(event); + } }); // But also check if the isolate was already paused (only after we've set @@ -252,8 +257,9 @@ } Future<Isolate> stepOverOrOverAsyncSuspension({ bool waitForNextPause = true }) async { - if (await isAtAsyncSuspension()) + if (await isAtAsyncSuspension()) { return await stepOverAsync(waitForNextPause: waitForNextPause); + } return await stepOver(waitForNextPause: waitForNextPause); } @@ -326,8 +332,9 @@ subscription = _stdout.stream.listen((String line) async { final dynamic json = parseFlutterResponse(line); _lastResponse = line; - if (json == null) + if (json == null) { return; + } if ((event != null && json['event'] == event) || (id != null && json['id'] == id)) { await subscription.cancel(); @@ -486,8 +493,9 @@ final String wsUriString = debugPort['params']['wsUri']; _vmServiceWsUri = Uri.parse(wsUriString); await connectToVmService(pauseOnExceptions: pauseOnExceptions); - if (!startPaused) + if (!startPaused) { await resume(waitForNextPause: false); + } } // Now await the started event; if it had already happened the future will @@ -499,8 +507,9 @@ Future<void> hotReload() => _restart(fullRestart: false); Future<void> _restart({ bool fullRestart = false, bool pause = false }) async { - if (_currentRunningAppId == null) + if (_currentRunningAppId == null) { throw Exception('App has not started yet'); + } _debugPrint('Performing ${ pause ? "paused " : "" }${ fullRestart ? "hot restart" : "hot reload" }...'); final dynamic hotReloadResponse = await _sendRequest( @@ -509,8 +518,9 @@ ); _debugPrint('${ fullRestart ? "Hot restart" : "Hot reload" } complete.'); - if (hotReloadResponse == null || hotReloadResponse['code'] != 0) + if (hotReloadResponse == null || hotReloadResponse['code'] != 0) { _throwErrorResponse('Hot ${fullRestart ? 'restart' : 'reload'} request failed'); + } } Future<int> detach() async { @@ -586,8 +596,9 @@ _process.stdin.writeln(jsonEncoded); final Map<String, dynamic> response = await responseFuture; - if (response['error'] != null || response['result'] == null) + if (response['error'] != null || response['result'] == null) { _throwErrorResponse('Unexpected error response'); + } return response['result']; }
diff --git a/packages/flutter_tools/test/integration.shard/test_utils.dart b/packages/flutter_tools/test/integration.shard/test_utils.dart index 452f254..023207c 100644 --- a/packages/flutter_tools/test/integration.shard/test_utils.dart +++ b/packages/flutter_tools/test/integration.shard/test_utils.dart
@@ -50,6 +50,7 @@ final StringBuffer errorOutput = StringBuffer(); process.stderr.transform(utf8.decoder).listen(errorOutput.write); final int exitCode = await process.exitCode; - if (exitCode != 0) + if (exitCode != 0) { throw Exception('flutter pub get failed: $errorOutput'); + } }
diff --git a/packages/flutter_tools/test/src/common.dart b/packages/flutter_tools/test/src/common.dart index 6860154..64e0575 100644 --- a/packages/flutter_tools/test/src/common.dart +++ b/packages/flutter_tools/test/src/common.dart
@@ -38,8 +38,9 @@ /// environment variable is set, it will be returned. Otherwise, this will /// deduce the path from `platform.script`. String getFlutterRoot() { - if (platform.environment.containsKey('FLUTTER_ROOT')) + if (platform.environment.containsKey('FLUTTER_ROOT')) { return platform.environment['FLUTTER_ROOT']; + } Error invalidScript() => StateError('Invalid script: ${platform.script}'); @@ -51,8 +52,9 @@ case 'data': final RegExp flutterTools = RegExp(r'(file://[^"]*[/\\]flutter_tools[/\\][^"]+\.dart)', multiLine: true); final Match match = flutterTools.firstMatch(Uri.decodeFull(platform.script.path)); - if (match == null) + if (match == null) { throw invalidScript(); + } scriptUri = Uri.parse(match.group(1)); break; default: @@ -61,16 +63,18 @@ final List<String> parts = fs.path.split(fs.path.fromUri(scriptUri)); final int toolsIndex = parts.indexOf('flutter_tools'); - if (toolsIndex == -1) + if (toolsIndex == -1) { throw invalidScript(); + } final String toolsPath = fs.path.joinAll(parts.sublist(0, toolsIndex + 1)); return fs.path.normalize(fs.path.join(toolsPath, '..', '..')); } CommandRunner<void> createTestCommandRunner([ FlutterCommand command ]) { final FlutterCommandRunner runner = FlutterCommandRunner(); - if (command != null) + if (command != null) { runner.addCommand(command); + } return runner; } @@ -87,10 +91,12 @@ /// Matcher for functions that throw [ToolExit]. Matcher throwsToolExit({ int exitCode, Pattern message }) { Matcher matcher = isToolExit; - if (exitCode != null) + if (exitCode != null) { matcher = allOf(matcher, (ToolExit e) => e.exitCode == exitCode); - if (message != null) + } + if (message != null) { matcher = allOf(matcher, (ToolExit e) => e.message.contains(message)); + } return throwsA(matcher); }
diff --git a/packages/flutter_tools/test/src/context.dart b/packages/flutter_tools/test/src/context.dart index c28e260..21ad56b 100644 --- a/packages/flutter_tools/test/src/context.dart +++ b/packages/flutter_tools/test/src/context.dart
@@ -129,8 +129,9 @@ void _printBufferedErrors(AppContext testContext) { if (testContext.get<Logger>() is BufferLogger) { final BufferLogger bufferLogger = testContext.get<Logger>(); - if (bufferLogger.errorText.isNotEmpty) + if (bufferLogger.errorText.isNotEmpty) { print(bufferLogger.errorText); + } bufferLogger.clear(); } } @@ -142,8 +143,9 @@ @override String get specifiedDeviceId { - if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') + if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') { return null; + } return _specifiedDeviceId; }
diff --git a/packages/flutter_tools/test/src/mocks.dart b/packages/flutter_tools/test/src/mocks.dart index adea05c..42be20f 100644 --- a/packages/flutter_tools/test/src/mocks.dart +++ b/packages/flutter_tools/test/src/mocks.dart
@@ -77,8 +77,9 @@ _createSdkFile(dir, 'build-tools/19.1.0/aapt$exe'); _createSdkFile(dir, 'build-tools/22.0.1/aapt$exe'); _createSdkFile(dir, 'build-tools/23.0.2/aapt$exe'); - if (withAndroidN) + if (withAndroidN) { _createSdkFile(dir, 'build-tools/24.0.0-preview/aapt$exe'); + } } _createSdkFile(dir, 'platforms/android-22/android.jar'); @@ -88,8 +89,9 @@ _createSdkFile(dir, 'platforms/android-N/build.prop', contents: _buildProp); } - if (withSdkManager) + if (withSdkManager) { _createSdkFile(dir, 'tools/bin/sdkmanager$bat'); + } if (withNdkDir != null) { final String ndkToolchainBin = fs.path.join( @@ -307,8 +309,9 @@ // Echo stdin to stdout. _stdoutController.add(bytesOnStdin); if (bytesOnStdin[0] == utf8.encode('y')[0]) { - for (final String line in outputLines) + for (final String line in outputLines) { _stdoutController.add(utf8.encode('$line\n')); + } } await _stdoutController.close(); } @@ -343,8 +346,9 @@ @override void add(List<int> data) { - if (!_completer.isCompleted) + if (!_completer.isCompleted) { _completer.complete(data); + } super.add(data); } } @@ -434,8 +438,9 @@ @override int get terminalColumns { - if (_terminalColumns != null) + if (_terminalColumns != null) { return _terminalColumns; + } throw const io.StdoutException('unspecified mock value'); } set terminalColumns(int value) => _terminalColumns = value; @@ -443,8 +448,9 @@ @override int get terminalLines { - if (_terminalLines != null) + if (_terminalLines != null) { return _terminalLines; + } throw const io.StdoutException('unspecified mock value'); } set terminalLines(int value) => _terminalLines = value;