[flutter_tool] Use curly braces around single statment control structures (#40446)

This commit is contained in:
Zachary Anderson 2019-09-13 14:51:35 -07:00 committed by GitHub
parent f29524a150
commit e2340c641d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
100 changed files with 1465 additions and 757 deletions

View file

@ -12,3 +12,4 @@ linter:
rules:
unawaited_futures: true
avoid_as: false # Disabled so we can gradually migrate to no implicit dynamic.
curly_braces_in_flow_control_structures: true

View file

@ -161,8 +161,9 @@ Future<void> run(List<String> args) async {
} 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);

View file

@ -93,10 +93,12 @@ Future<int> _handleToolError(
// 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<String> _doctorText() async {
}
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).

View file

@ -59,8 +59,9 @@ class AndroidConsole {
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;

View file

@ -143,8 +143,9 @@ class AndroidDevice extends Device {
/// 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 @@ class AndroidDevice extends Device {
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 @@ class AndroidDevice extends Device {
@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 @@ class AndroidDevice extends Device {
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 @@ class AndroidDevice extends Device {
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 @@ class AndroidDevice extends Device {
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 @@ class AndroidDevice extends Device {
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 @@ List<AndroidDevice> getAdbDevices() {
/// 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 @@ void parseADBDeviceOutput(
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 @@ void parseADBDeviceOutput(
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 @@ void parseADBDeviceOutput(
}
}
if (info['model'] != null)
if (info['model'] != null) {
info['model'] = cleanAdbDeviceName(info['model']);
}
if (deviceState == 'unauthorized') {
diagnostics?.add(
@ -856,8 +871,9 @@ class _AdbLogReader extends DeviceLogReader {
_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();
}
});
});
}

View file

@ -46,8 +46,9 @@ const int minimumAndroidSdkVersion = 25;
/// 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 @@ String getAvdPath() {
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 @@ class AndroidSdk {
} 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 @@ class AndroidSdk {
// 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 @@ class AndroidSdk {
// 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 @@ class AndroidSdk {
/// 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 @@ class AndroidSdk {
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 @@ class AndroidSdk {
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 @@ class AndroidSdk {
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 @@ class AndroidSdk {
buildToolsVersion ??= Version.primary(buildTools);
if (buildToolsVersion == null)
if (buildToolsVersion == null) {
return null;
}
return AndroidSdkVersion._(
this,
@ -576,8 +590,9 @@ class AndroidSdk {
/// 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 @@ class AndroidSdkVersion implements Comparable<AndroidSdkVersion> {
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 @@ class AndroidSdkVersion implements Comparable<AndroidSdkVersion> {
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;
}
}

View file

@ -55,8 +55,9 @@ class AndroidStudio implements Comparable<AndroidStudio> {
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 @@ class AndroidStudio implements Comparable<AndroidStudio> {
@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 @@ class AndroidStudio implements Comparable<AndroidStudio> {
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 @@ class AndroidStudio implements Comparable<AndroidStudio> {
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 @@ class AndroidStudio implements Comparable<AndroidStudio> {
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;
}

View file

@ -477,8 +477,9 @@ void updateLocalProperties({
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 @@ void updateLocalProperties({
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 @@ Future<void> _buildGradleProjectV1(FlutterProject project) async {
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 @@ Future<void> _buildGradleProjectV2(
}
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 @@ Future<void> _buildGradleProjectV2(
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 @@ Future<void> _buildGradleProjectV2(
}
} 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 @@ Future<void> _buildGradleProjectV2(
@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 @@ class GradleProject {
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 @@ class GradleProject {
}
}
}
if (productFlavors.isEmpty)
if (productFlavors.isEmpty) {
buildTypes.addAll(variants);
}
return GradleProject(
buildTypes.toList(),
productFlavors.toList(),
@ -1002,33 +1020,36 @@ class GradleProject {
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 @@ class GradleProject {
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)}';
}
}

View file

@ -501,8 +501,9 @@ class ApkManifestData {
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);

View file

@ -336,12 +336,15 @@ class CachedArtifacts extends Artifacts {
}
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 @@ class LocalEngineArtifacts extends Artifacts {
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');
}

View file

@ -81,12 +81,14 @@ class _ManifestAssetBundle implements AssetBundle {
@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 @@ class _ManifestAssetBundle implements AssetBundle {
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 @@ class _ManifestAssetBundle implements AssetBundle {
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 @@ class _ManifestAssetBundle implements AssetBundle {
packageName: packageName,
);
if (packageAssets == null)
if (packageAssets == null) {
return 1;
}
assetVariants.addAll(packageAssets);
fonts.addAll(_parseFonts(
@ -262,8 +268,9 @@ class _Asset {
/// 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 @@ class _Asset {
@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 @@ DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) {
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 @@ class _AssetDirectoryCache {
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 @@ _Asset _resolveAsset(
// 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(

View file

@ -288,8 +288,9 @@ class AOTSnapshotter {
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 @@ class AOTSnapshotter {
}
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,

View file

@ -10,8 +10,9 @@ import 'platform.dart';
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>();

View file

@ -81,8 +81,9 @@ class AppContext {
/// 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 @@ class AppContext {
return _boxNull(generators[type]());
} finally {
_reentrantChecks.removeLast();
if (_reentrantChecks.isEmpty)
if (_reentrantChecks.isEmpty) {
_reentrantChecks = null;
}
}
});
}
@ -120,8 +122,9 @@ class AppContext {
@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 @@ class AppContext {
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 += ' ';
}

View file

@ -55,8 +55,9 @@ ReplayFileSystem getReplayFileSystem(String location) {
/// 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 copyDirectorySync(
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 @@ Directory getRecordingSink(String dirname, String basename) {
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 @@ Directory getRecordingSink(String dirname, String basename) {
/// 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 @@ String escapePath(String path) => platform.isWindows ? path.replaceAll('\\', '\\
///
/// 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);
}

View file

@ -61,15 +61,18 @@ class Fingerprinter {
}
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 @@ class Fingerprint {
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 @@ class Fingerprint {
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 @@ class Fingerprint {
@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);

View file

@ -36,10 +36,11 @@ class Flags {
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;
}

View file

@ -164,8 +164,9 @@ class _PosixProcessSignal extends ProcessSignal {
@override
Stream<ProcessSignal> watch() {
if (platform.isWindows)
if (platform.isWindows) {
return const Stream<ProcessSignal>.empty();
}
return super.watch();
}
}

View file

@ -167,12 +167,14 @@ class StdoutLogger extends Logger {
_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 @@ class StdoutLogger extends Logger {
_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 @@ class BufferLogger extends Logger {
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 @@ class VerboseLogger extends Logger {
}
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 @@ class VerboseLogger extends Logger {
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 @@ class VerboseLogger extends Logger {
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 @@ abstract class Status {
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 @@ abstract class Status {
@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 @@ abstract class Status {
void finish() {
assert(_stopwatch.isRunning);
_stopwatch.stop();
if (onFinish != null)
if (onFinish != null) {
onFinish();
}
}
}
@ -572,8 +588,9 @@ class SummaryStatus extends Status {
@override
void stop() {
if (!_messageShowingOnCurrentLine)
if (!_messageShowingOnCurrentLine) {
_printMessage();
}
super.stop();
writeSummaryInformation();
stdout.write('\n');
@ -582,8 +599,9 @@ class SummaryStatus extends Status {
@override
void cancel() {
super.cancel();
if (_messageShowingOnCurrentLine)
if (_messageShowingOnCurrentLine) {
stdout.write('\n');
}
}
/// Prints a (minimum) 8 character padded time.
@ -596,8 +614,9 @@ class SummaryStatus extends Status {
void writeSummaryInformation() {
assert(_messageShowingOnCurrentLine);
stdout.write(elapsedTime.padLeft(_kTimePadding));
if (seemsSlow)
if (seemsSlow) {
stdout.write(' (!)');
}
}
@override
@ -773,11 +792,13 @@ class AnsiStatus extends AnsiSpinner {
/// 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() {

View file

@ -21,8 +21,9 @@ Future<List<int>> fetchUrl(Uri url, {int maxAttempts}) async {
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 @@ Future<List<int>> fetchUrl(Uri url, {int maxAttempts}) async {
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;
}
}
}

View file

@ -41,8 +41,9 @@ abstract class OperatingSystemUtils {
/// 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 @@ class _PosixUtils extends OperatingSystemUtils {
@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 @@ class _WindowsUtils extends OperatingSystemUtils {
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 @@ class _WindowsUtils extends OperatingSystemUtils {
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 @@ class _WindowsUtils extends OperatingSystemUtils {
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 @@ String findProjectRoot([ String directory ]) {
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;
}
}

View file

@ -126,10 +126,12 @@ class RunResult {
@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 @@ class _DefaultProcessUtils implements ProcessUtils {
.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 @@ class _DefaultProcessUtils implements ProcessUtils {
.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 @@ class _DefaultProcessUtils implements ProcessUtils {
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;

View file

@ -117,8 +117,9 @@ class AnsiTerminal {
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 @@ class AnsiTerminal {
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 @@ class AnsiTerminal {
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;
}
}

View file

@ -86,8 +86,9 @@ String snakeCase(String str, [ String sep = '_' ]) {
}
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 @@ File getUniqueFile(Directory dir, String baseName, String ext) {
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 @@ class SettingsFile {
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 @@ class Poller {
Timer _timer;
Future<void> _handleCallback() async {
if (_canceled)
if (_canceled) {
return;
}
try {
await callback();
@ -279,8 +284,9 @@ class Poller {
printTrace('Error from poller: $error');
}
if (!_canceled)
if (!_canceled) {
_timer = Timer(pollingInterval, _handleCallback);
}
}
/// Cancels the poller.

View file

@ -7,22 +7,27 @@ class Version implements Comparable<Version> {
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 @@ class Version implements Comparable<Version> {
/// 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 @@ class Version implements Comparable<Version> {
@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);
}

View file

@ -414,12 +414,15 @@ String getPlatformNameForAndroidArch(AndroidArch arch) {
}
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 @@ HostPlatform getCurrentHostPlatform() {
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)) {

View file

@ -79,8 +79,9 @@ class BundleBuilder {
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 @@ class BundleBuilder {
packagesPath: packagesPath,
reportLicensedPackages: reportLicensedPackages,
);
if (assets == null)
if (assets == null) {
throwToolExit('Error building assets', exitCode: 1);
}
await assemble(
buildMode: buildMode,
@ -141,8 +143,9 @@ Future<AssetBundle> buildAssets({
includeDefaultFonts: includeDefaultFonts,
reportLicensedPackages: reportLicensedPackages,
);
if (result != 0)
if (result != 0) {
return null;
}
return assetBundle;
}
@ -177,8 +180,9 @@ Future<void> writeBundle(
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.

View file

@ -138,8 +138,9 @@ class Cache {
/// 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 @@ class Cache {
/// 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 @@ class Cache {
/// 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 @@ abstract class CachedArtifact {
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 @@ abstract class CachedArtifact {
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 @@ class GradleWrapper extends CachedArtifact {
}
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;
}
}

View file

@ -56,14 +56,16 @@ abstract class AnalyzeBase {
/// 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 @@ class PackageDependency {
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 @@ class PackageDependency {
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 @@ class PackageDependencyTracker {
// 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 @@ class PackageDependencyTracker {
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;
}
}

View file

@ -64,19 +64,22 @@ class AnalyzeContinuously extends AnalyzeBase {
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 @@ class AnalyzeContinuously extends AnalyzeBase {
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 @@ class AnalyzeContinuously extends AnalyzeBase {
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) {

View file

@ -57,15 +57,18 @@ class AnalyzeOnce extends AnalyzeBase {
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 @@ class AnalyzeOnce extends AnalyzeBase {
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);

View file

@ -109,8 +109,9 @@ class AttachCommand extends FlutterCommand {
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 @@ class AttachCommand extends FlutterCommand {
@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 @@ class AttachCommand extends FlutterCommand {
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 {

View file

@ -74,8 +74,9 @@ class BuildAotCommand extends BuildSubCommand with TargetPlatformBasedDevelopmen
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 @@ class BuildAotCommand extends BuildSubCommand with TargetPlatformBasedDevelopmen
// 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 @@ class BuildAotCommand extends BuildSubCommand with TargetPlatformBasedDevelopmen
}
status?.stop();
if (outputPath == null)
if (outputPath == null) {
throwToolExit(null);
}
final String builtMessage = 'Built to $outputPath${fs.path.separator}.';
if (argResults['quiet']) {

View file

@ -59,13 +59,15 @@ class BuildIOSCommand extends BuildSubCommand {
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 @@ class BuildIOSCommand extends BuildSubCommand {
'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 @@ class BuildIOSCommand extends BuildSubCommand {
throwToolExit('Encountered error while building for $logTarget.');
}
if (result.output != null)
if (result.output != null) {
printStatus('Built ${result.output}.');
}
return null;
}

View file

@ -65,21 +65,25 @@ class ChannelCommand extends FlutterCommand {
<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;
},
);

View file

@ -86,8 +86,9 @@ class ConfigCommand extends FlutterCommand {
}
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 @@ class ConfigCommand extends FlutterCommand {
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 @@ class ConfigCommand extends FlutterCommand {
}
}
if (argResults.arguments.isEmpty)
if (argResults.arguments.isEmpty) {
printStatus(usage);
}
return null;
}

View file

@ -180,11 +180,13 @@ class CreateCommand extends FlutterCommand {
// 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 @@ class CreateCommand extends FlutterCommand {
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 @@ class CreateCommand extends FlutterCommand {
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 @@ class CreateCommand extends FlutterCommand {
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 @@ class CreateCommand extends FlutterCommand {
}
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 @@ String _validateProjectDir(String dirPath, { String flutterRoot, bool overwrite
'${overwrite ? ' Refusing to overwrite a file with a directory.' : ''}';
}
if (overwrite)
if (overwrite) {
return null;
}
final FileSystemEntityType type = fs.typeSync(dirPath);

View file

@ -62,8 +62,9 @@ class DaemonCommand extends FlutterCommand {
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 @@ class Daemon {
_commandSubscription = commandStream.listen(
_handleRequest,
onDone: () {
if (!_onExitCompleter.isCompleted)
if (!_onExitCompleter.isCompleted) {
_onExitCompleter.complete(0);
}
},
);
}
@ -134,13 +136,15 @@ class Daemon {
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 @@ class Daemon {
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 @@ abstract class Domain {
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 @@ abstract class Domain {
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 @@ class DaemonDomain extends Domain {
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 @@ class AppDomain extends Domain {
'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 @@ class AppDomain extends Domain {
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 @@ class AppDomain extends Domain {
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 @@ class AppDomain extends Domain {
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 @@ class AppDomain extends Domain {
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 @@ class DeviceDomain extends Domain {
}
void addDeviceDiscoverer(DeviceDiscovery discoverer) {
if (!discoverer.supportsPlatform)
if (!discoverer.supportsPlatform) {
return;
}
_discoverers.add(discoverer);
if (discoverer is PollingDeviceDiscovery) {
@ -694,15 +718,17 @@ class DeviceDomain extends Domain {
/// 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 @@ class DeviceDomain extends Domain {
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 @@ class DeviceDomain extends Domain {
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 @@ String jsonEncodeObject(dynamic object) {
}
dynamic _toEncodable(dynamic object) {
if (object is OperationResult)
if (object is OperationResult) {
return _operationResultToMap(object);
}
return object;
}
@ -804,12 +835,15 @@ Map<String, dynamic> _operationResultToMap(OperationResult result) {
}
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 @@ class _AppRunLogger extends Logger {
}
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);
}
}
}

View file

@ -94,15 +94,18 @@ class DriveCommand extends RunCommandBase {
@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 @@ class DriveCommand extends RunCommandBase {
}
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 @@ class DriveCommand extends RunCommandBase {
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 @@ class DriveCommand extends RunCommandBase {
}
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 @@ Future<LaunchResult> _startApp(DriveCommand command) async {
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 @@ Future<void> _runTests(List<String> testArgs, String observatoryUri) async {
],
environment: <String, String>{'VM_SERVICE_URL': observatoryUri},
);
if (result != 0)
if (result != 0) {
throwToolExit('Driver tests failed: $result', exitCode: result);
}
}

View file

@ -28,8 +28,9 @@ class InstallCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts
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 @@ class InstallCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts
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);

View file

@ -42,8 +42,9 @@ class LogsCommand extends FlutterCommand {
@override
Future<FlutterCommandResult> runCommand() async {
if (argResults['clear'])
if (argResults['clear']) {
device.clearLogs();
}
final DeviceLogReader logReader = device.getLogReader();
@ -78,8 +79,9 @@ class LogsCommand extends FlutterCommand {
// 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;
}

View file

@ -37,8 +37,9 @@ class MakeHostAppEditableCommand extends FlutterCommand {
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

View file

@ -112,8 +112,9 @@ class PackagesGetCommand extends FlutterCommand {
@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);

View file

@ -195,12 +195,13 @@ class RunCommand extends RunCommandBase {
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 @@ class RunCommand extends RunCommandBase {
@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 @@ class RunCommand extends RunCommandBase {
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 @@ class RunCommand extends RunCommandBase {
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 @@ class RunCommand extends RunCommandBase {
}
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 @@ class RunCommand extends RunCommandBase {
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.');
}
}
}

View file

@ -81,8 +81,9 @@ class ScreenshotCommand extends FlutterCommand {
@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:

View file

@ -164,8 +164,9 @@ class TestCommand extends FastFlutterCommand {
// 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 @@ class TestCommand extends FastFlutterCommand {
);
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);
}

View file

@ -160,8 +160,9 @@ class UpdatePackagesCommand extends FlutterCommand {
// 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 @@ class UpdatePackagesCommand extends FlutterCommand {
// 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 @@ class UpdatePackagesCommand extends FlutterCommand {
// 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 @@ class UpdatePackagesCommand extends FlutterCommand {
@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 @@ class UpdatePackagesCommand extends FlutterCommand {
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 @@ class UpdatePackagesCommand extends FlutterCommand {
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 @@ class PubspecYaml {
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 @@ class PubspecYaml {
} 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 @@ class PubspecYaml {
//
// 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 @@ class PubspecYaml {
// 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 @@ class PubspecYaml {
// 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 @@ class PubspecYaml {
// 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 @@ class PubspecYaml {
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 @@ class PubspecYaml {
// 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 @@ class PubspecYaml {
..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 @@ class PubspecYaml {
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 @@ class PubspecChecksum extends PubspecLine {
/// 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 @@ class PubspecHeader extends PubspecLine {
// * 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 @@ class PubspecHeader extends PubspecLine {
/// 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 @@ class PubspecDependency extends PubspecLine {
//
// 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 @@ class PubspecDependency extends PubspecLine {
/// - 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 @@ class PubspecDependency extends PubspecLine {
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 @@ String _generateFakePubspec(Iterable<PubspecDependency> dependencies) {
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 @@ class PubDependencyTree {
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 @@ class PubDependencyTree {
}
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 @@ String _computeChecksum(Iterable<String> names, String getVersion(String name))
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) {

View file

@ -278,10 +278,12 @@ class KernelCompiler {
'--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 @@ class KernelCompiler {
command.addAll(<String>[ '--platform', platformDill]);
}
if (extraFrontEndOptions != null)
if (extraFrontEndOptions != null) {
command.addAll(extraFrontEndOptions);
}
command.add(mainUri?.toString() ?? mainPath);
@ -440,8 +443,9 @@ class ResidentCompiler {
_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 @@ class ResidentCompiler {
// '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 @@ class ResidentCompiler {
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) {

View file

@ -91,12 +91,13 @@ class AnalysisServer {
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 @@ class AnalysisServer {
.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 @@ class AnalysisError implements Comparable<AnalysisError> {
@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);
}

View file

@ -52,21 +52,24 @@ class PackageMap {
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;
}
}

View file

@ -57,15 +57,18 @@ class PubContext {
}
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 @@ Future<void> pubGet({
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 @@ Future<void> pubGet({
}
}
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 @@ Future<void> pub(
}) async {
showTraceForErrors ??= isRunningOnBot;
if (showTraceForErrors)
if (showTraceForErrors) {
arguments.insert(0, '--trace');
}
int attempts = 0;
int duration = 1;
int code;
@ -276,9 +282,10 @@ String _filterOverrideWarnings(String message) {
// 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;
}

View file

@ -110,8 +110,9 @@ class DevFSFileContent extends DevFSContent {
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 @@ class DevFSFileContent extends DevFSContent {
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 @@ class DevFSFileContent extends DevFSContent {
@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 @@ class _DevFSHttpWriter {
_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 @@ class DevFS {
_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);

View file

@ -81,8 +81,9 @@ class DeviceManager {
/// 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 @@ class DeviceManager {
}
// 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 @@ abstract class Device {
@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 @@ abstract class Device {
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 @@ class LaunchResult {
@override
String toString() {
final StringBuffer buf = StringBuffer('started=$started');
if (observatoryUri != null)
if (observatoryUri != null) {
buf.write(', observatory=$observatoryUri');
}
return buf.toString();
}
}

View file

@ -98,26 +98,33 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {
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 @@ class Doctor {
/// 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 @@ class Doctor {
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 @@ abstract class IntelliJValidator extends DoctorValidator {
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 @@ abstract class IntelliJValidator extends DoctorValidator {
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 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator {
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 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator {
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;
}
}

View file

@ -80,26 +80,29 @@ class EmulatorManager {
}
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 @@ abstract class Emulator {
@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 @@ abstract class Emulator {
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>>[];

View file

@ -27,8 +27,9 @@ class FlutterManifest {
/// 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 @@ class FlutterManifest {
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 @@ class FlutterManifest {
/// 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 @@ class FlutterManifest {
/// 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 @@ class FlutterManifest {
/// 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 @@ class FlutterManifest {
}
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 @@ class FlutterManifest {
style: fontFile['style'],
));
}
if (fontAssets.isNotEmpty)
if (fontAssets.isNotEmpty) {
fonts.add(Font(fontFamily['family'], fontAssets));
}
}
return fonts;
}
@ -269,11 +275,13 @@ class FontAsset {
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;

View file

@ -46,8 +46,9 @@ class IntelliJPlugins {
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);
}

View file

@ -110,8 +110,9 @@ Future<Map<String, String>> getCodeSigningIdentityDevelopmentTeam({
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 @@ Future<Map<String, String>> getCodeSigningIdentityDevelopmentTeam({
// 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 @@ Future<String> _chooseSigningIdentity(List<String> validCodeSigningIdentities) a
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 @@ Future<String> _chooseSigningIdentity(List<String> validCodeSigningIdentities) a
// 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(

View file

@ -167,14 +167,16 @@ class IOSDevice extends Device {
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 @@ class IOSDevice extends Device {
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 @@ class IOSDevice extends Device {
// 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 @@ class IOSDevice extends Device {
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 @@ class _IOSDeviceLogReader extends DeviceLogReader {
_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 @@ class _IOSDevicePortForwarder extends DevicePortForwarder {
@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 @@ class _IOSDevicePortForwarder extends DevicePortForwarder {
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.');
}

View file

@ -56,8 +56,9 @@ class IOSEmulator extends Emulator {
}
// 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)

View file

@ -181,8 +181,9 @@ class IMobileDevice {
<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 @@ class IMobileDevice {
<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 @@ class IMobileDevice {
);
}
}
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 @@ Future<XcodeBuildResult> buildXcodeProject({
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 @@ String readGeneratedXcconfig(String appPath) {
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 @@ class XcodeBuildExecution {
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 @@ bool upgradePbxProjWithFlutterAssets(IosProject project) {
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);
}

View file

@ -28,10 +28,12 @@ class PlistParser {
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);

View file

@ -47,8 +47,9 @@ class IOSSimulatorUtils {
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 @@ class IOSSimulator extends Device {
@override
String supportMessage() {
if (isSupported())
if (isSupported()) {
return 'Supported';
}
return _supportMessage ?? 'Unknown';
}
@ -353,35 +355,42 @@ class IOSSimulator extends Device {
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 @@ class IOSSimulator extends Device {
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 @@ class IOSSimulator extends Device {
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 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
// 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 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
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 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
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 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
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 @@ int compareIosVersions(String v1, String v2) {
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 @@ int compareIphoneVersions(String id1, String id2) {
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'];

View file

@ -136,8 +136,9 @@ List<String> _xcodeBuildSettingsLines({
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 @@ class XcodeProjectInterpreter {
}
_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 @@ class XcodeProjectInterpreter {
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 @@ Map<String, String> parseXcodeBuildSettings(String showBuildSettingsOutput) {
/// 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 @@ class XcodeProjectInfo {
}
collector?.add(line.trim());
}
if (schemes.isEmpty)
if (schemes.isEmpty) {
schemes.add('Runner');
}
return XcodeProjectInfo(targets, buildConfigurations, schemes);
}
@ -425,10 +432,10 @@ class XcodeProjectInfo {
/// 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 @@ class XcodeProjectInfo {
/// 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 @@ class XcodeProjectInfo {
/// 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

View file

@ -87,14 +87,16 @@ class CocoaPods {
}
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 @@ class CocoaPods {
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 @@ class CocoaPods {
// 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;

View file

@ -37,8 +37,9 @@ class Xcode {
}
bool get isInstalled {
if (xcodeSelectPath == null || xcodeSelectPath.isEmpty)
if (xcodeSelectPath == null || xcodeSelectPath.isEmpty) {
return false;
}
return xcodeProjectInterpreter.isInstalled;
}
@ -90,12 +91,15 @@ class Xcode {
}
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 @@ class Xcode {
}
String getSimulatorPath() {
if (xcodeSelectPath == null)
if (xcodeSelectPath == null) {
return null;
}
final List<String> searchPaths = <String>[
fs.path.join(xcodeSelectPath, 'Applications', 'Simulator.app'),
];

View file

@ -24,8 +24,9 @@ class XcodeValidator extends DoctorValidator {
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 @@ class XcodeValidator extends DoctorValidator {
return ValidationResult(xcodeStatus, messages, statusInfo: xcodeVersionInfo);
}
}
}

View file

@ -189,14 +189,17 @@ class Plugin {
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 @@ List<Plugin> findPlugins(FlutterProject project) {
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;
}

View file

@ -102,10 +102,10 @@ class FlutterProject {
}
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 @@ class IosProject implements XcodeBasedProject {
/// 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 @@ class IosProject implements XcodeBasedProject {
///
/// 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 @@ class IosProject implements XcodeBasedProject {
Future<void> ensureReadyForPlatformSpecificTooling() async {
_regenerateFromTemplateIfNeeded();
if (!_flutterLibRoot.existsSync())
if (!_flutterLibRoot.existsSync()) {
return;
}
await _updateGeneratedXcodeConfigIfNeeded();
}
@ -425,12 +428,14 @@ class IosProject implements XcodeBasedProject {
}
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 @@ class IosProject implements XcodeBasedProject {
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 @@ class AndroidProject {
/// 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 @@ class AndroidProject {
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 @@ class WebProject {
/// Deletes [directory] with all content.
void _deleteIfExistsSync(Directory directory) {
if (directory.existsSync())
if (directory.existsSync()) {
directory.deleteSync(recursive: true);
}
}

View file

@ -116,8 +116,9 @@ class FlutterDevice {
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 @@ class FlutterDevice {
}
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 @@ class FlutterDevice {
}
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 @@ class FlutterDevice {
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 @@ class FlutterDevice {
}
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 @@ class FlutterDevice {
to = 'iOS';
break;
}
for (FlutterView view in views)
for (FlutterView view in views) {
await view.uiIsolate.flutterPlatformOverride(to);
}
return to;
}
@ -313,14 +329,16 @@ class FlutterDevice {
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 @@ class FlutterDevice {
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 @@ class FlutterDevice {
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 @@ class FlutterDevice {
}
Future<void> updateReloadStatus(bool wasReloadSuccessful) async {
if (wasReloadSuccessful)
if (wasReloadSuccessful) {
generator?.accept();
else
} else {
await generator?.reject();
}
}
}
@ -635,63 +657,73 @@ abstract class ResidentRunner {
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 @@ abstract class ResidentRunner {
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 @@ abstract class ResidentRunner {
} 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 @@ abstract class ResidentRunner {
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 @@ abstract class ResidentRunner {
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 @@ abstract class ResidentRunner {
);
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 @@ abstract class ResidentRunner {
// 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 @@ abstract class ResidentRunner {
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 @@ class OperationResult {
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 @@ class TerminalHandler {
_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 @@ class TerminalHandler {
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':

View file

@ -52,8 +52,9 @@ class ColdRunner extends ResidentRunner {
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 @@ class ColdRunner extends ResidentRunner {
coldRunner: this,
route: route,
);
if (result != 0)
if (result != 0) {
return result;
}
}
// Connect to observatory.
@ -89,8 +91,9 @@ class ColdRunner extends ResidentRunner {
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 @@ class ColdRunner extends ResidentRunner {
appStartedCompleter?.complete();
if (stayResident && !traceStartup)
if (stayResident && !traceStartup) {
return waitForAppToFinish();
}
await cleanupAtFinish();
return 0;
}
@ -203,8 +207,9 @@ class ColdRunner extends ResidentRunner {
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();
}

View file

@ -164,8 +164,9 @@ class HotRunner extends ResidentRunner {
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 @@ class HotRunner extends ResidentRunner {
'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 @@ class HotRunner extends ResidentRunner {
}
int result = 0;
if (stayResident)
if (stayResident) {
result = await waitForAppToFinish();
}
await cleanupAtFinish();
return result;
}
@ -240,8 +245,9 @@ class HotRunner extends ResidentRunner {
}) 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 @@ class HotRunner extends ResidentRunner {
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 @@ class HotRunner extends ResidentRunner {
}
void _resetDirtyAssets() {
for (FlutterDevice device in flutterDevices)
for (FlutterDevice device in flutterDevices) {
device.devFS.assetPathsToEvict.clear();
}
}
Future<void> _cleanupDevFS() async {
@ -343,8 +351,9 @@ class HotRunner extends ResidentRunner {
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 @@ class HotRunner extends ResidentRunner {
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 @@ class HotRunner extends ResidentRunner {
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 @@ class HotRunner extends ResidentRunner {
)
)
)) {
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 @@ class HotRunner extends ResidentRunner {
}
}
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 @@ class HotRunner extends ResidentRunner {
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 @@ class HotRunner extends ResidentRunner {
_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 @@ class HotRunner extends ResidentRunner {
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 @@ class HotRunner extends ResidentRunner {
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;

View file

@ -158,12 +158,13 @@ abstract class FlutterCommand extends Command<void> {
}
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 @@ abstract class FlutterCommand extends Command<void> {
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 @@ abstract class FlutterCommand extends Command<void> {
/// 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 @@ abstract class FlutterCommand extends Command<void> {
// 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));
}
}
}

View file

@ -121,8 +121,9 @@ class FlutterCommandRunner extends CommandRunner<void> {
'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 @@ class FlutterCommandRunner extends CommandRunner<void> {
'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 @@ class FlutterCommandRunner extends CommandRunner<void> {
}
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
}
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
}
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
}
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 @@ class FlutterCommandRunner extends CommandRunner<void> {
})
.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 @@ class FlutterCommandRunner extends CommandRunner<void> {
}
final String parent = fs.path.dirname(directory);
if (parent == directory)
if (parent == directory) {
break;
}
directory = parent;
}

View file

@ -17,8 +17,9 @@ const String _kFlutterServicesManifestPath = 'flutter_services.yaml';
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 @@ Future<void> parseServiceConfigs(
}
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)));
}
}
}
}

View file

@ -91,8 +91,9 @@ class Template {
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 @@ class Template {
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 @@ class Template {
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++;

View file

@ -78,8 +78,9 @@ class CoverageCollector extends TestWatcher {
});
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 @@ class CoverageCollector extends TestWatcher {
);
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 @@ class CoverageCollector extends TestWatcher {
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 @@ class CoverageCollector extends TestWatcher {
'--add-tracefile', sourceFile.path,
'--output-file', coverageFile.path,
]);
if (result.exitCode != 0)
if (result.exitCode != 0) {
return false;
}
} finally {
tempDir.deleteSync(recursive: true);
}

View file

@ -418,8 +418,9 @@ class FlutterPlatform extends PlatformPlugin {
});
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 @@ class FlutterPlatform extends PlatformPlugin {
//
// 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');
}

View file

@ -96,8 +96,9 @@ Future<int> runTests(
// 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;

View file

@ -115,8 +115,9 @@ class FlutterTesterDevice extends Device {
}
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 @@ class FlutterTesterDevice extends Device {
'--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 @@ class FlutterTesterDevice extends Device {
_logReader.addLine(line);
});
if (!debuggingOptions.debuggingEnabled)
if (!debuggingOptions.debuggingEnabled) {
return LaunchResult.succeeded();
}
final ProtocolDiscovery observatoryDiscovery = ProtocolDiscovery.observatory(
getLogReader(),
@ -248,8 +253,9 @@ class _FlutterTesterDeviceLogReader extends DeviceLogReader {
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);
}

View file

@ -57,8 +57,9 @@ class Tracing {
break;
}
}
if (!done)
if (!done) {
await whenFirstFrameRendered.future;
}
} catch (exception) {
status.cancel();
rethrow;
@ -138,8 +139,9 @@ Future<void> downloadStartupTrace(VMService observatory, { bool awaitFirstFrame
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));

View file

@ -177,16 +177,18 @@ class FlutterVersion {
.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 @@ class FlutterVersion {
}();
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 @@ class FlutterVersion {
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 @@ class VersionCheckStamp {
}) 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 @@ class VersionCheckStamp {
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 @@ class VersionCheckError implements Exception {
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 @@ String _runGit(String command) {
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 @@ Future<String> _run(List<String> command) async {
}
String _shortGitRevision(String revision) {
if (revision == null)
if (revision == null) {
return '';
}
return revision.length > 10 ? revision.substring(0, 10) : revision;
}
@ -610,15 +624,18 @@ class GitTagVersion {
}
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';
}
}

View file

@ -72,15 +72,17 @@ Future<StreamChannel<String>> _defaultOpenChannel(Uri uri, {io.CompressionOption
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 @@ class VMService {
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 @@ class VMService {
_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 @@ class VMService {
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 @@ void _upgradeCollection(
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 @@ abstract class ServiceObject {
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 @@ abstract class ServiceObject {
/// 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 @@ abstract class ServiceObject {
// 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 @@ class VM extends ServiceObjectOwner {
@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 @@ class VM extends ServiceObjectOwner {
_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 @@ class VM extends ServiceObjectOwner {
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 @@ class VM extends ServiceObjectOwner {
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 @@ class VM extends ServiceObjectOwner {
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 @@ class VM extends ServiceObjectOwner {
// 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 @@ class VM extends ServiceObjectOwner {
}
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 @@ class Isolate extends ServiceObjectOwner {
@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 @@ class Isolate extends ServiceObjectOwner {
}
// 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 @@ class Isolate extends ServiceObjectOwner {
@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 @@ class Isolate extends ServiceObjectOwner {
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 @@ class Isolate extends ServiceObjectOwner {
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 @@ class Isolate extends ServiceObjectOwner {
'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 @@ class FlutterView extends ServiceObject {
// launch errors.
if (event.kind == ServiceEvent.kIsolateRunnable) {
printTrace('Isolate is runnable.');
if (!completer.isCompleted)
if (!completer.isCompleted) {
completer.complete();
}
}
});
await owner.vm.runInView(viewId,

View file

@ -225,8 +225,9 @@ class ReplayVMServiceChannel extends StreamChannelMixin<String> {
}
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 @@ class ReplayVMServiceChannel extends StreamChannelMixin<String> {
exit(0);
} else {
_controller.add(json.encoder.convert(transaction.response.data));
if (_transactions.isEmpty)
if (_transactions.isEmpty) {
_controller.close();
}
}
}
@ -266,8 +268,9 @@ class _ReplaySink implements StreamSink<String> {
@override
void add(String data) {
if (_completer.isCompleted)
if (_completer.isCompleted) {
throw StateError('Sink already closed');
}
channel.send(_Request.fromString(data));
}

View file

@ -66,8 +66,9 @@ class VsCode {
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 @@ class VsCode {
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 @@ class VsCode {
'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'];

View file

@ -58,8 +58,9 @@ class _FakeGenSnapshot implements GenSnapshot {
_depfilePath = depfilePath;
_additionalArgs = additionalArgs.toList();
if (!succeed)
if (!succeed) {
return 1;
}
outputs.forEach((String filePath, String fileContent) {
fs.file(filePath).writeAsString(fileContent);
});

View file

@ -26,8 +26,9 @@ void main() {
});
tearDown(() {
if (daemon != null)
if (daemon != null) {
return daemon.shutdown();
}
notifyingLogger.dispose();
});

View file

@ -191,8 +191,9 @@ void main() {
].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();
}
}
}

View file

@ -74,8 +74,9 @@ void main() {
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 @@ void main() {
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 @@ void main() {
(!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 @@ void main() {
(!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 @@ Future<void> _testFile(
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 @@ Future<void> _testFile(
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 @@ Future<void> _testFile(
outputLineNumber += 1;
}
expect(allowSkip, isFalse);
if (!haveSeenStdErrMarker)
if (!haveSeenStdErrMarker) {
expect(exec.stderr, '');
}
}
Future<ProcessResult> _runFlutterTest(
@ -214,14 +225,16 @@ Future<ProcessResult> _runFlutterTest(
// 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 @@ Future<ProcessResult> _runFlutterTest(
testPath
];
while (_testExclusionLock != null)
while (_testExclusionLock != null) {
await _testExclusionLock;
}
final Completer<void> testExclusionCompleter = Completer<void>();
_testExclusionLock = testExclusionCompleter.future;

View file

@ -286,8 +286,9 @@ class MockCrashReportSender extends MockClient {
.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];

View file

@ -302,8 +302,9 @@ Directory _newTempDir(FileSystem fs) {
}
void _cleanupTempDirs() {
while (_tempDirs.isNotEmpty)
while (_tempDirs.isNotEmpty) {
tryToDelete(_tempDirs.removeLast());
}
}
Future<void> _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async {

View file

@ -648,8 +648,9 @@ class FakeIosDoctorProvider implements DoctorValidatorsProvider {
List<Workflow> get workflows {
if (_workflows == null) {
_workflows = <Workflow>[];
if (iosWorkflow.appliesToHostPlatform)
if (iosWorkflow.appliesToHostPlatform) {
_workflows.add(iosWorkflow);
}
}
return _workflows;
}

View file

@ -157,10 +157,11 @@ baz=qux
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);

View file

@ -74,8 +74,9 @@ class MockPeer implements rpc.Peer {
@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') {

View file

@ -28,8 +28,9 @@ abstract class Project {
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
}
}

View file

@ -71,8 +71,9 @@ abstract class FlutterTestDriver {
} else {
lastTime = time;
}
if (_printDebugOutputToStdOut)
if (_printDebugOutputToStdOut) {
print('$time$_logPrefix$line');
}
}
Future<void> _setupProcess(
@ -82,10 +83,12 @@ abstract class FlutterTestDriver {
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 @@ abstract class FlutterTestDriver {
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 @@ abstract class FlutterTestDriver {
&& 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 @@ abstract class FlutterTestDriver {
}
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 @@ abstract class FlutterTestDriver {
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 @@ class FlutterRunTestDriver extends FlutterTestDriver {
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 @@ class FlutterRunTestDriver extends FlutterTestDriver {
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 @@ class FlutterRunTestDriver extends FlutterTestDriver {
);
_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 @@ class FlutterRunTestDriver extends FlutterTestDriver {
_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'];
}

View file

@ -50,6 +50,7 @@ Future<void> getPackages(String folder) async {
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');
}
}

View file

@ -38,8 +38,9 @@ void tryToDelete(Directory directory) {
/// 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 @@ String getFlutterRoot() {
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 @@ String getFlutterRoot() {
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 @@ void updateFileModificationTime(
/// 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);
}

View file

@ -129,8 +129,9 @@ void testUsingContext(
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 @@ class FakeDeviceManager implements DeviceManager {
@override
String get specifiedDeviceId {
if (_specifiedDeviceId == null || _specifiedDeviceId == 'all')
if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') {
return null;
}
return _specifiedDeviceId;
}

View file

@ -77,8 +77,9 @@ class MockAndroidSdk extends Mock implements AndroidSdk {
_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 @@ class MockAndroidSdk extends Mock implements AndroidSdk {
_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 @@ class PromptingProcess implements Process {
// 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 @@ class CompleterIOSink extends MemoryIOSink {
@override
void add(List<int> data) {
if (!_completer.isCompleted)
if (!_completer.isCompleted) {
_completer.complete(data);
}
super.add(data);
}
}
@ -434,8 +438,9 @@ class MemoryStdout extends MemoryIOSink implements io.Stdout {
@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 @@ class MemoryStdout extends MemoryIOSink implements io.Stdout {
@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;