Commit 7a09316c authored by Chris Bracken's avatar Chris Bracken Committed by GitHub

Declare locals final where not reassigned (flutter_tools) (#8570)

parent 46291903
......@@ -35,7 +35,7 @@ const List<String> _kRequiredOptions = const <String>[
];
Future<Null> main(List<String> args) async {
AppContext executableContext = new AppContext();
final AppContext executableContext = new AppContext();
executableContext.setVariable(Logger, new StdoutLogger());
executableContext.runInZone(() {
// Initialize the context with some defaults.
......@@ -66,7 +66,7 @@ Future<Null> run(List<String> args) async {
exit(1);
}
Cache.flutterRoot = platform.environment['FLUTTER_ROOT'];
String outputPath = argResults[_kOptionOutput];
final String outputPath = argResults[_kOptionOutput];
try {
await assemble(
outputPath: outputPath,
......
......@@ -60,10 +60,10 @@ import 'src/usage.dart';
///
/// This function is intended to be used from the `flutter` command line tool.
Future<Null> main(List<String> args) async {
bool verbose = args.contains('-v') || args.contains('--verbose');
bool help = args.contains('-h') || args.contains('--help') ||
final bool verbose = args.contains('-v') || args.contains('--verbose');
final bool help = args.contains('-h') || args.contains('--help') ||
(args.isNotEmpty && args.first == 'help') || (args.length == 1 && verbose);
bool verboseHelp = help && verbose;
final bool verboseHelp = help && verbose;
await run(args, <FlutterCommand>[
new AnalyzeCommand(verboseHelp: verboseHelp),
......@@ -104,11 +104,11 @@ Future<int> run(List<String> args, List<FlutterCommand> subCommands, {
args.removeWhere((String option) => option == '-v' || option == '--verbose');
}
FlutterCommandRunner runner = new FlutterCommandRunner(verboseHelp: verboseHelp);
final FlutterCommandRunner runner = new FlutterCommandRunner(verboseHelp: verboseHelp);
subCommands.forEach(runner.addCommand);
// Construct a context.
AppContext _executableContext = new AppContext();
final AppContext _executableContext = new AppContext();
// Make the context current.
return await _executableContext.runInZone(() async {
......@@ -140,7 +140,7 @@ Future<int> run(List<String> args, List<FlutterCommand> subCommands, {
// Initialize the system locale.
await intl.findSystemLocale();
Completer<int> runCompleter = new Completer<int>();
final Completer<int> runCompleter = new Completer<int>();
Chain.capture<Future<Null>>(() async {
await runner.run(args);
await _exit(0);
......@@ -206,7 +206,7 @@ Future<int> _handleToolError(
flutterVersion: flutterVersion,
);
try {
File file = await _createLocalCrashReport(args, error, chain);
final File file = await _createLocalCrashReport(args, error, chain);
stderr.writeln(
'Crash report written to ${file.path};\n'
'please let us know at https://github.com/flutter/flutter/issues.',
......@@ -235,7 +235,7 @@ FileSystem crashFileSystem = new LocalFileSystem();
Future<File> _createLocalCrashReport(List<String> args, dynamic error, Chain chain) async {
File crashFile = getUniqueFile(crashFileSystem.currentDirectory, 'flutter', 'log');
StringBuffer buffer = new StringBuffer();
final StringBuffer buffer = new StringBuffer();
buffer.writeln('Flutter crash report; please file at https://github.com/flutter/flutter/issues.\n');
......@@ -267,8 +267,8 @@ Future<File> _createLocalCrashReport(List<String> args, dynamic error, Chain cha
Future<String> _doctorText() async {
try {
BufferLogger logger = new BufferLogger();
AppContext appContext = new AppContext();
final BufferLogger logger = new BufferLogger();
final AppContext appContext = new AppContext();
appContext.setVariable(Logger, logger);
......@@ -287,7 +287,7 @@ Future<int> _exit(int code) async {
// Send any last analytics calls that are in progress without overly delaying
// the tool's exit (we wait a maximum of 250ms).
if (flutterUsage.enabled) {
Stopwatch stopwatch = new Stopwatch()..start();
final Stopwatch stopwatch = new Stopwatch()..start();
await flutterUsage.ensureAnalyticsSent();
printTrace('ensureAnalyticsSent: ${stopwatch.elapsedMilliseconds}ms');
}
......@@ -295,7 +295,7 @@ Future<int> _exit(int code) async {
// Run shutdown hooks before flushing logs
await runShutdownHooks();
Completer<Null> completer = new Completer<Null>();
final Completer<Null> completer = new Completer<Null>();
// Give the task / timer queue one cycle through before we hard exit.
Timer.run(() {
......
......@@ -51,7 +51,7 @@ class Adb {
/// Ask the ADB server for its internal version number.
Future<String> getServerVersion() {
return _sendAdbServerCommand('host:version').then((String response) {
_AdbServerResponse adbResponse = new _AdbServerResponse(response);
final _AdbServerResponse adbResponse = new _AdbServerResponse(response);
if (adbResponse.isOkay)
return adbResponse.message;
throw adbResponse.message;
......@@ -60,11 +60,11 @@ class Adb {
/// Queries the adb server for the list of connected adb devices.
Future<List<AdbDevice>> listDevices() async {
String stringResponse = await _sendAdbServerCommand('host:devices-l');
_AdbServerResponse response = new _AdbServerResponse(stringResponse);
final String stringResponse = await _sendAdbServerCommand('host:devices-l');
final _AdbServerResponse response = new _AdbServerResponse(stringResponse);
if (response.isFail)
throw response.message;
String message = response.message.trim();
final String message = response.message.trim();
if (message.isEmpty)
return <AdbDevice>[];
return message.split('\n').map(
......@@ -73,16 +73,16 @@ class Adb {
}
Future<String> _sendAdbServerCommand(String command) async {
Socket socket = await Socket.connect(InternetAddress.LOOPBACK_IP_V4, adbServerPort);
final Socket socket = await Socket.connect(InternetAddress.LOOPBACK_IP_V4, adbServerPort);
try {
printTrace('--> $command');
socket.add(_createAdbRequest(command));
List<List<int>> result = await socket.toList();
List<int> data = result.fold(<int>[], (List<int> previous, List<int> element) {
final List<List<int>> result = await socket.toList();
final List<int> data = result.fold(<int>[], (List<int> previous, List<int> element) {
return previous..addAll(element);
});
String stringResult = new String.fromCharCodes(data);
final String stringResult = new String.fromCharCodes(data);
printTrace('<-- ${stringResult.trim()}');
return stringResult;
} finally {
......@@ -97,7 +97,7 @@ class AdbDevice {
// 'TA95000FQA device usb:340787200X product:peregrine_retus model:XT1045 device:peregrine'
// '015d172c98400a03 device usb:340787200X product:nakasi model:Nexus_7 device:grouper'
Match match = kDeviceRegex.firstMatch(deviceInfo);
final Match match = kDeviceRegex.firstMatch(deviceInfo);
id = match[1];
status = match[2];
......@@ -106,7 +106,7 @@ class AdbDevice {
rest = rest.trim();
for (String data in rest.split(' ')) {
if (data.contains(':')) {
List<String> fields = data.split(':');
final List<String> fields = data.split(':');
_info[fields[0]] = fields[1];
}
}
......@@ -183,11 +183,11 @@ String cleanAdbDeviceName(String name) {
}
List<int> _createAdbRequest(String payload) {
List<int> data = payload.codeUnits;
final List<int> data = payload.codeUnits;
// A 4-byte hexadecimal string giving the length of the payload.
String prefix = data.length.toRadixString(16).padLeft(4, '0');
List<int> result = <int>[];
final String prefix = data.length.toRadixString(16).padLeft(4, '0');
final List<int> result = <int>[];
result.addAll(prefix.codeUnits);
result.addAll(data);
return result;
......
......@@ -44,7 +44,7 @@ String getAdbPath([AndroidSdk existingSdk]) {
if (existingSdk?.adbPath != null)
return existingSdk.adbPath;
AndroidSdk sdk = AndroidSdk.locateAndroidSdk();
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk();
if (sdk?.latestVersion == null) {
return os.which('adb')?.path;
......@@ -89,7 +89,7 @@ class AndroidSdk {
if (aaptBin != null) {
// Make sure we're using the aapt from the SDK.
aaptBin = fs.file(aaptBin.resolveSymbolicLinksSync());
String dir = aaptBin.parent.parent.parent.path;
final String dir = aaptBin.parent.parent.parent.path;
if (validSdkDirectory(dir))
return new AndroidSdk(dir);
}
......@@ -98,7 +98,7 @@ class AndroidSdk {
if (adbBin != null) {
// Make sure we're using the adb from the SDK.
adbBin = fs.file(adbBin.resolveSymbolicLinksSync());
String dir = adbBin.parent.parent.path;
final String dir = adbBin.parent.parent.path;
if (validSdkDirectory(dir))
return new AndroidSdk(dir);
}
......@@ -137,7 +137,7 @@ class AndroidSdk {
void _init() {
List<String> platforms = <String>[]; // android-22, ...
Directory platformsDir = fs.directory(fs.path.join(directory, 'platforms'));
final Directory platformsDir = fs.directory(fs.path.join(directory, 'platforms'));
if (platformsDir.existsSync()) {
platforms = platformsDir
.listSync()
......@@ -148,7 +148,7 @@ class AndroidSdk {
List<Version> buildTools = <Version>[]; // 19.1.0, 22.0.1, ...
Directory buildToolsDir = fs.directory(fs.path.join(directory, 'build-tools'));
final Directory buildToolsDir = fs.directory(fs.path.join(directory, 'build-tools'));
if (buildToolsDir.existsSync()) {
buildTools = buildToolsDir
.listSync()
......
......@@ -34,7 +34,7 @@ final RegExp _dotHomeStudioVersionMatcher =
/// Locate Gradle.
String get gradleExecutable {
// See if the user has explicitly configured gradle-dir.
String gradleDir = config.getValue('gradle-dir');
final String gradleDir = config.getValue('gradle-dir');
if (gradleDir != null) {
if (fs.isFileSync(gradleDir))
return gradleDir;
......@@ -58,9 +58,9 @@ class AndroidStudio implements Comparable<AndroidStudio> {
List<String> _validationMessages = <String>[];
factory AndroidStudio.fromMacOSBundle(String bundlePath) {
String studioPath = fs.path.join(bundlePath, 'Contents');
String plistFile = fs.path.join(studioPath, 'Info.plist');
String versionString =
final String studioPath = fs.path.join(bundlePath, 'Contents');
final String plistFile = fs.path.join(studioPath, 'Info.plist');
final String versionString =
getValueFromFile(plistFile, kCFBundleShortVersionStringKey);
Version version;
if (versionString != null)
......@@ -69,12 +69,12 @@ class AndroidStudio implements Comparable<AndroidStudio> {
}
factory AndroidStudio.fromHomeDot(Directory homeDotDir) {
Match versionMatch =
final Match versionMatch =
_dotHomeStudioVersionMatcher.firstMatch(homeDotDir.basename);
if (versionMatch?.groupCount != 2) {
return null;
}
Version version = new Version.parse(versionMatch[2]);
final Version version = new Version.parse(versionMatch[2]);
if (version == null) {
return null;
}
......@@ -103,7 +103,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
@override
int compareTo(AndroidStudio other) {
int result = version.compareTo(other.version);
final int result = version.compareTo(other.version);
if (result == 0)
return directory.compareTo(other.directory);
return result;
......@@ -111,7 +111,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
/// Locates the newest, valid version of Android Studio.
static AndroidStudio latestValid() {
String configuredStudio = config.getValue('android-studio-dir');
final String configuredStudio = config.getValue('android-studio-dir');
if (configuredStudio != null) {
String configuredStudioPath = configuredStudio;
if (platform.isMacOS && !configuredStudioPath.endsWith('Contents'))
......@@ -121,7 +121,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
}
// Find all available Studio installations.
List<AndroidStudio> studios = allInstalled();
final List<AndroidStudio> studios = allInstalled();
if (studios.isEmpty) {
return null;
}
......@@ -134,13 +134,13 @@ class AndroidStudio implements Comparable<AndroidStudio> {
platform.isMacOS ? _allMacOS() : _allLinuxOrWindows();
static List<AndroidStudio> _allMacOS() {
List<FileSystemEntity> candidatePaths = <FileSystemEntity>[];
final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[];
void _checkForStudio(String path) {
if (!fs.isDirectorySync(path))
return;
try {
Iterable<Directory> directories = fs
final Iterable<Directory> directories = fs
.directory(path)
.listSync()
.where((FileSystemEntity e) => e is Directory);
......@@ -159,7 +159,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
_checkForStudio('/Applications');
_checkForStudio(fs.path.join(homeDirPath, 'Applications'));
String configuredStudioDir = config.getValue('android-studio-dir');
final String configuredStudioDir = config.getValue('android-studio-dir');
if (configuredStudioDir != null) {
FileSystemEntity configuredStudio = fs.file(configuredStudioDir);
if (configuredStudio.basename == 'Contents') {
......@@ -178,7 +178,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
}
static List<AndroidStudio> _allLinuxOrWindows() {
List<AndroidStudio> studios = <AndroidStudio>[];
final List<AndroidStudio> studios = <AndroidStudio>[];
bool _hasStudioAt(String path, {Version newerThan}) {
return studios.any((AndroidStudio studio) {
......@@ -194,7 +194,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
// pointing to the same installation, so we grab only the latest one.
for (FileSystemEntity entity in fs.directory(homeDirPath).listSync()) {
if (entity is Directory && entity.basename.startsWith('.AndroidStudio')) {
AndroidStudio studio = new AndroidStudio.fromHomeDot(entity);
final AndroidStudio studio = new AndroidStudio.fromHomeDot(entity);
if (studio != null &&
!_hasStudioAt(studio.directory, newerThan: studio.version)) {
studios.removeWhere(
......@@ -204,7 +204,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
}
}
String configuredStudioDir = config.getValue('android-studio-dir');
final String configuredStudioDir = config.getValue('android-studio-dir');
if (configuredStudioDir != null && !_hasStudioAt(configuredStudioDir)) {
studios.add(new AndroidStudio(configuredStudioDir,
configured: configuredStudioDir));
......@@ -244,7 +244,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
gradlePaths = fs.directory(fs.path.join(directory, 'gradle')).listSync();
for (FileSystemEntity entry in gradlePaths.where((FileSystemEntity e) =>
e.basename.startsWith('gradle-') && e is Directory)) {
Version version =
final Version version =
new Version.parse(entry.basename.substring('gradle-'.length)) ??
Version.unknown;
if (latestGradleVersion == null || version > latestGradleVersion) {
......
......@@ -19,15 +19,15 @@ class AndroidStudioValidator extends DoctorValidator {
AndroidStudioValidator(this._studio) : super('Android Studio');
static List<DoctorValidator> get allValidators {
List<DoctorValidator> validators = <DoctorValidator>[];
List<AndroidStudio> studios = AndroidStudio.allInstalled();
final List<DoctorValidator> validators = <DoctorValidator>[];
final List<AndroidStudio> studios = AndroidStudio.allInstalled();
if (studios.isEmpty) {
validators.add(new NoAndroidStudioValidator());
} else {
validators.addAll(studios
.map((AndroidStudio studio) => new AndroidStudioValidator(studio)));
}
String cfgGradleDir = config.getValue('gradle-dir');
final String cfgGradleDir = config.getValue('gradle-dir');
if (cfgGradleDir != null) {
validators.add(new ConfiguredGradleValidator(cfgGradleDir));
}
......@@ -36,9 +36,9 @@ class AndroidStudioValidator extends DoctorValidator {
@override
Future<ValidationResult> validate() async {
List<ValidationMessage> messages = <ValidationMessage>[];
final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType type = ValidationType.missing;
String studioVersionText = 'version ${_studio.version}';
final String studioVersionText = 'version ${_studio.version}';
messages
.add(new ValidationMessage('Android Studio at ${_studio.directory}'));
if (_studio.isValid) {
......@@ -66,9 +66,9 @@ class NoAndroidStudioValidator extends DoctorValidator {
@override
Future<ValidationResult> validate() async {
List<ValidationMessage> messages = <ValidationMessage>[];
final List<ValidationMessage> messages = <ValidationMessage>[];
String cfgAndroidStudio = config.getValue('android-studio-dir');
final String cfgAndroidStudio = config.getValue('android-studio-dir');
if (cfgAndroidStudio != null) {
messages.add(
new ValidationMessage.error('android-studio-dir = $cfgAndroidStudio\n'
......@@ -91,7 +91,7 @@ class ConfiguredGradleValidator extends DoctorValidator {
@override
Future<ValidationResult> validate() async {
ValidationType type = ValidationType.missing;
List<ValidationMessage> messages = <ValidationMessage>[];
final List<ValidationMessage> messages = <ValidationMessage>[];
messages.add(new ValidationMessage('gradle-dir = $cfgGradleDir'));
......@@ -103,7 +103,7 @@ class ConfiguredGradleValidator extends DoctorValidator {
String versionString;
if (processManager.canRun(gradleExecutable)) {
type = ValidationType.partial;
ProcessResult result =
final ProcessResult result =
processManager.runSync(<String>[gradleExecutable, '--version']);
if (result.exitCode == 0) {
versionString = result.stdout
......@@ -111,7 +111,7 @@ class ConfiguredGradleValidator extends DoctorValidator {
.split('\n')
.firstWhere((String s) => s.startsWith('Gradle '))
.substring('Gradle '.length);
Version version = new Version.parse(versionString) ?? Version.unknown;
final Version version = new Version.parse(versionString) ?? Version.unknown;
if (version >= minGradleVersion) {
type = ValidationType.installed;
} else {
......
......@@ -25,13 +25,13 @@ class AndroidWorkflow extends DoctorValidator implements Workflow {
@override
Future<ValidationResult> validate() async {
List<ValidationMessage> messages = <ValidationMessage>[];
final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType type = ValidationType.missing;
String sdkVersionText;
if (androidSdk == null) {
if (platform.environment.containsKey(kAndroidHome)) {
String androidHomeDir = platform.environment[kAndroidHome];
final String androidHomeDir = platform.environment[kAndroidHome];
messages.add(new ValidationMessage.error(
'$kAndroidHome = $androidHomeDir\n'
'but Android SDK not found at this location.'
......@@ -57,11 +57,11 @@ class AndroidWorkflow extends DoctorValidator implements Workflow {
}
if (platform.environment.containsKey(kAndroidHome)) {
String androidHomeDir = platform.environment[kAndroidHome];
final String androidHomeDir = platform.environment[kAndroidHome];
messages.add(new ValidationMessage('$kAndroidHome = $androidHomeDir'));
}
List<String> validationResult = androidSdk.validateSdkWellFormed();
final List<String> validationResult = androidSdk.validateSdkWellFormed();
if (validationResult.isEmpty) {
// Empty result means SDK is well formed.
......@@ -72,10 +72,10 @@ class AndroidWorkflow extends DoctorValidator implements Workflow {
try {
printTrace('java -version');
ProcessResult result = processManager.runSync(<String>['java', '-version']);
final ProcessResult result = processManager.runSync(<String>['java', '-version']);
if (result.exitCode == 0) {
javaVersion = result.stderr;
List<String> versionLines = javaVersion.split('\n');
final List<String> versionLines = javaVersion.split('\n');
javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
}
} catch (error) {
......
......@@ -35,15 +35,15 @@ bool isProjectUsingGradle() {
}
FlutterPluginVersion get flutterPluginVersion {
File plugin = fs.file('android/buildSrc/src/main/groovy/FlutterPlugin.groovy');
final File plugin = fs.file('android/buildSrc/src/main/groovy/FlutterPlugin.groovy');
if (plugin.existsSync()) {
String packageLine = plugin.readAsLinesSync().skip(4).first;
final String packageLine = plugin.readAsLinesSync().skip(4).first;
if (packageLine == "package io.flutter.gradle") {
return FlutterPluginVersion.v2;
}
return FlutterPluginVersion.v1;
}
File appGradle = fs.file('android/app/build.gradle');
final File appGradle = fs.file('android/app/build.gradle');
if (appGradle.existsSync()) {
for (String line in appGradle.readAsLinesSync()) {
if (line.contains(new RegExp(r"apply from: .*/flutter.gradle"))) {
......@@ -69,9 +69,9 @@ String get gradleAppOut {
}
String locateSystemGradle({ bool ensureExecutable: true }) {
String gradle = gradleExecutable;
final String gradle = gradleExecutable;
if (ensureExecutable && gradle != null) {
File file = fs.file(gradle);
final File file = fs.file(gradle);
if (file.existsSync())
os.makeExecutable(file);
}
......@@ -104,7 +104,7 @@ Future<String> ensureGradle() async {
Future<Null> buildGradleProject(BuildMode buildMode, String target) async {
// Create android/local.properties.
File localProperties = fs.file('android/local.properties');
final File localProperties = fs.file('android/local.properties');
if (!localProperties.existsSync()) {
localProperties.writeAsStringSync(
'sdk.dir=${_escapePath(androidSdk.directory)}\n'
......@@ -115,12 +115,12 @@ Future<Null> buildGradleProject(BuildMode buildMode, String target) async {
// FlutterPlugin v1 reads local.properties to determine build mode. Plugin v2
// uses the standard Android way to determine what to build, but we still
// update local.properties, in case we want to use it in the future.
String buildModeName = getModeName(buildMode);
SettingsFile settings = new SettingsFile.parseFromFile(localProperties);
final String buildModeName = getModeName(buildMode);
final SettingsFile settings = new SettingsFile.parseFromFile(localProperties);
settings.values['flutter.buildMode'] = buildModeName;
settings.writeContents(localProperties);
String gradle = await ensureGradle();
final String gradle = await ensureGradle();
switch (flutterPluginVersion) {
case FlutterPluginVersion.none:
......@@ -138,8 +138,8 @@ String _escapePath(String path) => platform.isWindows ? path.replaceAll('\\', '\
Future<Null> buildGradleProjectV1(String gradle) async {
// Run 'gradle build'.
Status status = logger.startProgress('Running \'gradle build\'...', expectSlowOperation: true);
int exitcode = await runCommandAndStreamOutput(
final Status status = logger.startProgress('Running \'gradle build\'...', expectSlowOperation: true);
final int exitcode = await runCommandAndStreamOutput(
<String>[fs.file(gradle).absolute.path, 'build'],
workingDirectory: 'android',
allowReentrantFlutter: true
......@@ -149,22 +149,22 @@ Future<Null> buildGradleProjectV1(String gradle) async {
if (exitcode != 0)
throwToolExit('Gradle build failed: $exitcode', exitCode: exitcode);
File apkFile = fs.file(gradleAppOutV1);
final File apkFile = fs.file(gradleAppOutV1);
printStatus('Built $gradleAppOutV1 (${getSizeAsMB(apkFile.lengthSync())}).');
}
Future<Null> buildGradleProjectV2(String gradle, String buildModeName, String target) async {
String assembleTask = "assemble${toTitleCase(buildModeName)}";
final String assembleTask = "assemble${toTitleCase(buildModeName)}";
// Run 'gradle assemble<BuildMode>'.
Status status = logger.startProgress('Running \'gradle $assembleTask\'...', expectSlowOperation: true);
String gradlePath = fs.file(gradle).absolute.path;
List<String> command = <String>[gradlePath];
final Status status = logger.startProgress('Running \'gradle $assembleTask\'...', expectSlowOperation: true);
final String gradlePath = fs.file(gradle).absolute.path;
final List<String> command = <String>[gradlePath];
if (!logger.isVerbose) {
command.add('-q');
}
if (artifacts is LocalEngineArtifacts) {
LocalEngineArtifacts localEngineArtifacts = artifacts;
final LocalEngineArtifacts localEngineArtifacts = artifacts;
printTrace('Using local engine: ${localEngineArtifacts.engineOutPath}');
command.add('-PlocalEngineOut=${localEngineArtifacts.engineOutPath}');
}
......@@ -172,7 +172,7 @@ Future<Null> buildGradleProjectV2(String gradle, String buildModeName, String ta
command.add('-Ptarget=$target');
}
command.add(assembleTask);
int exitcode = await runCommandAndStreamOutput(
final int exitcode = await runCommandAndStreamOutput(
command,
workingDirectory: 'android',
allowReentrantFlutter: true
......@@ -182,13 +182,13 @@ Future<Null> buildGradleProjectV2(String gradle, String buildModeName, String ta
if (exitcode != 0)
throwToolExit('Gradle build failed: $exitcode', exitCode: exitcode);
String apkFilename = 'app-$buildModeName.apk';
File apkFile = fs.file('$gradleAppOutDir/$apkFilename');
final String apkFilename = 'app-$buildModeName.apk';
final File apkFile = fs.file('$gradleAppOutDir/$apkFilename');
// Copy the APK to app.apk, so `flutter run`, `flutter install`, etc. can find it.
apkFile.copySync('$gradleAppOutDir/app.apk');
printTrace('calculateSha: $gradleAppOutDir/app.apk');
File apkShaFile = fs.file('$gradleAppOutDir/app.apk.sha1');
final File apkShaFile = fs.file('$gradleAppOutDir/app.apk.sha1');
apkShaFile.writeAsStringSync(calculateSha(apkFile));
printStatus('Built $apkFilename (${getSizeAsMB(apkFile.lengthSync())}).');
......
......@@ -50,14 +50,14 @@ class AndroidApk extends ApplicationPackage {
/// Creates a new AndroidApk from an existing APK.
factory AndroidApk.fromApk(String applicationBinary) {
String aaptPath = androidSdk?.latestVersion?.aaptPath;
final String aaptPath = androidSdk?.latestVersion?.aaptPath;
if (aaptPath == null) {
printError('Unable to locate the Android SDK; please run \'flutter doctor\'.');
return null;
}
List<String> aaptArgs = <String>[aaptPath, 'dump', 'badging', applicationBinary];
ApkManifestData data = ApkManifestData.parseFromAaptBadging(runCheckedSync(aaptArgs));
final List<String> aaptArgs = <String>[aaptPath, 'dump', 'badging', applicationBinary];
final ApkManifestData data = ApkManifestData.parseFromAaptBadging(runCheckedSync(aaptArgs));
if (data == null) {
printError('Unable to read manifest info from $applicationBinary.');
......@@ -100,19 +100,19 @@ class AndroidApk extends ApplicationPackage {
if (!fs.isFileSync(manifestPath))
return null;
String manifestString = fs.file(manifestPath).readAsStringSync();
xml.XmlDocument document = xml.parse(manifestString);
final String manifestString = fs.file(manifestPath).readAsStringSync();
final xml.XmlDocument document = xml.parse(manifestString);
Iterable<xml.XmlElement> manifests = document.findElements('manifest');
final Iterable<xml.XmlElement> manifests = document.findElements('manifest');
if (manifests.isEmpty)
return null;
String packageId = manifests.first.getAttribute('package');
final String packageId = manifests.first.getAttribute('package');
String launchActivity;
for (xml.XmlElement category in document.findAllElements('category')) {
if (category.getAttribute('android:name') == 'android.intent.category.LAUNCHER') {
xml.XmlElement activity = category.parent.parent;
String activityName = activity.getAttribute('android:name');
final xml.XmlElement activity = category.parent.parent;
final String activityName = activity.getAttribute('android:name');
launchActivity = "$packageId/$activityName";
break;
}
......@@ -146,18 +146,18 @@ abstract class IOSApp extends ApplicationPackage {
factory IOSApp.fromIpa(String applicationBinary) {
Directory bundleDir;
try {
Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app_');
final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app_');
addShutdownHook(() async => await tempDir.delete(recursive: true));
os.unzip(fs.file(applicationBinary), tempDir);
Directory payloadDir = fs.directory(fs.path.join(tempDir.path, 'Payload'));
final Directory payloadDir = fs.directory(fs.path.join(tempDir.path, 'Payload'));
bundleDir = payloadDir.listSync().singleWhere(_isBundleDirectory);
} on StateError catch (e, stackTrace) {
printError('Invalid prebuilt iOS binary: ${e.toString()}', stackTrace);
return null;
}
String plistPath = fs.path.join(bundleDir.path, 'Info.plist');
String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
final String plistPath = fs.path.join(bundleDir.path, 'Info.plist');
final String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
if (id == null)
return null;
......@@ -173,11 +173,11 @@ abstract class IOSApp extends ApplicationPackage {
if (getCurrentHostPlatform() != HostPlatform.darwin_x64)
return null;
String plistPath = fs.path.join('ios', 'Runner', 'Info.plist');
final String plistPath = fs.path.join('ios', 'Runner', 'Info.plist');
String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
if (id == null)
return null;
String projectPath = fs.path.join('ios', 'Runner.xcodeproj');
final String projectPath = fs.path.join('ios', 'Runner.xcodeproj');
id = substituteXcodeVariables(id, projectPath, 'Runner');
return new BuildableIOSApp(
......@@ -299,22 +299,22 @@ class ApkManifestData {
// package: name='io.flutter.gallery' versionCode='1' versionName='0.0.1' platformBuildVersionName='NMR1'
// launchable-activity: name='io.flutter.app.FlutterActivity' label='' icon=''
Map<String, Map<String, String>> map = <String, Map<String, String>>{};
final Map<String, Map<String, String>> map = <String, Map<String, String>>{};
for (String line in data.split('\n')) {
int index = line.indexOf(':');
final int index = line.indexOf(':');
if (index != -1) {
String name = line.substring(0, index);
final String name = line.substring(0, index);
line = line.substring(index + 1).trim();
Map<String, String> entries = <String, String>{};
final Map<String, String> entries = <String, String>{};
map[name] = entries;
for (String entry in line.split(' ')) {
entry = entry.trim();
if (entry.isNotEmpty && entry.contains('=')) {
int split = entry.indexOf('=');
String key = entry.substring(0, split);
final int split = entry.indexOf('=');
final String key = entry.substring(0, split);
String value = entry.substring(split + 1);
if (value.startsWith("'") && value.endsWith("'"))
value = value.substring(1, value.length - 1);
......
......@@ -105,7 +105,7 @@ class CachedArtifacts extends Artifacts {
}
String _getAndroidArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) {
String engineDir = _getEngineArtifactsPath(platform, mode);
final String engineDir = _getEngineArtifactsPath(platform, mode);
switch (artifact) {
case Artifact.chromiumDebugKeyStore:
case Artifact.classesDexJar:
......@@ -119,7 +119,7 @@ class CachedArtifacts extends Artifacts {
return fs.path.join(engineDir, _artifactToFileName(artifact));
case Artifact.genSnapshot:
assert(mode != BuildMode.debug, 'Artifact $artifact only available in non-debug mode.');
String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform());
final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform());
return fs.path.join(engineDir, hostPlatform, _artifactToFileName(artifact));
default:
assert(false, 'Artifact $artifact not available for platform $platform.');
......@@ -128,7 +128,7 @@ class CachedArtifacts extends Artifacts {
}
String _getIosArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) {
String engineDir = _getEngineArtifactsPath(platform, mode);
final String engineDir = _getEngineArtifactsPath(platform, mode);
switch (artifact) {
case Artifact.dartIoEntriesTxt:
case Artifact.dartVmEntryPointsTxt:
......@@ -157,8 +157,8 @@ class CachedArtifacts extends Artifacts {
continue returnResourcePath;
returnResourcePath:
case Artifact.icudtlDat:
String engineArtifactsPath = cache.getArtifactDirectory('engine').path;
String platformDirName = getNameForTargetPlatform(platform);
final String engineArtifactsPath = cache.getArtifactDirectory('engine').path;
final String platformDirName = getNameForTargetPlatform(platform);
return fs.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact));
default:
assert(false, 'Artifact $artifact not available for platform $platform.');
......@@ -169,8 +169,8 @@ class CachedArtifacts extends Artifacts {
}
String _getEngineArtifactsPath(TargetPlatform platform, [BuildMode mode]) {
String engineDir = cache.getArtifactDirectory('engine').path;
String platformName = getNameForTargetPlatform(platform);
final String engineDir = cache.getArtifactDirectory('engine').path;
final String platformName = getNameForTargetPlatform(platform);
switch (platform) {
case TargetPlatform.linux_x64:
case TargetPlatform.darwin_x64:
......@@ -182,7 +182,7 @@ class CachedArtifacts extends Artifacts {
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
assert(mode != null, 'Need to specify a build mode for platform $platform.');
String suffix = mode != BuildMode.debug ? '-${getModeName(mode)}' : '';
final String suffix = mode != BuildMode.debug ? '-${getModeName(mode)}' : '';
return fs.path.join(engineDir, platformName + suffix);
}
assert(false, 'Invalid platform $platform.');
......@@ -222,7 +222,7 @@ class LocalEngineArtifacts extends Artifacts {
case Artifact.classesDexJar:
return fs.path.join(engineOutPath, 'gen', 'flutter', 'shell', 'platform', 'android', 'android', _artifactToFileName(artifact));
case Artifact.libskyShellSo:
String abi = _getAbiDirectory(platform);
final String abi = _getAbiDirectory(platform);
return fs.path.join(engineOutPath, 'gen', 'flutter', 'shell', 'platform', 'android', 'android', fs.path.join('android', 'libs', abi, _artifactToFileName(artifact)));
case Artifact.genSnapshot:
return _genSnapshotPath(platform);
......@@ -257,7 +257,7 @@ class LocalEngineArtifacts extends Artifacts {
}
String _skySnapshotPath() {
String clangPath = fs.path.join(engineOutPath, 'clang_x64', _artifactToFileName(Artifact.skySnapshot));
final String clangPath = fs.path.join(engineOutPath, 'clang_x64', _artifactToFileName(Artifact.skySnapshot));
if (fs.isFileSync(clangPath))
return clangPath;
return fs.path.join(engineOutPath, _artifactToFileName(Artifact.skySnapshot));
......
......@@ -41,7 +41,7 @@ class AssetBundle {
if ((projectRoot == null) || (projectAssets == null))
return;
List<String> assets = projectAssets.split(',');
final List<String> assets = projectAssets.split(',');
for (String asset in assets) {
if (asset == '')
continue;
......@@ -57,7 +57,7 @@ class AssetBundle {
if (_lastBuildTimestamp == null)
return true;
FileStat stat = fs.file(manifestPath).statSync();
final FileStat stat = fs.file(manifestPath).statSync();
if (stat.type == FileSystemEntityType.NOT_FOUND)
return true;
......@@ -88,19 +88,19 @@ class AssetBundle {
return 0;
}
if (manifest != null) {
int result = await _validateFlutterManifest(manifest);
final int result = await _validateFlutterManifest(manifest);
if (result != 0)
return result;
}
Map<String, dynamic> manifestDescriptor = manifest;
manifestDescriptor = manifestDescriptor['flutter'] ?? <String, dynamic>{};
String assetBasePath = fs.path.dirname(fs.path.absolute(manifestPath));
final String assetBasePath = fs.path.dirname(fs.path.absolute(manifestPath));
_lastBuildTimestamp = new DateTime.now();
final PackageMap packageMap = new PackageMap(packagesPath);
Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
final Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
packageMap,
manifestDescriptor,
assetBasePath,
......@@ -123,7 +123,7 @@ class AssetBundle {
}
}
List<_Asset> materialAssets = <_Asset>[];
final List<_Asset> materialAssets = <_Asset>[];
if (usesMaterialDesign && includeDefaultFonts) {
materialAssets.addAll(_getMaterialAssets(_kFontSetMaterial));
if (includeRobotoFonts)
......@@ -136,7 +136,7 @@ class AssetBundle {
entries[_kAssetManifestJson] = _createAssetManifest(assetVariants);
DevFSContent fontManifest =
final DevFSContent fontManifest =
_createFontManifest(manifestDescriptor, usesMaterialDesign, includeDefaultFonts, includeRobotoFonts);
if (fontManifest != null)
entries[_kFontManifestJson] = fontManifest;
......@@ -183,7 +183,7 @@ class _Asset {
String get symbolicPrefix {
if (_assetEntry == null || _assetEntry == relativePath)
return null;
int index = _assetEntry.indexOf(relativePath);
final int index = _assetEntry.indexOf(relativePath);
return index == -1 ? null : _assetEntry.substring(0, index);
}
......@@ -192,7 +192,7 @@ class _Asset {
}
Map<String, dynamic> _readMaterialFontsManifest() {
String fontsPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
final String fontsPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
'packages', 'flutter_tools', 'schema', 'material_fonts.yaml');
return loadYaml(fs.file(fontsPath).readAsStringSync());
......@@ -205,11 +205,11 @@ List<Map<String, dynamic>> _getMaterialFonts(String fontSet) {
}
List<_Asset> _getMaterialAssets(String fontSet) {
List<_Asset> result = <_Asset>[];
final List<_Asset> result = <_Asset>[];
for (Map<String, dynamic> family in _getMaterialFonts(fontSet)) {
for (Map<String, dynamic> font in family['fonts']) {
String assetKey = font['asset'];
final String assetKey = font['asset'];
result.add(new _Asset(
base: fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'artifacts', 'material_fonts'),
source: fs.path.basename(assetKey),
......@@ -281,7 +281,7 @@ Future<DevFSContent> _obtainLicenses(
final List<String> combinedLicensesList = packageLicenses.keys.map(
(String license) {
List<String> packageNames = packageLicenses[license].toList()
final List<String> packageNames = packageLicenses[license].toList()
..sort();
return packageNames.join('\n') + '\n\n' + license;
}
......@@ -294,9 +294,9 @@ Future<DevFSContent> _obtainLicenses(
}
DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) {
Map<String, List<String>> json = <String, List<String>>{};
final Map<String, List<String>> json = <String, List<String>>{};
for (_Asset main in assetVariants.keys) {
List<String> variants = <String>[];
final List<String> variants = <String>[];
for (_Asset variant in assetVariants[main])
variants.add(variant.relativePath);
json[main.relativePath] = variants;
......@@ -308,7 +308,7 @@ DevFSContent _createFontManifest(Map<String, dynamic> manifestDescriptor,
bool usesMaterialDesign,
bool includeDefaultFonts,
bool includeRobotoFonts) {
List<Map<String, dynamic>> fonts = <Map<String, dynamic>>[];
final List<Map<String, dynamic>> fonts = <Map<String, dynamic>>[];
if (usesMaterialDesign && includeDefaultFonts) {
fonts.addAll(_getMaterialFonts(AssetBundle._kFontSetMaterial));
if (includeRobotoFonts)
......@@ -331,7 +331,7 @@ Map<_Asset, List<_Asset>> _parseAssets(
String assetBase, {
List<String> excludeDirs: const <String>[]
}) {
Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
if (manifestDescriptor == null)
return result;
......@@ -342,22 +342,22 @@ Map<_Asset, List<_Asset>> _parseAssets(
if (manifestDescriptor.containsKey('assets')) {
for (String asset in manifestDescriptor['assets']) {
_Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
final _Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
if (!baseAsset.assetFileExists) {
printError('Error: unable to locate asset entry in pubspec.yaml: "$asset".');
return null;
}
List<_Asset> variants = <_Asset>[];
final List<_Asset> variants = <_Asset>[];
result[baseAsset] = variants;
// Find asset variants
String assetPath = baseAsset.assetFile.path;
String assetFilename = fs.path.basename(assetPath);
Directory assetDir = fs.directory(fs.path.dirname(assetPath));
final String assetPath = baseAsset.assetFile.path;
final String assetFilename = fs.path.basename(assetPath);
final Directory assetDir = fs.directory(fs.path.dirname(assetPath));
List<FileSystemEntity> files = assetDir.listSync(recursive: true);
final List<FileSystemEntity> files = assetDir.listSync(recursive: true);
for (FileSystemEntity entity in files) {
if (!fs.isFileSync(entity.path))
......@@ -368,7 +368,7 @@ Map<_Asset, List<_Asset>> _parseAssets(
continue;
if (fs.path.basename(entity.path) == assetFilename && entity.path != assetPath) {
String key = fs.path.relative(entity.path, from: baseAsset.base);
final String key = fs.path.relative(entity.path, from: baseAsset.base);
String assetEntry;
if (baseAsset.symbolicPrefix != null)
assetEntry = fs.path.join(baseAsset.symbolicPrefix, key);
......@@ -381,14 +381,14 @@ Map<_Asset, List<_Asset>> _parseAssets(
// Add assets referenced in the fonts section of the manifest.
if (manifestDescriptor.containsKey('fonts')) {
for (Map<String, dynamic> family in manifestDescriptor['fonts']) {
List<Map<String, dynamic>> fonts = family['fonts'];
final List<Map<String, dynamic>> fonts = family['fonts'];
if (fonts == null) continue;
for (Map<String, dynamic> font in fonts) {
String asset = font['asset'];
final String asset = font['asset'];
if (asset == null) continue;
_Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
final _Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
if (!baseAsset.assetFileExists) {
printError('Error: unable to locate asset entry in pubspec.yaml: "$asset".');
return null;
......@@ -412,15 +412,15 @@ _Asset _resolveAsset(
String packageKey = asset.substring(9);
String relativeAsset = asset;
int index = packageKey.indexOf('/');
final int index = packageKey.indexOf('/');
if (index != -1) {
relativeAsset = packageKey.substring(index + 1);
packageKey = packageKey.substring(0, index);
}
Uri uri = packageMap.map[packageKey];
final Uri uri = packageMap.map[packageKey];
if (uri != null && uri.scheme == 'file') {
File file = fs.file(uri);
final File file = fs.file(uri);
return new _Asset(base: file.path, assetEntry: asset, relativePath: relativeAsset);
}
}
......@@ -431,16 +431,16 @@ _Asset _resolveAsset(
dynamic _loadFlutterManifest(String manifestPath) {
if (manifestPath == null || !fs.isFileSync(manifestPath))
return null;
String manifestDescriptor = fs.file(manifestPath).readAsStringSync();
final String manifestDescriptor = fs.file(manifestPath).readAsStringSync();
return loadYaml(manifestDescriptor);
}
Future<int> _validateFlutterManifest(Object manifest) async {
String schemaPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
final String schemaPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
'packages', 'flutter_tools', 'schema', 'pubspec_yaml.json');
Schema schema = await Schema.createSchemaFromUrl(fs.path.toUri(schemaPath).toString());
final Schema schema = await Schema.createSchemaFromUrl(fs.path.toUri(schemaPath).toString());
Validator validator = new Validator(schema);
final Validator validator = new Validator(schema);
if (validator.validate(manifest)) {
return 0;
} else {
......
......@@ -44,7 +44,7 @@ class Config {
}
String _userHomeDir() {
String envKey = platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME';
String value = platform.environment[envKey];
final String envKey = platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME';
final String value = platform.environment[envKey];
return value == null ? '.' : value;
}
......@@ -20,7 +20,7 @@ class AppContext {
if (_instances.containsKey(type))
return true;
AppContext parent = _calcParent(_zone);
final AppContext parent = _calcParent(_zone);
return parent != null ? parent.isSet(type) : false;
}
......@@ -28,7 +28,7 @@ class AppContext {
if (_instances.containsKey(type))
return _instances[type];
AppContext parent = _calcParent(_zone);
final AppContext parent = _calcParent(_zone);
return parent?.getVariable(type);
}
......@@ -49,11 +49,11 @@ class AppContext {
}
AppContext _calcParent(Zone zone) {
Zone parentZone = zone.parent;
final Zone parentZone = zone.parent;
if (parentZone == null)
return null;
AppContext parentContext = parentZone['context'];
final AppContext parentContext = parentZone['context'];
return parentContext == this
? _calcParent(parentZone)
: parentContext;
......@@ -70,7 +70,7 @@ class AppContext {
}
Future<dynamic> _run(dynamic method()) async {
Zone previousZone = _zone;
final Zone previousZone = _zone;
try {
_zone = Zone.current;
return await method();
......
......@@ -34,9 +34,9 @@ FileSystem get fs => context == null ? _kLocalFs : context[FileSystem];
/// It is permissible for [location] to represent an existing non-empty
/// directory as long as there is no collision with the `"file"` subdirectory.
void enableRecordingFileSystem(String location) {
FileSystem originalFileSystem = fs;
Directory dir = getRecordingSink(location, _kRecordingType);
RecordingFileSystem fileSystem = new RecordingFileSystem(
final FileSystem originalFileSystem = fs;
final Directory dir = getRecordingSink(location, _kRecordingType);
final RecordingFileSystem fileSystem = new RecordingFileSystem(
delegate: _kLocalFs, destination: dir);
addShutdownHook(() async {
await fileSystem.recording.flush();
......@@ -54,13 +54,13 @@ void enableRecordingFileSystem(String location) {
/// been recorded (i.e. the result of having been previously passed to
/// [enableRecordingFileSystem]), or a [ToolExit] will be thrown.
void enableReplayFileSystem(String location) {
Directory dir = getReplaySource(location, _kRecordingType);
final Directory dir = getReplaySource(location, _kRecordingType);
context.setVariable(FileSystem, new ReplayFileSystem(recording: dir));
}
/// Create the ancestor directories of a file path if they do not already exist.
void ensureDirectoryExists(String filePath) {
String dirPath = fs.path.dirname(filePath);
final String dirPath = fs.path.dirname(filePath);
if (fs.isDirectorySync(dirPath))
return;
try {
......@@ -81,9 +81,9 @@ void copyDirectorySync(Directory srcDir, Directory destDir) {
destDir.createSync(recursive: true);
srcDir.listSync().forEach((FileSystemEntity entity) {
String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename);
final String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename);
if (entity is File) {
File newFile = destDir.fileSystem.file(newPath);
final File newFile = destDir.fileSystem.file(newPath);
newFile.writeAsBytesSync(entity.readAsBytesSync());
} else if (entity is Directory) {
copyDirectorySync(
......@@ -105,7 +105,7 @@ void copyDirectorySync(Directory srcDir, Directory destDir) {
/// directory exists as an entity other than a directory, a [ToolExit] will
/// also be thrown.
Directory getRecordingSink(String dirname, String basename) {
String location = _kLocalFs.path.join(dirname, basename);
final String location = _kLocalFs.path.join(dirname, basename);
switch (_kLocalFs.typeSync(location, followLinks: false)) {
case FileSystemEntityType.FILE:
case FileSystemEntityType.LINK:
......@@ -129,7 +129,7 @@ Directory getRecordingSink(String dirname, String basename) {
///
/// If the target directory does not exist, a [ToolExit] will be thrown.
Directory getReplaySource(String dirname, String basename) {
Directory dir = _kLocalFs.directory(_kLocalFs.path.join(dirname, basename));
final Directory dir = _kLocalFs.directory(_kLocalFs.path.join(dirname, basename));
if (!dir.existsSync())
throwToolExit('Invalid replay-from location: $dirname ("$basename" does not exist)');
return dir;
......
......@@ -206,7 +206,7 @@ class VerboseLogger extends Logger {
if (message.trim().isEmpty)
return;
int millis = stopwatch.elapsedMilliseconds;
final int millis = stopwatch.elapsedMilliseconds;
stopwatch.reset();
String prefix;
......@@ -220,8 +220,8 @@ class VerboseLogger extends Logger {
}
prefix = '[$prefix] ';
String indent = ''.padLeft(prefix.length);
String indentMessage = message.replaceAll('\n', '\n$indent');
final String indent = ''.padLeft(prefix.length);
final String indentMessage = message.replaceAll('\n', '\n$indent');
if (type == _LogType.error) {
stderr.writeln(prefix + terminal.bolden(indentMessage));
......@@ -243,9 +243,9 @@ enum _LogType {
class AnsiTerminal {
AnsiTerminal() {
String term = platform.environment['TERM'];
final String term = platform.environment['TERM'];
// FLUTTER_ANSI_TERMINAL is a work-around for https://github.com/dart-lang/sdk/issues/28614
bool flutterAnsiTerm = platform.environment.containsKey('FLUTTER_ANSI_TERMINAL');
final bool flutterAnsiTerm = platform.environment.containsKey('FLUTTER_ANSI_TERMINAL');
supportsColor = (term != null && term != 'dumb') || flutterAnsiTerm;
}
......@@ -326,7 +326,7 @@ class _AnsiStatus extends Status {
live = false;
if (expectSlowOperation) {
double seconds = stopwatch.elapsedMilliseconds / Duration.MILLISECONDS_PER_SECOND;
final double seconds = stopwatch.elapsedMilliseconds / Duration.MILLISECONDS_PER_SECOND;
print('\b\b\b\b\b${secondsFormat.format(seconds).padLeft(4)}s');
} else {
print('\b\b\b\b\b${millisecondsFormat.format(stopwatch.elapsedMilliseconds).padLeft(3)}ms');
......
......@@ -14,9 +14,9 @@ const int kNetworkProblemExitCode = 50;
Future<List<int>> fetchUrl(Uri url) async {
printTrace('Downloading $url.');
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.getUrl(url);
HttpClientResponse response = await request.close();
final HttpClient httpClient = new HttpClient();
final HttpClientRequest request = await httpClient.getUrl(url);
final HttpClientResponse response = await request.close();
printTrace('Received response statusCode=${response.statusCode}');
if (response.statusCode != 200) {
......@@ -28,7 +28,7 @@ Future<List<int>> fetchUrl(Uri url) async {
}
try {
BytesBuilder responseBody = new BytesBuilder(copy: false);
final BytesBuilder responseBody = new BytesBuilder(copy: false);
await for (List<int> chunk in response)
responseBody.add(chunk);
......
......@@ -54,10 +54,10 @@ class _PosixUtils extends OperatingSystemUtils {
/// to locate the binary.
@override
File which(String execName) {
ProcessResult result = processManager.runSync(<String>['which', execName]);
final ProcessResult result = processManager.runSync(<String>['which', execName]);
if (result.exitCode != 0)
return null;
String path = result.stdout.trim().split('\n').first.trim();
final String path = result.stdout.trim().split('\n').first.trim();
return fs.file(path);
}
......@@ -90,7 +90,7 @@ class _WindowsUtils extends OperatingSystemUtils {
@override
File which(String execName) {
ProcessResult result = processManager.runSync(<String>['where', execName]);
final ProcessResult result = processManager.runSync(<String>['where', execName]);
if (result.exitCode != 0)
return null;
return fs.file(result.stdout.trim().split('\n').first.trim());
......@@ -98,14 +98,14 @@ class _WindowsUtils extends OperatingSystemUtils {
@override
void zip(Directory data, File zipFile) {
Archive archive = new Archive();
final Archive archive = new Archive();
for (FileSystemEntity entity in data.listSync(recursive: true)) {
if (entity is! File) {
continue;
}
File file = entity;
String path = file.fileSystem.path.relative(file.path, from: data.path);
List<int> bytes = file.readAsBytesSync();
final File file = entity;
final String path = file.fileSystem.path.relative(file.path, from: data.path);
final List<int> bytes = file.readAsBytesSync();
archive.addFile(new ArchiveFile(path, bytes.length, bytes));
}
zipFile.writeAsBytesSync(new ZipEncoder().encode(archive), flush: true);
......@@ -113,14 +113,14 @@ class _WindowsUtils extends OperatingSystemUtils {
@override
void unzip(File file, Directory targetDirectory) {
Archive archive = new ZipDecoder().decodeBytes(file.readAsBytesSync());
final Archive archive = new ZipDecoder().decodeBytes(file.readAsBytesSync());
for (ArchiveFile archiveFile in archive.files) {
// The archive package doesn't correctly set isFile.
if (!archiveFile.isFile || archiveFile.name.endsWith('/'))
continue;
File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name));
final File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name));
if (!destFile.parent.existsSync())
destFile.parent.createSync(recursive: true);
destFile.writeAsBytesSync(archiveFile.content);
......@@ -134,8 +134,8 @@ class _WindowsUtils extends OperatingSystemUtils {
}
Future<int> findAvailablePort() async {
ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0);
int port = socket.port;
final ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0);
final int port = socket.port;
await socket.close();
return port;
}
......@@ -148,7 +148,7 @@ Future<int> findPreferredPort(int defaultPort, { int searchStep: 2 }) async {
int iterationCount = 0;
while (iterationCount < _kMaxSearchIterations) {
int port = defaultPort + iterationCount * searchStep;
final int port = defaultPort + iterationCount * searchStep;
if (await _isPortAvailable(port))
return port;
iterationCount++;
......@@ -160,7 +160,7 @@ Future<int> findPreferredPort(int defaultPort, { int searchStep: 2 }) async {
Future<bool> _isPortAvailable(int port) async {
try {
// TODO(ianh): This is super racy.
ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, port);
final ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, port);
await socket.close();
return true;
} catch (error) {
......@@ -178,7 +178,7 @@ String findProjectRoot([String directory]) {
while (true) {
if (fs.isFileSync(fs.path.join(directory, kProjectRootSentinel)))
return directory;
String parent = fs.path.dirname(directory);
final String parent = fs.path.dirname(directory);
if (directory == parent) return null;
directory = parent;
}
......
......@@ -24,19 +24,19 @@ Platform get platform => context == null ? _kLocalPlatform : context[Platform];
/// non-empty directory as long as there is no collision with the `"platform"`
/// subdirectory.
Future<Null> enableRecordingPlatform(String location) async {
Directory dir = getRecordingSink(location, _kRecordingType);
File file = _getPlatformManifest(dir);
final Directory dir = getRecordingSink(location, _kRecordingType);
final File file = _getPlatformManifest(dir);
await file.writeAsString(platform.toJson(), flush: true);
}
Future<Null> enableReplayPlatform(String location) async {
Directory dir = getReplaySource(location, _kRecordingType);
File file = _getPlatformManifest(dir);
String json = await file.readAsString();
final Directory dir = getReplaySource(location, _kRecordingType);
final File file = _getPlatformManifest(dir);
final String json = await file.readAsString();
context.setVariable(Platform, new FakePlatform.fromJson(json));
}
File _getPlatformManifest(Directory dir) {
String path = dir.fileSystem.path.join(dir.path, 'MANIFEST.txt');
final String path = dir.fileSystem.path.join(dir.path, 'MANIFEST.txt');
return dir.fileSystem.file(path);
}
......@@ -69,8 +69,8 @@ Future<Null> runShutdownHooks() async {
_shutdownHooksRunning = true;
try {
for (ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) {
List<ShutdownHook> hooks = _shutdownHooks.remove(stage);
List<Future<dynamic>> futures = <Future<dynamic>>[];
final List<ShutdownHook> hooks = _shutdownHooks.remove(stage);
final List<Future<dynamic>> futures = <Future<dynamic>>[];
for (ShutdownHook shutdownHook in hooks)
futures.add(shutdownHook());
await Future.wait<dynamic>(futures);
......@@ -100,7 +100,7 @@ Future<Process> runCommand(List<String> cmd, {
Map<String, String> environment
}) async {
_traceCommand(cmd, workingDirectory: workingDirectory);
Process process = await processManager.start(
final Process process = await processManager.start(
cmd,
workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter, environment)
......@@ -119,13 +119,13 @@ Future<int> runCommandAndStreamOutput(List<String> cmd, {
StringConverter mapFunction,
Map<String, String> environment
}) async {
Process process = await runCommand(
final Process process = await runCommand(
cmd,
workingDirectory: workingDirectory,
allowReentrantFlutter: allowReentrantFlutter,
environment: environment
);
StreamSubscription<String> subscription = process.stdout
final StreamSubscription<String> subscription = process.stdout
.transform(UTF8.decoder)
.transform(const LineSplitter())
.where((String line) => filter == null ? true : filter.hasMatch(line))
......@@ -133,7 +133,7 @@ Future<int> runCommandAndStreamOutput(List<String> cmd, {
if (mapFunction != null)
line = mapFunction(line);
if (line != null) {
String message = '$prefix$line';
final String message = '$prefix$line';
if (trace)
printTrace(message);
else
......@@ -160,7 +160,7 @@ Future<int> runCommandAndStreamOutput(List<String> cmd, {
}
Future<Null> runAndKill(List<String> cmd, Duration timeout) {
Future<Process> proc = runDetached(cmd);
final Future<Process> proc = runDetached(cmd);
return new Future<Null>.delayed(timeout, () async {
printTrace('Intentionally killing ${cmd[0]}');
processManager.killPid((await proc).pid);
......@@ -169,7 +169,7 @@ Future<Null> runAndKill(List<String> cmd, Duration timeout) {
Future<Process> runDetached(List<String> cmd) {
_traceCommand(cmd);
Future<Process> proc = processManager.start(
final Future<Process> proc = processManager.start(
cmd,
mode: ProcessStartMode.DETACHED,
);
......@@ -181,12 +181,12 @@ Future<RunResult> runAsync(List<String> cmd, {
bool allowReentrantFlutter: false
}) async {
_traceCommand(cmd, workingDirectory: workingDirectory);
ProcessResult results = await processManager.run(
final ProcessResult results = await processManager.run(
cmd,
workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter),
);
RunResult runResults = new RunResult(results);
final RunResult runResults = new RunResult(results);
printTrace(runResults.toString());
return runResults;
}
......@@ -241,7 +241,7 @@ String runSync(List<String> cmd, {
}
void _traceCommand(List<String> args, { String workingDirectory }) {
String argsText = args.join(' ');
final String argsText = args.join(' ');
if (workingDirectory == null)
printTrace(argsText);
else
......@@ -257,7 +257,7 @@ String _runWithLoggingSync(List<String> cmd, {
bool hideStdout: false,
}) {
_traceCommand(cmd, workingDirectory: workingDirectory);
ProcessResult results = processManager.runSync(
final ProcessResult results = processManager.runSync(
cmd,
workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter),
......@@ -312,7 +312,7 @@ class RunResult {
@override
String toString() {
StringBuffer out = new StringBuffer();
final StringBuffer out = new StringBuffer();
if (processResult.stdout.isNotEmpty)
out.writeln(processResult.stdout);
if (processResult.stderr.isNotEmpty)
......
......@@ -28,10 +28,10 @@ ProcessManager get processManager => context[ProcessManager];
/// directory as long as there is no collision with the `"process"`
/// subdirectory.
void enableRecordingProcessManager(String location) {
ProcessManager originalProcessManager = processManager;
Directory dir = getRecordingSink(location, _kRecordingType);
ProcessManager delegate = const LocalProcessManager();
RecordingProcessManager manager = new RecordingProcessManager(delegate, dir);
final ProcessManager originalProcessManager = processManager;
final Directory dir = getRecordingSink(location, _kRecordingType);
final ProcessManager delegate = const LocalProcessManager();
final RecordingProcessManager manager = new RecordingProcessManager(delegate, dir);
addShutdownHook(() async {
await manager.flush(finishRunningProcesses: true);
context.setVariable(ProcessManager, originalProcessManager);
......@@ -48,7 +48,7 @@ void enableRecordingProcessManager(String location) {
/// recorded (i.e. the result of having been previously passed to
/// [enableRecordingProcessManager]), or a [ToolExit] will be thrown.
Future<Null> enableReplayProcessManager(String location) async {
Directory dir = getReplaySource(location, _kRecordingType);
final Directory dir = getReplaySource(location, _kRecordingType);
ProcessManager manager;
try {
......
......@@ -22,7 +22,7 @@ bool get isRunningOnBot {
}
String hex(List<int> bytes) {
StringBuffer result = new StringBuffer();
final StringBuffer result = new StringBuffer();
for (int part in bytes)
result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
return result.toString();
......@@ -55,18 +55,18 @@ String pluralize(String word, int count) => count == 1 ? word : word + 's';
/// Return the name of an enum item.
String getEnumName(dynamic enumItem) {
String name = '$enumItem';
int index = name.indexOf('.');
final String name = '$enumItem';
final int index = name.indexOf('.');
return index == -1 ? name : name.substring(index + 1);
}
File getUniqueFile(Directory dir, String baseName, String ext) {
FileSystem fs = dir.fileSystem;
final FileSystem fs = dir.fileSystem;
int i = 1;
while (true) {
String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext';
File file = fs.file(fs.path.join(dir.path, name));
final String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext';
final File file = fs.file(fs.path.join(dir.path, name));
if (!file.existsSync())
return file;
i++;
......@@ -87,7 +87,7 @@ String getElapsedAsMilliseconds(Duration duration) => '${duration.inMilliseconds
/// Return a relative path if [fullPath] is contained by the cwd, else return an
/// absolute path.
String getDisplayPath(String fullPath) {
String cwd = fs.currentDirectory.path + fs.path.separator;
final String cwd = fs.currentDirectory.path + fs.path.separator;
return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath;
}
......@@ -114,10 +114,10 @@ class ItemListNotifier<T> {
List<T> get items => _items.toList();
void updateWithNewList(List<T> updatedList) {
Set<T> updatedSet = new Set<T>.from(updatedList);
final Set<T> updatedSet = new Set<T>.from(updatedList);
Set<T> addedItems = updatedSet.difference(_items);
Set<T> removedItems = _items.difference(updatedSet);
final Set<T> addedItems = updatedSet.difference(_items);
final Set<T> removedItems = _items.difference(updatedSet);
_items = updatedSet;
......@@ -140,7 +140,7 @@ class SettingsFile {
line = line.trim();
if (line.startsWith('#') || line.isEmpty)
continue;
int index = line.indexOf('=');
final int index = line.indexOf('=');
if (index != -1)
values[line.substring(0, index)] = line.substring(index + 1);
}
......@@ -174,7 +174,7 @@ class Uuid {
/// random numbers as the source of the generated uuid.
String generateV4() {
// Generate xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx / 8-4-4-4-12.
int special = 8 + _random.nextInt(4);
final int special = 8 + _random.nextInt(4);
return
'${_bitsDigits(16, 4)}${_bitsDigits(16, 4)}-'
......
......@@ -43,15 +43,15 @@ class Version implements Comparable<Version> {
/// Creates a new [Version] by parsing [text].
factory Version.parse(String text) {
Match match = versionPattern.firstMatch(text);
final Match match = versionPattern.firstMatch(text);
if (match == null) {
return null;
}
try {
int major = int.parse(match[1] ?? '0');
int minor = int.parse(match[3] ?? '0');
int patch = int.parse(match[5] ?? '0');
final int major = int.parse(match[1] ?? '0');
final int minor = int.parse(match[3] ?? '0');
final int patch = int.parse(match[5] ?? '0');
return new Version._(major, minor, patch, text);
} on FormatException {
return null;
......
......@@ -130,7 +130,7 @@ String getBuildDirectory() {
if (context == null || config == null)
return 'build';
String buildDir = config.getValue('build-dir') ?? 'build';
final String buildDir = config.getValue('build-dir') ?? 'build';
if (fs.path.isAbsolute(buildDir)) {
throw new Exception(
'build-dir config setting in ${config.configPath} must be relative');
......
......@@ -89,7 +89,7 @@ class Cache {
static String get engineRevision {
if (_engineRevision == null) {
File revisionFile = fs.file(fs.path.join(flutterRoot, 'bin', 'internal', 'engine.version'));
final File revisionFile = fs.file(fs.path.join(flutterRoot, 'bin', 'internal', 'engine.version'));
if (revisionFile.existsSync())
_engineRevision = revisionFile.readAsStringSync().trim();
}
......@@ -108,7 +108,7 @@ class Cache {
/// Return a directory in the cache dir. For `pkg`, this will return `bin/cache/pkg`.
Directory getCacheDir(String name) {
Directory dir = fs.directory(fs.path.join(getRoot().path, name));
final Directory dir = fs.directory(fs.path.join(getRoot().path, name));
if (!dir.existsSync())
dir.createSync(recursive: true);
return dir;
......@@ -124,12 +124,12 @@ class Cache {
}
String getVersionFor(String artifactName) {
File versionFile = fs.file(fs.path.join(_rootOverride?.path ?? flutterRoot, 'bin', 'internal', '$artifactName.version'));
final File versionFile = fs.file(fs.path.join(_rootOverride?.path ?? flutterRoot, 'bin', 'internal', '$artifactName.version'));
return versionFile.existsSync() ? versionFile.readAsStringSync().trim() : null;
}
String getStampFor(String artifactName) {
File stampFile = getStampFileFor(artifactName);
final File stampFile = getStampFileFor(artifactName);
return stampFile.existsSync() ? stampFile.readAsStringSync().trim() : null;
}
......@@ -142,8 +142,8 @@ class Cache {
}
bool isUpToDate() {
MaterialFonts materialFonts = new MaterialFonts(cache);
FlutterEngine engine = new FlutterEngine(cache);
final MaterialFonts materialFonts = new MaterialFonts(cache);
final FlutterEngine engine = new FlutterEngine(cache);
return materialFonts.isUpToDate() && engine.isUpToDate();
}
......@@ -151,14 +151,14 @@ class Cache {
Future<String> getThirdPartyFile(String urlStr, String serviceName, {
bool unzip: false
}) async {
Uri url = Uri.parse(urlStr);
Directory thirdPartyDir = getArtifactDirectory('third_party');
final Uri url = Uri.parse(urlStr);
final Directory thirdPartyDir = getArtifactDirectory('third_party');
Directory serviceDir = fs.directory(fs.path.join(thirdPartyDir.path, serviceName));
final Directory serviceDir = fs.directory(fs.path.join(thirdPartyDir.path, serviceName));
if (!serviceDir.existsSync())
serviceDir.createSync(recursive: true);
File cachedFile = fs.file(fs.path.join(serviceDir.path, url.pathSegments.last));
final File cachedFile = fs.file(fs.path.join(serviceDir.path, url.pathSegments.last));
if (!cachedFile.existsSync()) {
try {
await _downloadFileToCache(url, cachedFile, unzip);
......@@ -174,11 +174,11 @@ class Cache {
Future<Null> updateAll() async {
if (!_lockEnabled)
return null;
MaterialFonts materialFonts = new MaterialFonts(cache);
final MaterialFonts materialFonts = new MaterialFonts(cache);
if (!materialFonts.isUpToDate())
await materialFonts.download();
FlutterEngine engine = new FlutterEngine(cache);
final FlutterEngine engine = new FlutterEngine(cache);
if (!engine.isUpToDate())
await engine.download();
}
......@@ -190,17 +190,17 @@ class Cache {
if (!location.parent.existsSync())
location.parent.createSync(recursive: true);
List<int> fileBytes = await fetchUrl(url);
final List<int> fileBytes = await fetchUrl(url);
if (unzip) {
if (location is Directory && !location.existsSync())
location.createSync(recursive: true);
File tempFile = fs.file(fs.path.join(fs.systemTempDirectory.path, '${url.toString().hashCode}.zip'));
final File tempFile = fs.file(fs.path.join(fs.systemTempDirectory.path, '${url.toString().hashCode}.zip'));
tempFile.writeAsBytesSync(fileBytes, flush: true);
os.unzip(tempFile, location);
tempFile.deleteSync();
} else {
File file = location;
final File file = location;
file.writeAsBytesSync(fileBytes, flush: true);
}
}
......@@ -220,9 +220,9 @@ class MaterialFonts {
}
Future<Null> download() {
Status status = logger.startProgress('Downloading Material fonts...', expectSlowOperation: true);
final Status status = logger.startProgress('Downloading Material fonts...', expectSlowOperation: true);
Directory fontsDir = cache.getArtifactDirectory(kName);
final Directory fontsDir = cache.getArtifactDirectory(kName);
if (fontsDir.existsSync())
fontsDir.deleteSync(recursive: true);
......@@ -250,7 +250,7 @@ class FlutterEngine {
// Return a list of (cache directory path, download URL path) tuples.
List<List<String>> _getBinaryDirs() {
List<List<String>> binaryDirs = <List<String>>[];
final List<List<String>> binaryDirs = <List<String>>[];
if (cache.includeAllPlatforms)
binaryDirs
......@@ -309,16 +309,16 @@ class FlutterEngine {
];
bool isUpToDate() {
Directory pkgDir = cache.getCacheDir('pkg');
final Directory pkgDir = cache.getCacheDir('pkg');
for (String pkgName in _getPackageDirs()) {
String pkgPath = fs.path.join(pkgDir.path, pkgName);
final String pkgPath = fs.path.join(pkgDir.path, pkgName);
if (!fs.directory(pkgPath).existsSync())
return false;
}
Directory engineDir = cache.getArtifactDirectory(kName);
final Directory engineDir = cache.getArtifactDirectory(kName);
for (List<String> toolsDir in _getBinaryDirs()) {
Directory dir = fs.directory(fs.path.join(engineDir.path, toolsDir[0]));
final Directory dir = fs.directory(fs.path.join(engineDir.path, toolsDir[0]));
if (!dir.existsSync())
return false;
}
......@@ -327,33 +327,33 @@ class FlutterEngine {
}
Future<Null> download() async {
String engineVersion = cache.getVersionFor(kName);
String url = 'https://storage.googleapis.com/flutter_infra/flutter/$engineVersion/';
final String engineVersion = cache.getVersionFor(kName);
final String url = 'https://storage.googleapis.com/flutter_infra/flutter/$engineVersion/';
Directory pkgDir = cache.getCacheDir('pkg');
final Directory pkgDir = cache.getCacheDir('pkg');
for (String pkgName in _getPackageDirs()) {
String pkgPath = fs.path.join(pkgDir.path, pkgName);
Directory dir = fs.directory(pkgPath);
final String pkgPath = fs.path.join(pkgDir.path, pkgName);
final Directory dir = fs.directory(pkgPath);
if (dir.existsSync())
dir.deleteSync(recursive: true);
await _downloadItem('Downloading package $pkgName...', url + pkgName + '.zip', pkgDir);
}
Directory engineDir = cache.getArtifactDirectory(kName);
final Directory engineDir = cache.getArtifactDirectory(kName);
if (engineDir.existsSync())
engineDir.deleteSync(recursive: true);
for (List<String> toolsDir in _getBinaryDirs()) {
String cacheDir = toolsDir[0];
String urlPath = toolsDir[1];
Directory dir = fs.directory(fs.path.join(engineDir.path, cacheDir));
final String cacheDir = toolsDir[0];
final String urlPath = toolsDir[1];
final Directory dir = fs.directory(fs.path.join(engineDir.path, cacheDir));
await _downloadItem('Downloading $cacheDir tools...', url + urlPath, dir);
_makeFilesExecutable(dir);
File frameworkZip = fs.file(fs.path.join(dir.path, 'Flutter.framework.zip'));
final File frameworkZip = fs.file(fs.path.join(dir.path, 'Flutter.framework.zip'));
if (frameworkZip.existsSync()) {
Directory framework = fs.directory(fs.path.join(dir.path, 'Flutter.framework'));
final Directory framework = fs.directory(fs.path.join(dir.path, 'Flutter.framework'));
framework.createSync();
os.unzip(frameworkZip, framework);
}
......@@ -365,7 +365,7 @@ class FlutterEngine {
void _makeFilesExecutable(Directory dir) {
for (FileSystemEntity entity in dir.listSync()) {
if (entity is File) {
String name = fs.path.basename(entity.path);
final String name = fs.path.basename(entity.path);
if (name == 'sky_snapshot' || name == 'sky_shell')
os.makeExecutable(entity);
}
......@@ -373,7 +373,7 @@ class FlutterEngine {
}
Future<Null> _downloadItem(String message, String url, Directory dest) {
Status status = logger.startProgress(message, expectSlowOperation: true);
final Status status = logger.startProgress(message, expectSlowOperation: true);
return Cache._downloadFileToCache(Uri.parse(url), dest, true).then<Null>((Null value) {
status.stop();
}).whenComplete(() {
......
......@@ -39,7 +39,7 @@ abstract class AnalyzeBase {
void writeBenchmark(Stopwatch stopwatch, int errorCount, int membersMissingDocumentation) {
final String benchmarkOut = 'analysis_benchmark.json';
Map<String, dynamic> data = <String, dynamic>{
final Map<String, dynamic> data = <String, dynamic>{
'time': (stopwatch.elapsedMilliseconds / 1000.0),
'issues': errorCount,
'missingDartDocs': membersMissingDocumentation
......@@ -56,8 +56,8 @@ abstract class AnalyzeBase {
bool inRepo(List<String> fileList) {
if (fileList == null || fileList.isEmpty)
fileList = <String>[fs.path.current];
String root = fs.path.normalize(fs.path.absolute(Cache.flutterRoot));
String prefix = root + fs.path.separator;
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))
......
......@@ -46,7 +46,7 @@ class AnalyzeContinuously extends AnalyzeBase {
analysisTarget = fs.currentDirectory.path;
}
AnalysisServer server = new AnalysisServer(dartSdkPath, directories);
final AnalysisServer server = new AnalysisServer(dartSdkPath, directories);
server.onAnalyzing.listen((bool isAnalyzing) => _handleAnalysisStatus(server, isAnalyzing));
server.onErrors.listen(_handleAnalysisErrors);
......@@ -55,7 +55,7 @@ class AnalyzeContinuously extends AnalyzeBase {
await server.start();
final int exitCode = await server.onExit;
String message = 'Analysis server exited with code $exitCode.';
final String message = 'Analysis server exited with code $exitCode.';
if (exitCode != 0)
throwToolExit(message, exitCode: exitCode);
printStatus(message);
......@@ -98,8 +98,8 @@ class AnalyzeContinuously extends AnalyzeBase {
// Print an analysis summary.
String errorsMessage;
int issueCount = errors.length;
int issueDiff = issueCount - lastErrorCount;
final int issueCount = errors.length;
final int issueDiff = issueCount - lastErrorCount;
lastErrorCount = issueCount;
if (firstAnalysis)
......@@ -113,8 +113,8 @@ class AnalyzeContinuously extends AnalyzeBase {
else
errorsMessage = 'no issues found';
String files = '${analyzedPaths.length} ${pluralize('file', analyzedPaths.length)}';
String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2);
final String files = '${analyzedPaths.length} ${pluralize('file', analyzedPaths.length)}';
final String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2);
printStatus('$errorsMessage • analyzed $files, $seconds seconds');
if (firstAnalysis && isBenchmarking) {
......@@ -156,8 +156,8 @@ class AnalysisServer {
int _id = 0;
Future<Null> start() async {
String snapshot = fs.path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot');
List<String> command = <String>[
final String snapshot = fs.path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot');
final List<String> command = <String>[
fs.path.join(dartSdkPath, 'bin', 'dart'),
snapshot,
'--sdk',
......@@ -168,10 +168,10 @@ class AnalysisServer {
_process = await processManager.start(command);
_process.exitCode.whenComplete(() => _process = null);
Stream<String> errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter());
final Stream<String> errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter());
errorStream.listen((String error) => printError(error));
Stream<String> inStream = _process.stdout.transform(UTF8.decoder).transform(const LineSplitter());
final Stream<String> inStream = _process.stdout.transform(UTF8.decoder).transform(const LineSplitter());
inStream.listen(_handleServerResponse);
// Available options (many of these are obsolete):
......@@ -199,7 +199,7 @@ class AnalysisServer {
Future<int> get onExit => _process.exitCode;
void _sendCommand(String method, Map<String, dynamic> params) {
String message = JSON.encode(<String, dynamic> {
final String message = JSON.encode(<String, dynamic> {
'id': (++_id).toString(),
'method': method,
'params': params
......@@ -211,12 +211,12 @@ class AnalysisServer {
void _handleServerResponse(String line) {
printTrace('<== $line');
dynamic response = JSON.decode(line);
final dynamic response = JSON.decode(line);
if (response is Map<dynamic, dynamic>) {
if (response['event'] != null) {
String event = response['event'];
dynamic params = response['params'];
final String event = response['event'];
final dynamic params = response['params'];
if (params is Map<dynamic, dynamic>) {
if (event == 'server.status')
......@@ -228,7 +228,7 @@ class AnalysisServer {
}
} else if (response['error'] != null) {
// Fields are 'code', 'message', and 'stackTrace'.
Map<String, dynamic> error = response['error'];
final Map<String, dynamic> error = response['error'];
printError('Error response from the server: ${error['code']} ${error['message']}');
if (error['stackTrace'] != null)
printError(error['stackTrace']);
......@@ -239,7 +239,7 @@ class AnalysisServer {
void _handleStatus(Map<String, dynamic> statusInfo) {
// {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}}
if (statusInfo['analysis'] != null) {
bool isAnalyzing = statusInfo['analysis']['isAnalyzing'];
final bool isAnalyzing = statusInfo['analysis']['isAnalyzing'];
_analyzingController.add(isAnalyzing);
}
}
......@@ -253,8 +253,8 @@ class AnalysisServer {
void _handleAnalysisIssues(Map<String, dynamic> issueInfo) {
// {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}}
String file = issueInfo['file'];
List<AnalysisError> errors = issueInfo['errors'].map((Map<String, dynamic> json) => new AnalysisError(json)).toList();
final String file = issueInfo['file'];
final List<AnalysisError> errors = issueInfo['errors'].map((Map<String, dynamic> json) => new AnalysisError(json)).toList();
_errorsController.add(new FileAnalysisErrors(file, errors));
}
......@@ -299,7 +299,7 @@ class AnalysisError implements Comparable<AnalysisError> {
if (offset != other.offset)
return offset - other.offset;
int diff = other.severityLevel - severityLevel;
final int diff = other.severityLevel - severityLevel;
if (diff != 0)
return diff;
......@@ -308,7 +308,7 @@ class AnalysisError implements Comparable<AnalysisError> {
@override
String toString() {
String relativePath = fs.path.relative(file);
final String relativePath = fs.path.relative(file);
return '${severity.toLowerCase().padLeft(7)}$message$relativePath:$startLine:$startColumn';
}
......
......@@ -28,13 +28,13 @@ class AnalyzeOnce extends AnalyzeBase {
@override
Future<Null> analyze() async {
Stopwatch stopwatch = new Stopwatch()..start();
Set<Directory> pubSpecDirectories = new HashSet<Directory>();
List<File> dartFiles = <File>[];
final Stopwatch stopwatch = new Stopwatch()..start();
final Set<Directory> pubSpecDirectories = new HashSet<Directory>();
final List<File> dartFiles = <File>[];
for (String file in argResults.rest.toList()) {
file = fs.path.normalize(fs.path.absolute(file));
String root = fs.path.rootPrefix(file);
final String root = fs.path.rootPrefix(file);
dartFiles.add(fs.file(file));
while (file != root) {
file = fs.path.dirname(file);
......@@ -45,15 +45,15 @@ class AnalyzeOnce extends AnalyzeBase {
}
}
bool currentDirectory = argResults['current-directory'] && (argResults.wasParsed('current-directory') || dartFiles.isEmpty);
bool currentPackage = argResults['current-package'] && (argResults.wasParsed('current-package') || dartFiles.isEmpty);
bool flutterRepo = argResults['flutter-repo'] || inRepo(argResults.rest);
final bool currentDirectory = argResults['current-directory'] && (argResults.wasParsed('current-directory') || dartFiles.isEmpty);
final bool currentPackage = argResults['current-package'] && (argResults.wasParsed('current-package') || dartFiles.isEmpty);
final bool flutterRepo = argResults['flutter-repo'] || inRepo(argResults.rest);
//TODO (pq): revisit package and directory defaults
if (currentDirectory && !flutterRepo) {
// ./*.dart
Directory currentDirectory = fs.directory('.');
final Directory currentDirectory = fs.directory('.');
bool foundOne = false;
for (FileSystemEntity entry in currentDirectory.listSync()) {
if (isDartFile(entry)) {
......@@ -67,7 +67,7 @@ class AnalyzeOnce extends AnalyzeBase {
if (currentPackage && !flutterRepo) {
// **/.*dart
Directory currentDirectory = fs.directory('.');
final Directory currentDirectory = fs.directory('.');
_collectDartFiles(currentDirectory, dartFiles);
pubSpecDirectories.add(currentDirectory);
}
......@@ -80,21 +80,21 @@ class AnalyzeOnce extends AnalyzeBase {
}
// determine what all the various .packages files depend on
PackageDependencyTracker dependencies = new PackageDependencyTracker();
final PackageDependencyTracker dependencies = new PackageDependencyTracker();
for (Directory directory in pubSpecDirectories) {
String pubSpecYamlPath = fs.path.join(directory.path, 'pubspec.yaml');
File pubSpecYamlFile = fs.file(pubSpecYamlPath);
final String pubSpecYamlPath = fs.path.join(directory.path, 'pubspec.yaml');
final File pubSpecYamlFile = fs.file(pubSpecYamlPath);
if (pubSpecYamlFile.existsSync()) {
// we are analyzing the actual canonical source for this package;
// make sure we remember that, in case all the packages are actually
// pointing elsewhere somehow.
yaml.YamlMap pubSpecYaml = yaml.loadYaml(fs.file(pubSpecYamlPath).readAsStringSync());
String packageName = pubSpecYaml['name'];
String packagePath = fs.path.normalize(fs.path.absolute(fs.path.join(directory.path, 'lib')));
final yaml.YamlMap pubSpecYaml = yaml.loadYaml(fs.file(pubSpecYamlPath).readAsStringSync());
final String packageName = pubSpecYaml['name'];
final String packagePath = fs.path.normalize(fs.path.absolute(fs.path.join(directory.path, 'lib')));
dependencies.addCanonicalCase(packageName, packagePath, pubSpecYamlPath);
}
String dotPackagesPath = fs.path.join(directory.path, '.packages');
File dotPackages = fs.file(dotPackagesPath);
final String dotPackagesPath = fs.path.join(directory.path, '.packages');
final File dotPackages = fs.file(dotPackagesPath);
if (dotPackages.existsSync()) {
// this directory has opinions about what we should be using
dotPackages
......@@ -102,10 +102,10 @@ class AnalyzeOnce extends AnalyzeBase {
.split('\n')
.where((String line) => !line.startsWith(new RegExp(r'^ *#')))
.forEach((String line) {
int colon = line.indexOf(':');
final int colon = line.indexOf(':');
if (colon > 0) {
String packageName = line.substring(0, colon);
String packagePath = fs.path.fromUri(line.substring(colon+1));
final String packageName = line.substring(0, colon);
final String packagePath = fs.path.fromUri(line.substring(colon+1));
// Ensure that we only add the `analyzer` package 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.
......@@ -118,7 +118,7 @@ class AnalyzeOnce extends AnalyzeBase {
// prepare a union of all the .packages files
if (dependencies.hasConflicts) {
StringBuffer message = new StringBuffer();
final StringBuffer message = new StringBuffer();
message.writeln(dependencies.generateConflictReport());
message.writeln('Make sure you have run "pub upgrade" in all the directories mentioned above.');
if (dependencies.hasConflictsAffectingFlutterRepo) {
......@@ -131,7 +131,7 @@ class AnalyzeOnce extends AnalyzeBase {
'"pub deps --style=list" and "pub upgrade --verbosity=solver" in the affected directories.');
throwToolExit(message.toString());
}
Map<String, String> packages = dependencies.asPackageMap();
final Map<String, String> packages = dependencies.asPackageMap();
Cache.releaseLockEarly();
......@@ -142,16 +142,16 @@ class AnalyzeOnce extends AnalyzeBase {
logger.printStatus('Analyzing ${dartFiles.length} files...');
}
}
DriverOptions options = new DriverOptions();
final DriverOptions options = new DriverOptions();
options.dartSdkPath = argResults['dart-sdk'];
options.packageMap = packages;
options.analysisOptionsFile = flutterRepo
? fs.path.join(Cache.flutterRoot, '.analysis_options_repo')
: fs.path.join(Cache.flutterRoot, 'packages', 'flutter', 'lib', 'analysis_options_user.yaml');
AnalysisDriver analyzer = new AnalysisDriver(options);
final AnalysisDriver analyzer = new AnalysisDriver(options);
// TODO(pq): consider error handling
List<AnalysisErrorDescription> errors = analyzer.analyze(dartFiles);
final List<AnalysisErrorDescription> errors = analyzer.analyze(dartFiles);
int errorCount = 0;
int membersMissingDocumentation = 0;
......@@ -176,7 +176,7 @@ class AnalyzeOnce extends AnalyzeBase {
dumpErrors(errors.map<String>((AnalysisErrorDescription error) => error.asString()));
stopwatch.stop();
String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
final String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
if (isBenchmarking)
writeBenchmark(stopwatch, errorCount, membersMissingDocumentation);
......@@ -200,7 +200,7 @@ class AnalyzeOnce extends AnalyzeBase {
List<String> flutterRootComponents;
bool isFlutterLibrary(String filename) {
flutterRootComponents ??= fs.path.normalize(fs.path.absolute(Cache.flutterRoot)).split(fs.path.separator);
List<String> filenameComponents = fs.path.normalize(fs.path.absolute(filename)).split(fs.path.separator);
final List<String> filenameComponents = fs.path.normalize(fs.path.absolute(filename)).split(fs.path.separator);
if (filenameComponents.length < flutterRootComponents.length + 4) // the 4: 'packages', package_name, 'lib', file_name
return false;
for (int index = 0; index < flutterRootComponents.length; index += 1) {
......@@ -225,7 +225,7 @@ class AnalyzeOnce extends AnalyzeBase {
if (isDartFile(entity))
collected.add(entity);
if (entity is Directory) {
String name = fs.path.basename(entity.path);
final String name = fs.path.basename(entity.path);
if (!name.startsWith('.') && name != 'packages')
_collectDartFiles(entity, collected);
}
......@@ -262,10 +262,10 @@ class PackageDependency {
}
void describeConflict(StringBuffer result) {
assert(hasConflict);
List<String> targets = values.keys.toList();
final List<String> targets = values.keys.toList();
targets.sort((String a, String b) => values[b].length.compareTo(values[a].length));
for (String target in targets) {
int count = values[target].length;
final int count = values[target].length;
result.writeln(' $count ${count == 1 ? 'source wants' : 'sources want'} "$target":');
bool canonical = false;
for (String source in values[target]) {
......@@ -308,7 +308,7 @@ class PackageDependencyTracker {
String generateConflictReport() {
assert(hasConflicts);
StringBuffer result = new StringBuffer();
final StringBuffer result = new StringBuffer();
for (String package in packages.keys.where((String package) => packages[package].hasConflict)) {
result.writeln('Package "$package" has conflicts:');
packages[package].describeConflict(result);
......@@ -317,7 +317,7 @@ class PackageDependencyTracker {
}
Map<String, String> asPackageMap() {
Map<String, String> result = <String, String>{};
final Map<String, String> result = <String, String>{};
for (String package in packages.keys)
result[package] = packages[package].target;
return result;
......
......@@ -54,14 +54,14 @@ abstract class BuildSubCommand extends FlutterCommand {
@mustCallSuper
Future<Null> runCommand() async {
if (isRunningOnBot) {
File dotPackages = fs.file('.packages');
final File dotPackages = fs.file('.packages');
printStatus('Contents of .packages:');
if (dotPackages.existsSync())
printStatus(dotPackages.readAsStringSync());
else
printError('File not found: ${dotPackages.absolute.path}');
File pubspecLock = fs.file('pubspec.lock');
final File pubspecLock = fs.file('pubspec.lock');
printStatus('Contents of pubspec.lock:');
if (pubspecLock.existsSync())
printStatus(pubspecLock.readAsStringSync());
......@@ -86,7 +86,7 @@ class BuildCleanCommand extends FlutterCommand {
@override
Future<Null> runCommand() async {
Directory buildDir = fs.directory(getBuildDirectory());
final Directory buildDir = fs.directory(getBuildDirectory());
printStatus("Deleting '${buildDir.path}${fs.path.separator}'.");
if (!buildDir.existsSync())
......
......@@ -45,15 +45,15 @@ class BuildAotCommand extends BuildSubCommand {
@override
Future<Null> runCommand() async {
await super.runCommand();
String targetPlatform = argResults['target-platform'];
TargetPlatform platform = getTargetPlatformForName(targetPlatform);
final String targetPlatform = argResults['target-platform'];
final TargetPlatform platform = getTargetPlatformForName(targetPlatform);
if (platform == null)
throwToolExit('Unknown platform: $targetPlatform');
String typeName = artifacts.getEngineType(platform, getBuildMode());
Status status = logger.startProgress('Building AOT snapshot in ${getModeName(getBuildMode())} mode ($typeName)...',
final String typeName = artifacts.getEngineType(platform, getBuildMode());
final Status status = logger.startProgress('Building AOT snapshot in ${getModeName(getBuildMode())} mode ($typeName)...',
expectSlowOperation: true);
String outputPath = await buildAotSnapshot(
final String outputPath = await buildAotSnapshot(
findMainDartFile(targetFile),
platform,
getBuildMode(),
......@@ -116,31 +116,31 @@ Future<String> _buildAotSnapshot(
return null;
}
String genSnapshot = artifacts.getArtifactPath(Artifact.genSnapshot, platform, buildMode);
final String genSnapshot = artifacts.getArtifactPath(Artifact.genSnapshot, platform, buildMode);
Directory outputDir = fs.directory(outputPath);
final Directory outputDir = fs.directory(outputPath);
outputDir.createSync(recursive: true);
String vmSnapshotData = fs.path.join(outputDir.path, 'vm_snapshot_data');
String vmSnapshotInstructions = fs.path.join(outputDir.path, 'vm_snapshot_instr');
String isolateSnapshotData = fs.path.join(outputDir.path, 'isolate_snapshot_data');
String isolateSnapshotInstructions = fs.path.join(outputDir.path, 'isolate_snapshot_instr');
final String vmSnapshotData = fs.path.join(outputDir.path, 'vm_snapshot_data');
final String vmSnapshotInstructions = fs.path.join(outputDir.path, 'vm_snapshot_instr');
final String isolateSnapshotData = fs.path.join(outputDir.path, 'isolate_snapshot_data');
final String isolateSnapshotInstructions = fs.path.join(outputDir.path, 'isolate_snapshot_instr');
String vmEntryPoints = artifacts.getArtifactPath(Artifact.dartVmEntryPointsTxt, platform, buildMode);
String ioEntryPoints = artifacts.getArtifactPath(Artifact.dartIoEntriesTxt, platform, buildMode);
final String vmEntryPoints = artifacts.getArtifactPath(Artifact.dartVmEntryPointsTxt, platform, buildMode);
final String ioEntryPoints = artifacts.getArtifactPath(Artifact.dartIoEntriesTxt, platform, buildMode);
PackageMap packageMap = new PackageMap(PackageMap.globalPackagesPath);
String packageMapError = packageMap.checkValid();
final PackageMap packageMap = new PackageMap(PackageMap.globalPackagesPath);
final String packageMapError = packageMap.checkValid();
if (packageMapError != null) {
printError(packageMapError);
return null;
}
String skyEnginePkg = _getSdkExtensionPath(packageMap, 'sky_engine');
String uiPath = fs.path.join(skyEnginePkg, 'dart_ui', 'ui.dart');
String jniPath = fs.path.join(skyEnginePkg, 'dart_jni', 'jni.dart');
String vmServicePath = fs.path.join(skyEnginePkg, 'sdk_ext', 'vmservice_io.dart');
final String skyEnginePkg = _getSdkExtensionPath(packageMap, 'sky_engine');
final String uiPath = fs.path.join(skyEnginePkg, 'dart_ui', 'ui.dart');
final String jniPath = fs.path.join(skyEnginePkg, 'dart_jni', 'jni.dart');
final String vmServicePath = fs.path.join(skyEnginePkg, 'sdk_ext', 'vmservice_io.dart');
List<String> filePaths = <String>[
final List<String> filePaths = <String>[
vmEntryPoints,
ioEntryPoints,
uiPath,
......@@ -177,7 +177,7 @@ Future<String> _buildAotSnapshot(
assert(false);
}
List<String> missingFiles = filePaths.where((String p) => !fs.isFileSync(p)).toList();
final List<String> missingFiles = filePaths.where((String p) => !fs.isFileSync(p)).toList();
if (missingFiles.isNotEmpty) {
printError('Missing files: $missingFiles');
return null;
......@@ -187,7 +187,7 @@ Future<String> _buildAotSnapshot(
return null;
}
List<String> genSnapshotCmd = <String>[
final List<String> genSnapshotCmd = <String>[
genSnapshot,
'--assert_initializer',
'--await_is_keyword',
......@@ -242,7 +242,7 @@ Future<String> _buildAotSnapshot(
genSnapshotCmd.add(mainPath);
RunResult results = await runAsync(genSnapshotCmd);
final RunResult results = await runAsync(genSnapshotCmd);
if (results.exitCode != 0) {
printError('Dart snapshot generator failed with exit code ${results.exitCode}');
printError(results.toString());
......@@ -255,16 +255,16 @@ Future<String> _buildAotSnapshot(
printStatus('Building app.dylib...');
// These names are known to from the engine.
String kVmSnapshotData = 'kDartVmSnapshotData';
String kIsolateSnapshotData = 'kDartIsolateSnapshotData';
final String kVmSnapshotData = 'kDartVmSnapshotData';
final String kIsolateSnapshotData = 'kDartIsolateSnapshotData';
String kVmSnapshotDataC = fs.path.join(outputDir.path, '$kVmSnapshotData.c');
String kIsolateSnapshotDataC = fs.path.join(outputDir.path, '$kIsolateSnapshotData.c');
String kVmSnapshotDataO = fs.path.join(outputDir.path, '$kVmSnapshotData.o');
String kIsolateSnapshotDataO = fs.path.join(outputDir.path, '$kIsolateSnapshotData.o');
String assemblyO = fs.path.join(outputDir.path, 'snapshot_assembly.o');
final String kVmSnapshotDataC = fs.path.join(outputDir.path, '$kVmSnapshotData.c');
final String kIsolateSnapshotDataC = fs.path.join(outputDir.path, '$kIsolateSnapshotData.c');
final String kVmSnapshotDataO = fs.path.join(outputDir.path, '$kVmSnapshotData.o');
final String kIsolateSnapshotDataO = fs.path.join(outputDir.path, '$kIsolateSnapshotData.o');
final String assemblyO = fs.path.join(outputDir.path, 'snapshot_assembly.o');
List<String> commonBuildOptions = <String>['-arch', 'arm64', '-miphoneos-version-min=8.0'];
final List<String> commonBuildOptions = <String>['-arch', 'arm64', '-miphoneos-version-min=8.0'];
if (interpreter) {
runCheckedSync(<String>['mv', vmSnapshotData, fs.path.join(outputDir.path, kVmSnapshotData)]);
......@@ -289,9 +289,9 @@ Future<String> _buildAotSnapshot(
..addAll(<String>['-c', assembly, '-o', assemblyO]));
}
String appSo = fs.path.join(outputDir.path, 'app.dylib');
final String appSo = fs.path.join(outputDir.path, 'app.dylib');
List<String> linkCommand = <String>['xcrun', 'clang']
final List<String> linkCommand = <String>['xcrun', 'clang']
..addAll(commonBuildOptions)
..addAll(<String>[
'-dynamiclib',
......
......@@ -39,7 +39,7 @@ class BuildFlxCommand extends BuildSubCommand {
@override
Future<Null> runCommand() async {
await super.runCommand();
String outputPath = argResults['output-file'];
final String outputPath = argResults['output-file'];
await build(
mainPath: targetFile,
......
......@@ -39,19 +39,19 @@ class BuildIOSCommand extends BuildSubCommand {
@override
Future<Null> runCommand() async {
bool forSimulator = argResults['simulator'];
final bool forSimulator = argResults['simulator'];
defaultBuildMode = forSimulator ? BuildMode.debug : BuildMode.release;
await super.runCommand();
if (getCurrentHostPlatform() != HostPlatform.darwin_x64)
throwToolExit('Building for iOS is only supported on the Mac.');
IOSApp app = applicationPackages.getPackageForPlatform(TargetPlatform.ios);
final IOSApp app = applicationPackages.getPackageForPlatform(TargetPlatform.ios);
if (app == null)
throwToolExit('Application not configured for iOS');
bool shouldCodesign = argResults['codesign'];
final bool shouldCodesign = argResults['codesign'];
if (!forSimulator && !shouldCodesign) {
printStatus('Warning: Building for device with codesigning disabled. You will '
......@@ -61,12 +61,12 @@ class BuildIOSCommand extends BuildSubCommand {
if (forSimulator && !isEmulatorBuildMode(getBuildMode()))
throwToolExit('${toTitleCase(getModeName(getBuildMode()))} mode is not supported for emulators.');
String logTarget = forSimulator ? 'simulator' : 'device';
final String logTarget = forSimulator ? 'simulator' : 'device';
String typeName = artifacts.getEngineType(TargetPlatform.ios, getBuildMode());
Status status = logger.startProgress('Building $app for $logTarget ($typeName)...',
final String typeName = artifacts.getEngineType(TargetPlatform.ios, getBuildMode());
final Status status = logger.startProgress('Building $app for $logTarget ($typeName)...',
expectSlowOperation: true);
XcodeBuildResult result = await buildXcodeProject(
final XcodeBuildResult result = await buildXcodeProject(
app: app,
mode: getBuildMode(),
target: targetFile,
......
......@@ -33,18 +33,18 @@ class ChannelCommand extends FlutterCommand {
}
Future<Null> _listChannels() async {
String currentBranch = runSync(
final String currentBranch = runSync(
<String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
workingDirectory: Cache.flutterRoot);
printStatus('Flutter channels:');
int result = await runCommandAndStreamOutput(
final int result = await runCommandAndStreamOutput(
<String>['git', 'branch', '-r'],
workingDirectory: Cache.flutterRoot,
mapFunction: (String line) {
List<String> split = line.split('/');
final List<String> split = line.split('/');
if (split.length < 2) return null;
String branchName = split[1];
final String branchName = split[1];
if (branchName.startsWith('HEAD')) return null;
if (branchName == currentBranch) return '* $branchName';
return ' $branchName';
......@@ -56,7 +56,7 @@ class ChannelCommand extends FlutterCommand {
Future<Null> _switchChannel(String branchName) async {
printStatus('Switching to flutter channel named $branchName');
int result = await runCommandAndStreamOutput(
final int result = await runCommandAndStreamOutput(
<String>['git', 'checkout', branchName],
workingDirectory: Cache.flutterRoot,
);
......
......@@ -49,7 +49,7 @@ class ConfigCommand extends FlutterCommand {
@override
Future<Null> runCommand() async {
if (argResults.wasParsed('analytics')) {
bool value = argResults['analytics'];
final bool value = argResults['analytics'];
flutterUsage.enabled = value;
printStatus('Analytics reporting ${value ? 'enabled' : 'disabled'}.');
}
......
......@@ -69,21 +69,21 @@ class CreateCommand extends FlutterCommand {
await Cache.instance.updateAll();
String flutterRoot = fs.path.absolute(Cache.flutterRoot);
final String flutterRoot = fs.path.absolute(Cache.flutterRoot);
String flutterPackagesDirectory = fs.path.join(flutterRoot, 'packages');
String flutterPackagePath = fs.path.join(flutterPackagesDirectory, 'flutter');
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')))
throwToolExit('Unable to find package:flutter in $flutterPackagePath', exitCode: 2);
String flutterDriverPackagePath = fs.path.join(flutterRoot, 'packages', 'flutter_driver');
final String flutterDriverPackagePath = fs.path.join(flutterRoot, 'packages', 'flutter_driver');
if (!fs.isFileSync(fs.path.join(flutterDriverPackagePath, 'pubspec.yaml')))
throwToolExit('Unable to find package:flutter_driver in $flutterDriverPackagePath', exitCode: 2);
Directory projectDir = fs.directory(argResults.rest.first);
String dirPath = fs.path.normalize(projectDir.absolute.path);
String relativePath = fs.path.relative(dirPath);
String projectName = _normalizeProjectName(fs.path.basename(dirPath));
final Directory projectDir = fs.directory(argResults.rest.first);
final String dirPath = fs.path.normalize(projectDir.absolute.path);
final String relativePath = fs.path.relative(dirPath);
final String projectName = _normalizeProjectName(fs.path.basename(dirPath));
String error =_validateProjectDir(dirPath, flutterRoot: flutterRoot);
if (error != null)
......@@ -93,7 +93,7 @@ class CreateCommand extends FlutterCommand {
if (error != null)
throwToolExit(error);
int generatedCount = _renderTemplates(
final int generatedCount = _renderTemplates(
projectName,
argResults['description'],
dirPath,
......@@ -148,7 +148,7 @@ Your main program file is lib/main.dart in the $relativePath directory.
printStatus('Creating project ${fs.path.relative(dirPath)}...');
Map<String, dynamic> templateContext = <String, dynamic>{
final Map<String, dynamic> templateContext = <String, dynamic>{
'projectName': projectName,
'androidIdentifier': _createAndroidIdentifier(projectName),
'iosIdentifier': _createUTIIdentifier(projectName),
......@@ -161,7 +161,7 @@ Your main program file is lib/main.dart in the $relativePath directory.
templateContext['withDriverTest'] = renderDriverTest;
Template createTemplate = new Template.fromName('create');
final Template createTemplate = new Template.fromName('create');
fileCount += createTemplate.render(
fs.directory(dirPath),
templateContext, overwriteExisting: false,
......@@ -169,7 +169,7 @@ Your main program file is lib/main.dart in the $relativePath directory.
);
if (renderDriverTest) {
Template driverTemplate = new Template.fromName('driver');
final Template driverTemplate = new Template.fromName('driver');
fileCount += driverTemplate.render(fs.directory(fs.path.join(dirPath, 'test_driver')),
templateContext, overwriteExisting: false);
}
......@@ -192,7 +192,7 @@ String _createAndroidIdentifier(String name) {
String _createUTIIdentifier(String name) {
// Create a UTI (https://en.wikipedia.org/wiki/Uniform_Type_Identifier) from a base name
RegExp disallowed = new RegExp(r"[^a-zA-Z0-9\-\.\u0080-\uffff]+");
final RegExp disallowed = new RegExp(r"[^a-zA-Z0-9\-\.\u0080-\uffff]+");
name = camelCase(name).replaceAll(disallowed, '');
name = name.isEmpty ? 'untitled' : name;
return 'com.yourcompany.$name';
......@@ -236,7 +236,7 @@ String _validateProjectDir(String dirPath, { String flutterRoot }) {
"Target directory '$dirPath' is within the Flutter SDK at '$flutterRoot'.";
}
FileSystemEntityType type = fs.typeSync(dirPath);
final FileSystemEntityType type = fs.typeSync(dirPath);
if (type != FileSystemEntityType.NOT_FOUND) {
switch(type) {
......@@ -253,7 +253,7 @@ String _validateProjectDir(String dirPath, { String flutterRoot }) {
}
String _relativePath({ String from, String to }) {
String result = fs.path.relative(to, from: from);
final String result = fs.path.relative(to, from: from);
// `fs.path.relative()` doesn't always return a correct result: dart-lang/path#12.
if (fs.isDirectorySync(fs.path.join(from, result)))
return result;
......
......@@ -27,7 +27,7 @@ class DevicesCommand extends FlutterCommand {
exitCode: 1);
}
List<Device> devices = await deviceManager.getAllConnectedDevices();
final List<Device> devices = await deviceManager.getAllConnectedDevices();
if (devices.isEmpty) {
printStatus(
......
......@@ -85,7 +85,7 @@ class DriveCommand extends RunCommandBase {
@override
Future<Null> runCommand() async {
String testFile = _getTestFile();
final String testFile = _getTestFile();
if (testFile == null)
throwToolExit(null);
......@@ -110,7 +110,7 @@ class DriveCommand extends RunCommandBase {
);
}
LaunchResult result = await appStarter(this);
final LaunchResult result = await appStarter(this);
if (result == null)
throwToolExit('Application failed to start. Will not run test. Quitting.', exitCode: 1);
observatoryUri = result.observatoryUri.toString();
......@@ -141,7 +141,7 @@ class DriveCommand extends RunCommandBase {
String appFile = fs.path.normalize(targetFile);
// This command extends `flutter start` and therefore CWD == package dir
String packageDir = fs.currentDirectory.path;
final String packageDir = fs.currentDirectory.path;
// Make appFile path relative to package directory because we are looking
// for the corresponding test file relative to it.
......@@ -156,7 +156,7 @@ class DriveCommand extends RunCommandBase {
appFile = fs.path.relative(appFile, from: packageDir);
}
List<String> parts = fs.path.split(appFile);
final List<String> parts = fs.path.split(appFile);
if (parts.length < 2) {
printError(
......@@ -169,7 +169,7 @@ class DriveCommand extends RunCommandBase {
// Look for the test file inside `test_driver/` matching the sub-path, e.g.
// if the application is `lib/foo/bar.dart`, the test file is expected to
// be `test_driver/foo/bar_test.dart`.
String pathWithNoExtension = fs.path.withoutExtension(fs.path.joinAll(
final String pathWithNoExtension = fs.path.withoutExtension(fs.path.joinAll(
<String>[packageDir, 'test_driver']..addAll(parts.skip(1))));
return '${pathWithNoExtension}_test${fs.path.extension(appFile)}';
}
......@@ -183,7 +183,7 @@ void restoreTargetDeviceFinder() {
}
Future<Device> findTargetDevice() async {
List<Device> devices = await deviceManager.getDevices();
final List<Device> devices = await deviceManager.getDevices();
if (deviceManager.hasSpecifiedDeviceId) {
if (devices.isEmpty) {
......@@ -203,7 +203,7 @@ Future<Device> findTargetDevice() async {
// On Mac we look for the iOS Simulator. If available, we use that. Then
// we look for an Android device. If there's one, we use that. Otherwise,
// we launch a new iOS Simulator.
Device reusableDevice = devices.firstWhere(
final Device reusableDevice = devices.firstWhere(
(Device d) => d.isLocalEmulator,
orElse: () {
return devices.firstWhere((Device d) => d is AndroidDevice,
......@@ -218,7 +218,7 @@ Future<Device> findTargetDevice() async {
// No running emulator found. Attempt to start one.
printStatus('Starting iOS Simulator, because did not find existing connected devices.');
bool started = await SimControl.instance.boot();
final bool started = await SimControl.instance.boot();
if (started) {
return IOSSimulatorUtils.instance.getAttachedDevices().first;
} else {
......@@ -251,7 +251,7 @@ void restoreAppStarter() {
}
Future<LaunchResult> _startApp(DriveCommand command) async {
String mainPath = findMainDartFile(command.targetFile);
final String mainPath = findMainDartFile(command.targetFile);
if (await fs.type(mainPath) != FileSystemEntityType.FILE) {
printError('Tried to run $mainPath, but that file does not exist.');
return null;
......@@ -261,13 +261,13 @@ Future<LaunchResult> _startApp(DriveCommand command) async {
await appStopper(command);
printTrace('Installing application package.');
ApplicationPackage package = command.applicationPackages
final ApplicationPackage package = command.applicationPackages
.getPackageForPlatform(command.device.platform);
if (command.device.isAppInstalled(package))
command.device.uninstallApp(package);
command.device.installApp(package);
Map<String, dynamic> platformArgs = <String, dynamic>{};
final Map<String, dynamic> platformArgs = <String, dynamic>{};
if (command.traceStartup)
platformArgs['trace-startup'] = command.traceStartup;
......@@ -280,7 +280,7 @@ Future<LaunchResult> _startApp(DriveCommand command) async {
.logLines
.listen(printStatus);
LaunchResult result = await command.device.startApp(
final LaunchResult result = await command.device.startApp(
package,
command.getBuildMode(),
mainPath: mainPath,
......@@ -313,11 +313,11 @@ Future<Null> _runTests(List<String> testArgs, String observatoryUri) async {
printTrace('Running driver tests.');
PackageMap.globalPackagesPath = fs.path.normalize(fs.path.absolute(PackageMap.globalPackagesPath));
List<String> args = testArgs.toList()
final List<String> args = testArgs.toList()
..add('--packages=${PackageMap.globalPackagesPath}')
..add('-rexpanded');
String dartVmPath = fs.path.join(dartSdkPath, 'bin', 'dart');
int result = await runCommandAndStreamOutput(
final String dartVmPath = fs.path.join(dartSdkPath, 'bin', 'dart');
final int result = await runCommandAndStreamOutput(
<String>[dartVmPath]..addAll(args),
environment: <String, String>{ 'VM_SERVICE_URL': observatoryUri }
);
......@@ -335,8 +335,8 @@ void restoreAppStopper() {
Future<bool> _stopApp(DriveCommand command) async {
printTrace('Stopping application.');
ApplicationPackage package = command.applicationPackages.getPackageForPlatform(command.device.platform);
bool stopped = await command.device.stopApp(package);
final ApplicationPackage package = command.applicationPackages.getPackageForPlatform(command.device.platform);
final bool stopped = await command.device.stopApp(package);
await command._deviceLogSubscription?.cancel();
return stopped;
}
......@@ -36,9 +36,9 @@ class FormatCommand extends FlutterCommand {
);
}
String dartfmt = fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dartfmt');
List<String> cmd = <String>[dartfmt, '-w']..addAll(argResults.rest);
int result = await runCommandAndStreamOutput(cmd);
final String dartfmt = fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dartfmt');
final List<String> cmd = <String>[dartfmt, '-w']..addAll(argResults.rest);
final int result = await runCommandAndStreamOutput(cmd);
if (result != 0)
throwToolExit('Formatting failed: $result', exitCode: result);
}
......
......@@ -31,7 +31,7 @@ class InstallCommand extends FlutterCommand {
@override
Future<Null> runCommand() async {
ApplicationPackage package = applicationPackages.getPackageForPlatform(device.platform);
final ApplicationPackage package = applicationPackages.getPackageForPlatform(device.platform);
Cache.releaseLockEarly();
......
......@@ -42,16 +42,16 @@ class LogsCommand extends FlutterCommand {
if (argResults['clear'])
device.clearLogs();
DeviceLogReader logReader = device.getLogReader();
final DeviceLogReader logReader = device.getLogReader();
Cache.releaseLockEarly();
printStatus('Showing $logReader logs:');
Completer<int> exitCompleter = new Completer<int>();
final Completer<int> exitCompleter = new Completer<int>();
// Start reading.
StreamSubscription<String> subscription = logReader.logLines.listen(
final StreamSubscription<String> subscription = logReader.logLines.listen(
printStatus,
onDone: () {
exitCompleter.complete(0);
......@@ -75,7 +75,7 @@ class LogsCommand extends FlutterCommand {
}
// Wait for the log reader to be finished.
int result = await exitCompleter.future;
final int result = await exitCompleter.future;
subscription.cancel();
if (result != 0)
throwToolExit('Error listening to $logReader logs.');
......
......@@ -56,7 +56,7 @@ class PackagesGetCommand extends FlutterCommand {
if (argResults.rest.length > 1)
throwToolExit('Too many arguments.\n$usage');
String target = findProjectRoot(
final String target = findProjectRoot(
argResults.rest.length == 1 ? argResults.rest[0] : null);
if (target == null)
throwToolExit(
......
......@@ -148,7 +148,7 @@ class RunCommand extends RunCommandBase {
@override
String get usagePath {
String command = shouldUseHotMode() ? 'hotrun' : name;
final String command = shouldUseHotMode() ? 'hotrun' : name;
if (device == null)
return command;
......@@ -180,7 +180,7 @@ class RunCommand extends RunCommandBase {
}
bool shouldUseHotMode() {
bool hotArg = argResults['hot'] ?? false;
final bool hotArg = argResults['hot'] ?? false;
final bool shouldUseHotMode = hotArg;
return (getBuildMode() == BuildMode.debug) && shouldUseHotMode;
}
......@@ -209,7 +209,7 @@ class RunCommand extends RunCommandBase {
final bool hotMode = shouldUseHotMode();
if (argResults['machine']) {
Daemon daemon = new Daemon(stdinCommandStream, stdoutCommandResponse,
final Daemon daemon = new Daemon(stdinCommandStream, stdoutCommandResponse,
notifyingLogger: new NotifyingLogger(), logToStdout: true);
AppInstance app;
try {
......@@ -223,7 +223,7 @@ class RunCommand extends RunCommandBase {
} catch (error) {
throwToolExit(error.toString());
}
int result = await app.runner.waitForAppToFinish();
final int result = await app.runner.waitForAppToFinish();
if (result != 0)
throwToolExit(null, exitCode: result);
return null;
......@@ -250,7 +250,7 @@ class RunCommand extends RunCommandBase {
throwToolExit('Hot mode is not supported by this device. Run with --no-hot.');
}
String pidFile = argResults['pid-file'];
final String pidFile = argResults['pid-file'];
if (pidFile != null) {
// Write our pid to the file.
fs.file(pidFile).writeAsStringSync(pid.toString());
......@@ -281,7 +281,7 @@ class RunCommand extends RunCommandBase {
);
}
int result = await runner.run(
final int result = await runner.run(
route: route,
shouldBuild: !runningWithPrebuiltApplication && argResults['build'],
);
......
......@@ -92,7 +92,7 @@ class ScreenshotCommand extends FlutterCommand {
}
Future<Null> runSkia(File outputFile) async {
Uri skpUri = new Uri(scheme: 'http', host: '127.0.0.1',
final Uri skpUri = new Uri(scheme: 'http', host: '127.0.0.1',
port: int.parse(argResults[_kSkia]),
path: '/skp');
......@@ -108,28 +108,28 @@ class ScreenshotCommand extends FlutterCommand {
throwToolExit('Skia screenshot failed: $skpUri\n$e\n\n$errorHelpText');
}
if (skpResponse.statusCode != HttpStatus.OK) {
String error = await skpResponse.stream.toStringStream().join();
final String error = await skpResponse.stream.toStringStream().join();
throwToolExit('Error: $error\n\n$errorHelpText');
}
if (argResults[_kSkiaServe] != null) {
Uri skiaserveUri = Uri.parse(argResults[_kSkiaServe]);
Uri postUri = new Uri.http(skiaserveUri.authority, '/new');
http.MultipartRequest postRequest = new http.MultipartRequest('POST', postUri);
final Uri skiaserveUri = Uri.parse(argResults[_kSkiaServe]);
final Uri postUri = new Uri.http(skiaserveUri.authority, '/new');
final http.MultipartRequest postRequest = new http.MultipartRequest('POST', postUri);
postRequest.files.add(new http.MultipartFile(
'file', skpResponse.stream, skpResponse.contentLength));
http.StreamedResponse postResponse = await postRequest.send();
final http.StreamedResponse postResponse = await postRequest.send();
if (postResponse.statusCode != HttpStatus.OK)
throwToolExit('Failed to post Skia picture to skiaserve.\n\n$errorHelpText');
} else {
outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'skp');
IOSink sink = outputFile.openWrite();
final IOSink sink = outputFile.openWrite();
await sink.addStream(skpResponse.stream);
await sink.close();
await showOutputFileInfo(outputFile);
if (await outputFile.length() < 1000) {
String content = await outputFile.readAsString();
final String content = await outputFile.readAsString();
if (content.startsWith('{"jsonrpc":"2.0", "error"'))
throwToolExit('\nIt appears the output file contains an error message, not valid skia output.\n\n$errorHelpText');
}
......@@ -137,7 +137,7 @@ class ScreenshotCommand extends FlutterCommand {
}
Future<Null> showOutputFileInfo(File outputFile) async {
int sizeKB = (await outputFile.length()) ~/ 1024;
final int sizeKB = (await outputFile.length()) ~/ 1024;
printStatus('Screenshot written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).');
}
}
......@@ -31,9 +31,9 @@ class StopCommand extends FlutterCommand {
@override
Future<Null> runCommand() async {
ApplicationPackage app = applicationPackages.getPackageForPlatform(device.platform);
final ApplicationPackage app = applicationPackages.getPackageForPlatform(device.platform);
if (app == null) {
String platformName = getNameForTargetPlatform(device.platform);
final String platformName = getNameForTargetPlatform(device.platform);
throwToolExit('No Flutter application for $platformName found in the current directory.');
}
printStatus('Stopping apps on ${device.name}.');
......
......@@ -78,7 +78,7 @@ class TestCommand extends FlutterCommand {
}
Future<int> _runTests(List<String> testArgs, Directory testDirectory) async {
Directory currentDirectory = fs.currentDirectory;
final Directory currentDirectory = fs.currentDirectory;
try {
if (testDirectory != null) {
printTrace('switching to directory $testDirectory to run tests');
......@@ -96,8 +96,8 @@ class TestCommand extends FlutterCommand {
}
Future<bool> _collectCoverageData(CoverageCollector collector, { bool mergeCoverageData: false }) async {
Status status = logger.startProgress('Collecting coverage information...');
String coverageData = await collector.finalizeCoverage(
final Status status = logger.startProgress('Collecting coverage information...');
final String coverageData = await collector.finalizeCoverage(
timeout: const Duration(seconds: 30),
);
status.stop();
......@@ -105,13 +105,13 @@ class TestCommand extends FlutterCommand {
if (coverageData == null)
return false;
String coveragePath = argResults['coverage-path'];
File coverageFile = fs.file(coveragePath)
final String coveragePath = argResults['coverage-path'];
final File coverageFile = fs.file(coveragePath)
..createSync(recursive: true)
..writeAsStringSync(coverageData, flush: true);
printTrace('wrote coverage data to $coveragePath (size=${coverageData.length})');
String baseCoverageData = 'coverage/lcov.base.info';
final String baseCoverageData = 'coverage/lcov.base.info';
if (mergeCoverageData) {
if (!platform.isLinux) {
printError(
......@@ -136,10 +136,10 @@ class TestCommand extends FlutterCommand {
return false;
}
Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
try {
File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info'));
ProcessResult result = processManager.runSync(<String>[
final File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info'));
final ProcessResult result = processManager.runSync(<String>[
'lcov',
'--add-tracefile', baseCoverageData,
'--add-tracefile', sourceFile.path,
......@@ -163,7 +163,7 @@ class TestCommand extends FlutterCommand {
);
}
List<String> testArgs = <String>[];
final List<String> testArgs = <String>[];
commandValidator();
......@@ -208,7 +208,7 @@ class TestCommand extends FlutterCommand {
Cache.releaseLockEarly();
int result = await _runTests(testArgs, testDir);
final int result = await _runTests(testArgs, testDir);
if (collector != null) {
if (!await _collectCoverageData(collector, mergeCoverageData: argResults['merge-coverage']))
......
......@@ -51,11 +51,11 @@ class TraceCommand extends FlutterCommand {
@override
Future<Null> runCommand() async {
int observatoryPort = int.parse(argResults['debug-port']);
final int observatoryPort = int.parse(argResults['debug-port']);
// TODO(danrubel): this will break if we move to the new observatory URL
// See https://github.com/flutter/flutter/issues/7038
Uri observatoryUri = Uri.parse('http://127.0.0.1:$observatoryPort');
final Uri observatoryUri = Uri.parse('http://127.0.0.1:$observatoryPort');
Tracing tracing;
......@@ -84,7 +84,7 @@ class TraceCommand extends FlutterCommand {
}
Future<Null> _stopTracing(Tracing tracing) async {
Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline();
final Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline();
File localFile;
if (argResults['out'] != null) {
......@@ -103,7 +103,7 @@ class Tracing {
Tracing(this.vmService);
static Tracing connect(Uri uri) {
VMService observatory = VMService.connect(uri);
final VMService observatory = VMService.connect(uri);
return new Tracing(observatory);
}
......@@ -125,10 +125,10 @@ class Tracing {
await vmService.vm.setVMTimelineFlags(<String>[]);
timeline = await vmService.vm.getVMTimeline();
} else {
Completer<Null> whenFirstFrameRendered = new Completer<Null>();
final Completer<Null> whenFirstFrameRendered = new Completer<Null>();
vmService.onTimelineEvent.listen((ServiceEvent timelineEvent) {
List<Map<String, dynamic>> events = timelineEvent.timelineEvents;
final List<Map<String, dynamic>> events = timelineEvent.timelineEvents;
for (Map<String, dynamic> event in events) {
if (event['name'] == kFirstUsefulFrameEventName)
whenFirstFrameRendered.complete();
......@@ -159,8 +159,8 @@ class Tracing {
/// Download the startup trace information from the given observatory client and
/// store it to build/start_up_info.json.
Future<Null> downloadStartupTrace(VMService observatory) async {
String traceInfoFilePath = fs.path.join(getBuildDirectory(), 'start_up_info.json');
File traceInfoFile = fs.file(traceInfoFilePath);
final String traceInfoFilePath = fs.path.join(getBuildDirectory(), 'start_up_info.json');
final File traceInfoFile = fs.file(traceInfoFilePath);
// Delete old startup data, if any.
if (await traceInfoFile.exists())
......@@ -170,23 +170,23 @@ Future<Null> downloadStartupTrace(VMService observatory) async {
if (!(await traceInfoFile.parent.exists()))
await traceInfoFile.parent.create();
Tracing tracing = new Tracing(observatory);
final Tracing tracing = new Tracing(observatory);
Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline(
final Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline(
waitForFirstFrame: true
);
int extractInstantEventTimestamp(String eventName) {
List<Map<String, dynamic>> events = timeline['traceEvents'];
Map<String, dynamic> event = events.firstWhere(
final List<Map<String, dynamic>> events = timeline['traceEvents'];
final Map<String, dynamic> event = events.firstWhere(
(Map<String, dynamic> event) => event['name'] == eventName, orElse: () => null
);
return event == null ? null : event['ts'];
}
int engineEnterTimestampMicros = extractInstantEventTimestamp(kFlutterEngineMainEnterEventName);
int frameworkInitTimestampMicros = extractInstantEventTimestamp(kFrameworkInitEventName);
int firstFrameTimestampMicros = extractInstantEventTimestamp(kFirstUsefulFrameEventName);
final int engineEnterTimestampMicros = extractInstantEventTimestamp(kFlutterEngineMainEnterEventName);
final int frameworkInitTimestampMicros = extractInstantEventTimestamp(kFrameworkInitEventName);
final int firstFrameTimestampMicros = extractInstantEventTimestamp(kFirstUsefulFrameEventName);
if (engineEnterTimestampMicros == null) {
throw 'Engine start event is missing in the timeline. Cannot compute startup time.';
......@@ -196,8 +196,8 @@ Future<Null> downloadStartupTrace(VMService observatory) async {
throw 'First frame event is missing in the timeline. Cannot compute startup time.';
}
int timeToFirstFrameMicros = firstFrameTimestampMicros - engineEnterTimestampMicros;
Map<String, dynamic> traceInfo = <String, dynamic>{
final int timeToFirstFrameMicros = firstFrameTimestampMicros - engineEnterTimestampMicros;
final Map<String, dynamic> traceInfo = <String, dynamic>{
'engineEnterTimestampMicros': engineEnterTimestampMicros,
'timeToFirstFrameMicros': timeToFirstFrameMicros,
};
......
......@@ -31,7 +31,7 @@ class UpdatePackagesCommand extends FlutterCommand {
final bool hidden;
Future<Null> _downloadCoverageData() async {
Status status = logger.startProgress("Downloading lcov data for package:flutter...", expectSlowOperation: true);
final Status status = logger.startProgress("Downloading lcov data for package:flutter...", expectSlowOperation: true);
final List<int> data = await fetchUrl(Uri.parse('https://storage.googleapis.com/flutter_infra/flutter/coverage/lcov.info'));
final String coverageDir = fs.path.join(Cache.flutterRoot, 'packages/flutter/coverage');
fs.file(fs.path.join(coverageDir, 'lcov.base.info'))
......
......@@ -32,7 +32,7 @@ class UpgradeCommand extends FlutterCommand {
throwToolExit('Unable to upgrade Flutter: no upstream repository configured.');
}
FlutterVersion version = new FlutterVersion(Cache.flutterRoot);
final FlutterVersion version = new FlutterVersion(Cache.flutterRoot);
if (version.channel == 'alpha') {
// The alpha branch is deprecated. Rather than trying to pull the alpha
// branch, we should switch upstream to master.
......@@ -68,7 +68,7 @@ class UpgradeCommand extends FlutterCommand {
printStatus('');
printStatus(FlutterVersion.getVersion(Cache.flutterRoot).toString());
String projRoot = findProjectRoot();
final String projRoot = findProjectRoot();
if (projRoot != null) {
printStatus('');
await pubGet(directory: projRoot, upgrade: true, checkLastModified: false);
......
......@@ -85,20 +85,20 @@ class CrashReportSender {
printStatus('Sending crash report to Google.');
Uri uri = _baseUri.replace(
final Uri uri = _baseUri.replace(
queryParameters: <String, String>{
'product': _kProductId,
'version': flutterVersion,
},
);
_MultipartRequest req = new _MultipartRequest('POST', uri);
final _MultipartRequest req = new _MultipartRequest('POST', uri);
req.fields['product'] = _kProductId;
req.fields['version'] = flutterVersion;
req.fields['type'] = _kDartTypeId;
req.fields['error_runtime_type'] = '${error.runtimeType}';
Chain chain = stackTrace is StackTrace
final Chain chain = stackTrace is StackTrace
? new Chain.forTrace(stackTrace)
: new Chain.parse(stackTrace.toString());
......@@ -108,10 +108,10 @@ class CrashReportSender {
filename: _kStackTraceFilename,
));
http.StreamedResponse resp = await _client.send(req);
final http.StreamedResponse resp = await _client.send(req);
if (resp.statusCode == 200) {
String reportId = await new http.ByteStream(resp.stream)
final String reportId = await new http.ByteStream(resp.stream)
.bytesToString();
printStatus('Crash report sent (report ID: $reportId)');
} else {
......@@ -225,11 +225,11 @@ class _MultipartRequest extends http.BaseRequest {
/// that will emit the request body.
@override
http.ByteStream finalize() {
String boundary = _boundaryString();
final String boundary = _boundaryString();
headers['content-type'] = 'multipart/form-data; boundary=$boundary';
super.finalize();
StreamController<List<int>> controller = new StreamController<List<int>>(sync: true);
final StreamController<List<int>> controller = new StreamController<List<int>>(sync: true);
void writeAscii(String string) {
controller.add(UTF8.encode(string));
......@@ -369,8 +369,8 @@ class _MultipartRequest extends http.BaseRequest {
/// Returns a randomly-generated multipart boundary string
String _boundaryString() {
String prefix = "dart-";
List<int> list = new List<int>.generate(_BOUNDARY_LENGTH - prefix.length,
final String prefix = "dart-";
final List<int> list = new List<int>.generate(_BOUNDARY_LENGTH - prefix.length,
(int index) =>
_BOUNDARY_CHARACTERS[_random.nextInt(_BOUNDARY_CHARACTERS.length)],
growable: false);
......@@ -382,7 +382,7 @@ class _MultipartRequest extends http.BaseRequest {
/// [stream] is done. Unlike [store], [sink] remains open after [stream] is
/// done.
Future<Null> writeStreamToSink<O, I extends O>(Stream<I> stream, EventSink<O> sink) {
Completer<Null> completer = new Completer<Null>();
final Completer<Null> completer = new Completer<Null>();
stream.listen(sink.add,
onError: sink.addError,
onDone: () => completer.complete());
......
......@@ -50,8 +50,8 @@ class AnalysisDriver {
}
List<AnalysisErrorDescription> analyze(Iterable<File> files) {
List<AnalysisErrorInfo> infos = _analyze(files);
List<AnalysisErrorDescription> errors = <AnalysisErrorDescription>[];
final List<AnalysisErrorInfo> infos = _analyze(files);
final List<AnalysisErrorDescription> errors = <AnalysisErrorDescription>[];
for (AnalysisErrorInfo info in infos) {
for (AnalysisError error in info.errors) {
if (!_isFiltered(error))
......@@ -65,17 +65,17 @@ class AnalysisDriver {
context = AnalysisEngine.instance.createAnalysisContext();
_processAnalysisOptions();
context.analysisOptions = options;
PackageInfo packageInfo = new PackageInfo(options.packageMap);
List<UriResolver> resolvers = _getResolvers(context, packageInfo.asMap());
final PackageInfo packageInfo = new PackageInfo(options.packageMap);
final List<UriResolver> resolvers = _getResolvers(context, packageInfo.asMap());
context.sourceFactory =
new SourceFactory(resolvers, packageInfo.asPackages());
List<Source> sources = <Source>[];
ChangeSet changeSet = new ChangeSet();
final List<Source> sources = <Source>[];
final ChangeSet changeSet = new ChangeSet();
for (File file in files) {
JavaFile sourceFile = new JavaFile(fs.path.normalize(file.absolute.path));
final JavaFile sourceFile = new JavaFile(fs.path.normalize(file.absolute.path));
Source source = new FileBasedSource(sourceFile, sourceFile.toURI());
Uri uri = context.sourceFactory.restoreUri(source);
final Uri uri = context.sourceFactory.restoreUri(source);
if (uri != null) {
source = new FileBasedSource(sourceFile, uri);
}
......@@ -84,7 +84,7 @@ class AnalysisDriver {
}
context.applyChanges(changeSet);
List<AnalysisErrorInfo> infos = <AnalysisErrorInfo>[];
final List<AnalysisErrorInfo> infos = <AnalysisErrorInfo>[];
for (Source source in sources) {
context.computeErrors(source);
infos.add(context.getErrors(source));
......@@ -98,13 +98,13 @@ class AnalysisDriver {
Map<String, List<file_system.Folder>> packageMap) {
// Create our list of resolvers.
List<UriResolver> resolvers = <UriResolver>[];
final List<UriResolver> resolvers = <UriResolver>[];
// Look for an embedder.
EmbedderYamlLocator locator = new EmbedderYamlLocator(packageMap);
final EmbedderYamlLocator locator = new EmbedderYamlLocator(packageMap);
if (locator.embedderYamls.isNotEmpty) {
// Create and configure an embedded SDK.
EmbedderSdk sdk = new EmbedderSdk(PhysicalResourceProvider.INSTANCE, locator.embedderYamls);
final EmbedderSdk sdk = new EmbedderSdk(PhysicalResourceProvider.INSTANCE, locator.embedderYamls);
// Fail fast if no URI mappings are found.
assert(sdk.libraryMap.size() > 0);
sdk.analysisOptions = context.analysisOptions;
......@@ -112,7 +112,7 @@ class AnalysisDriver {
resolvers.add(new DartUriResolver(sdk));
} else {
// Fall back to a standard SDK if no embedder is found.
FolderBasedDartSdk sdk = new FolderBasedDartSdk(resourceProvider,
final FolderBasedDartSdk sdk = new FolderBasedDartSdk(resourceProvider,
PhysicalResourceProvider.INSTANCE.getFolder(sdkDir));
sdk.analysisOptions = context.analysisOptions;
......@@ -120,11 +120,11 @@ class AnalysisDriver {
}
if (options.packageRootPath != null) {
ContextBuilderOptions builderOptions = new ContextBuilderOptions();
final ContextBuilderOptions builderOptions = new ContextBuilderOptions();
builderOptions.defaultPackagesDirectoryPath = options.packageRootPath;
ContextBuilder builder = new ContextBuilder(resourceProvider, null, null,
final ContextBuilder builder = new ContextBuilder(resourceProvider, null, null,
options: builderOptions);
PackageMapUriResolver packageUriResolver = new PackageMapUriResolver(resourceProvider,
final PackageMapUriResolver packageUriResolver = new PackageMapUriResolver(resourceProvider,
builder.convertPackagesToMap(builder.createPackageMap('')));
resolvers.add(packageUriResolver);
......@@ -135,17 +135,17 @@ class AnalysisDriver {
}
bool _isFiltered(AnalysisError error) {
ErrorProcessor processor = ErrorProcessor.getProcessor(context.analysisOptions, error);
final ErrorProcessor processor = ErrorProcessor.getProcessor(context.analysisOptions, error);
// Filtered errors are processed to a severity of `null`.
return processor != null && processor.severity == null;
}
void _processAnalysisOptions() {
String optionsPath = options.analysisOptionsFile;
final String optionsPath = options.analysisOptionsFile;
if (optionsPath != null) {
file_system.File file =
final file_system.File file =
PhysicalResourceProvider.INSTANCE.getFile(optionsPath);
Map<Object, Object> optionMap =
final Map<Object, Object> optionMap =
analysisOptionsProvider.getOptionsFromFile(file);
if (optionMap != null)
applyToAnalysisOptions(options, optionMap);
......@@ -153,9 +153,9 @@ class AnalysisDriver {
}
void _processPlugins() {
List<Plugin> plugins = <Plugin>[];
final List<Plugin> plugins = <Plugin>[];
plugins.addAll(AnalysisEngine.instance.requiredPlugins);
ExtensionManager manager = new ExtensionManager();
final ExtensionManager manager = new ExtensionManager();
manager.processPlugins(plugins);
linter.registerLintRules();
}
......@@ -181,7 +181,7 @@ class AnalysisErrorDescription {
ErrorCode get errorCode => error.errorCode;
String get errorType {
ErrorSeverity severity = errorCode.errorSeverity;
final ErrorSeverity severity = errorCode.errorSeverity;
if (severity == ErrorSeverity.INFO) {
if (errorCode.type == ErrorType.HINT || errorCode.type == ErrorType.LINT)
return errorCode.type.displayName;
......@@ -231,9 +231,9 @@ class DriverOptions extends AnalysisOptionsImpl {
class PackageInfo {
PackageInfo(Map<String, String> packageMap) {
Map<String, Uri> packages = new HashMap<String, Uri>();
final Map<String, Uri> packages = new HashMap<String, Uri>();
for (String package in packageMap.keys) {
String path = packageMap[package];
final String path = packageMap[package];
packages[package] = new Uri.directory(path);
_map[package] = <file_system.Folder>[
PhysicalResourceProvider.INSTANCE.getFolder(path)
......
......@@ -35,7 +35,7 @@ class DartDependencySetBuilder {
mainScriptPath
];
String output = runSyncAndThrowStdErrOnError(args);
final String output = runSyncAndThrowStdErrOnError(args);
return new Set<String>.from(LineSplitter.split(output));
}
......@@ -65,8 +65,8 @@ class _GenSnapshotDartDependencySetBuilder implements DartDependencySetBuilder {
assert(fs.path.isAbsolute(this.projectRootPath));
// TODO(goderbauer): Implement --print-deps in gen_snapshot so we don't have to parse the Makefile
Directory tempDir = fs.systemTempDirectory.createTempSync('dart_dependency_set_builder_');
String depfilePath = fs.path.join(tempDir.path, 'snapshot_blob.bin.d');
final Directory tempDir = fs.systemTempDirectory.createTempSync('dart_dependency_set_builder_');
final String depfilePath = fs.path.join(tempDir.path, 'snapshot_blob.bin.d');
final List<String> args = <String>[
snapshotterPath,
......@@ -84,14 +84,14 @@ class _GenSnapshotDartDependencySetBuilder implements DartDependencySetBuilder {
String output = fs.file(depfilePath).readAsStringSync();
tempDir.deleteSync(recursive: true);
int splitIndex = output.indexOf(':');
final int splitIndex = output.indexOf(':');
if (splitIndex == -1)
throw new Exception('Unexpected output $output');
output = output.substring(splitIndex + 1);
// Note: next line means we cannot process anything with spaces in the path
// because Makefiles don't support spaces in paths :(
List<String> depsList = output.trim().split(' ');
final List<String> depsList = output.trim().split(' ');
return new Set<String>.from(depsList);
}
}
......@@ -9,7 +9,7 @@ import '../base/file_system.dart';
const String kPackagesFileName = '.packages';
Map<String, Uri> _parse(String packagesPath) {
List<int> source = fs.file(packagesPath).readAsBytesSync();
final List<int> source = fs.file(packagesPath).readAsBytesSync();
return packages_file.parse(source, new Uri.file(packagesPath));
}
......@@ -42,10 +42,10 @@ class PackageMap {
/// Returns the path to [packageUri].
String pathForPackage(Uri packageUri) {
assert(packageUri.scheme == 'package');
List<String> pathSegments = packageUri.pathSegments.toList();
String packageName = pathSegments.removeAt(0);
Uri packageBase = map[packageName];
String packageRelativePath = fs.path.joinAll(pathSegments);
final List<String> pathSegments = packageUri.pathSegments.toList();
final String packageName = pathSegments.removeAt(0);
final Uri packageBase = map[packageName];
final String packageRelativePath = fs.path.joinAll(pathSegments);
return packageBase.resolve(packageRelativePath).path;
}
......@@ -53,7 +53,7 @@ class PackageMap {
if (fs.isFileSync(packagesPath))
return null;
String message = '$packagesPath does not exist.';
String pubspecPath = fs.path.absolute(fs.path.dirname(packagesPath), 'pubspec.yaml');
final String pubspecPath = fs.path.absolute(fs.path.dirname(packagesPath), 'pubspec.yaml');
if (fs.isFileSync(pubspecPath))
message += '\nDid you run "flutter packages get" in this directory?';
else
......
......@@ -15,10 +15,10 @@ import 'sdk.dart';
bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) {
if (!dotPackages.existsSync())
return true;
DateTime dotPackagesLastModified = dotPackages.lastModifiedSync();
final DateTime dotPackagesLastModified = dotPackages.lastModifiedSync();
if (pubSpecYaml.lastModifiedSync().isAfter(dotPackagesLastModified))
return true;
File flutterToolsStamp = Cache.instance.getStampFileFor('flutter_tools');
final File flutterToolsStamp = Cache.instance.getStampFileFor('flutter_tools');
if (flutterToolsStamp.existsSync() &&
flutterToolsStamp.lastModifiedSync().isAfter(dotPackagesLastModified))
return true;
......@@ -34,8 +34,8 @@ Future<Null> pubGet({
if (directory == null)
directory = fs.currentDirectory.path;
File pubSpecYaml = fs.file(fs.path.join(directory, 'pubspec.yaml'));
File dotPackages = fs.file(fs.path.join(directory, '.packages'));
final File pubSpecYaml = fs.file(fs.path.join(directory, 'pubspec.yaml'));
final File dotPackages = fs.file(fs.path.join(directory, '.packages'));
if (!pubSpecYaml.existsSync()) {
if (!skipIfAbsent)
......@@ -44,10 +44,10 @@ Future<Null> pubGet({
}
if (!checkLastModified || _shouldRunPubGet(pubSpecYaml: pubSpecYaml, dotPackages: dotPackages)) {
String command = upgrade ? 'upgrade' : 'get';
Status status = logger.startProgress("Running 'flutter packages $command' in ${fs.path.basename(directory)}...",
final String command = upgrade ? 'upgrade' : 'get';
final Status status = logger.startProgress("Running 'flutter packages $command' in ${fs.path.basename(directory)}...",
expectSlowOperation: true);
int code = await runCommandAndStreamOutput(
final int code = await runCommandAndStreamOutput(
<String>[sdkBinaryName('pub'), '--verbosity=warning', command, '--no-packages-dir', '--no-precompile'],
workingDirectory: directory,
mapFunction: _filterOverrideWarnings,
......
......@@ -34,8 +34,8 @@ class DependencyChecker {
// Check all dependency modification times.
for (String path in _dependencies) {
File file = fs.file(path);
FileStat stat = file.statSync();
final File file = fs.file(path);
final FileStat stat = file.statSync();
if (stat.type == FileSystemEntityType.NOT_FOUND) {
printTrace('DependencyChecker: Error stating $path.');
return true;
......
......@@ -72,8 +72,8 @@ class DevFSFileContent extends DevFSContent {
_fileStat = file.statSync();
if (_fileStat.type == FileSystemEntityType.LINK) {
// Resolve, stat, and maybe cache the symlink target.
String resolved = file.resolveSymbolicLinksSync();
FileSystemEntity linkTarget = fs.file(resolved);
final String resolved = file.resolveSymbolicLinksSync();
final FileSystemEntity linkTarget = fs.file(resolved);
// Stat the link target.
_fileStat = linkTarget.statSync();
if (devFSConfig.cacheSymlinks) {
......@@ -84,7 +84,7 @@ class DevFSFileContent extends DevFSContent {
@override
bool get isModified {
FileStat _oldFileStat = _fileStat;
final FileStat _oldFileStat = _fileStat;
_stat();
return _oldFileStat == null || _fileStat.modified.isAfter(_oldFileStat.modified);
}
......@@ -121,7 +121,7 @@ class DevFSByteContent extends DevFSContent {
/// Return `true` only once so that the content is written to the device only once.
@override
bool get isModified {
bool modified = _isModified;
final bool modified = _isModified;
_isModified = false;
return modified;
}
......@@ -173,7 +173,7 @@ class ServiceProtocolDevFSOperations implements DevFSOperations {
@override
Future<Uri> create(String fsName) async {
Map<String, dynamic> response = await vmService.vm.createDevFS(fsName);
final Map<String, dynamic> response = await vmService.vm.createDevFS(fsName);
return Uri.parse(response['uri']);
}
......@@ -193,7 +193,7 @@ class ServiceProtocolDevFSOperations implements DevFSOperations {
} catch (e) {
return e;
}
String fileContents = BASE64.encode(bytes);
final String fileContents = BASE64.encode(bytes);
try {
return await vmService.vm.invokeRpcRaw(
'_writeDevFSFile',
......@@ -251,8 +251,8 @@ class _DevFSHttpWriter {
// Finished.
break;
}
Uri deviceUri = _outstanding.keys.first;
DevFSContent content = _outstanding.remove(deviceUri);
final Uri deviceUri = _outstanding.keys.first;
final DevFSContent content = _outstanding.remove(deviceUri);
_scheduleWrite(deviceUri, content, progressReporter);
_inFlight++;
}
......@@ -265,15 +265,15 @@ class _DevFSHttpWriter {
int retry = 0,
]) async {
try {
HttpClientRequest request = await _client.putUrl(httpAddress);
final HttpClientRequest request = await _client.putUrl(httpAddress);
request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
request.headers.add('dev_fs_name', fsName);
// TODO(goderbauer): transfer real Uri (instead of file path) when remote end supports it
request.headers.add('dev_fs_path_b64',
BASE64.encode(UTF8.encode(deviceUri.toFilePath(windows: false))));
Stream<List<int>> contents = content.contentsAsCompressedStream();
final Stream<List<int>> contents = content.contentsAsCompressedStream();
await request.addStream(contents);
HttpClientResponse response = await request.close();
final HttpClientResponse response = await request.close();
await response.drain<Null>();
} catch (e) {
if (retry < kMaxRetries) {
......@@ -375,17 +375,17 @@ class DevFS {
// Handle deletions.
printTrace('Scanning for deleted files');
String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory());
final String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory());
final List<Uri> toRemove = new List<Uri>();
_entries.forEach((Uri deviceUri, DevFSContent content) {
if (!content._exists) {
Future<Map<String, dynamic>> operation =
final Future<Map<String, dynamic>> operation =
_operations.deleteFile(fsName, deviceUri);
if (operation != null)
_pendingOperations.add(operation);
toRemove.add(deviceUri);
if (deviceUri.path.startsWith(assetBuildDirPrefix)) {
String archivePath = deviceUri.path.substring(assetBuildDirPrefix.length);
final String archivePath = deviceUri.path.substring(assetBuildDirPrefix.length);
assetPathsToEvict.add(archivePath);
}
}
......@@ -399,7 +399,7 @@ class DevFS {
// Update modified files
int numBytes = 0;
Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{};
final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{};
_entries.forEach((Uri deviceUri, DevFSContent content) {
String archivePath;
if (deviceUri.path.startsWith(assetBuildDirPrefix))
......@@ -423,7 +423,7 @@ class DevFS {
} else {
// Make service protocol requests for each.
dirtyEntries.forEach((Uri deviceUri, DevFSContent content) {
Future<Map<String, dynamic>> operation =
final Future<Map<String, dynamic>> operation =
_operations.writeFile(fsName, deviceUri, content);
if (operation != null)
_pendingOperations.add(operation);
......@@ -449,7 +449,7 @@ class DevFS {
}
void _scanFile(Uri deviceUri, FileSystemEntity file) {
DevFSContent content = _entries.putIfAbsent(deviceUri, () => new DevFSFileContent(file));
final DevFSContent content = _entries.putIfAbsent(deviceUri, () => new DevFSFileContent(file));
content._exists = true;
}
......@@ -463,7 +463,7 @@ class DevFS {
}
bool _shouldIgnore(Uri deviceUri) {
List<String> ignoredUriPrefixes = <String>['android/',
final List<String> ignoredUriPrefixes = <String>['android/',
_asUriPath(getBuildDirectory()),
'ios/',
'.pub/'];
......@@ -480,7 +480,7 @@ class DevFS {
bool ignoreDotFiles: true,
Set<String> fileFilter}) async {
if (directoryUriOnDevice == null) {
String relativeRootPath = fs.path.relative(directory.path, from: rootDirectory.path);
final String relativeRootPath = fs.path.relative(directory.path, from: rootDirectory.path);
if (relativeRootPath == '.') {
directoryUriOnDevice = new Uri();
} else {
......@@ -488,7 +488,7 @@ class DevFS {
}
}
try {
Stream<FileSystemEntity> files =
final Stream<FileSystemEntity> files =
directory.list(recursive: recursive, followLinks: false);
await for (FileSystemEntity file in files) {
if (!devFSConfig.noDirectorySymlinks && (file is Link)) {
......@@ -532,12 +532,12 @@ class DevFS {
Future<Null> _scanPackages(Set<String> fileFilter) async {
StringBuffer sb;
PackageMap packageMap = new PackageMap(_packagesFilePath);
final PackageMap packageMap = new PackageMap(_packagesFilePath);
for (String packageName in packageMap.map.keys) {
Uri packageUri = packageMap.map[packageName];
String packagePath = packageUri.toFilePath();
Directory packageDirectory = fs.directory(packageUri);
final Uri packageUri = packageMap.map[packageName];
final String packagePath = packageUri.toFilePath();
final Directory packageDirectory = fs.directory(packageUri);
Uri directoryUriOnDevice = fs.path.toUri(fs.path.join('packages', packageName) + fs.path.separator);
bool packageExists;
......@@ -560,7 +560,7 @@ class DevFS {
}
}
if (sb != null) {
DevFSContent content = _entries[fs.path.toUri('.packages')];
final DevFSContent content = _entries[fs.path.toUri('.packages')];
if (content is DevFSStringContent && content.string == sb.toString()) {
content._exists = true;
return;
......
......@@ -42,8 +42,8 @@ class DeviceManager {
/// This does a case insentitive compare with [deviceId].
Future<List<Device>> getDevicesById(String deviceId) async {
deviceId = deviceId.toLowerCase();
List<Device> devices = await getAllConnectedDevices();
Device device = devices.firstWhere(
final List<Device> devices = await getAllConnectedDevices();
final Device device = devices.firstWhere(
(Device device) =>
device.id.toLowerCase() == deviceId ||
device.name.toLowerCase() == deviceId,
......@@ -250,11 +250,11 @@ abstract class Device {
return <String>[];
// Extract device information
List<List<String>> table = <List<String>>[];
final List<List<String>> table = <List<String>>[];
for (Device device in devices) {
String supportIndicator = device.isSupported() ? '' : ' (unsupported)';
if (device.isLocalEmulator) {
String type = device.platform == TargetPlatform.ios ? 'simulator' : 'emulator';
final String type = device.platform == TargetPlatform.ios ? 'simulator' : 'emulator';
supportIndicator += ' ($type)';
}
table.add(<String>[
......@@ -266,7 +266,7 @@ abstract class Device {
}
// Calculate column widths
List<int> indices = new List<int>.generate(table[0].length - 1, (int i) => i);
final List<int> indices = new List<int>.generate(table[0].length - 1, (int i) => i);
List<int> widths = indices.map((int i) => 0).toList();
for (List<String> row in table) {
widths = indices.map((int i) => math.max(widths[i], row[i].length)).toList();
......@@ -336,7 +336,7 @@ class LaunchResult {
@override
String toString() {
StringBuffer buf = new StringBuffer('started=$started');
final StringBuffer buf = new StringBuffer('started=$started');
if (observatoryUri != null)
buf.write(', observatory=$observatoryUri');
if (diagnosticUri != null)
......
......@@ -28,7 +28,7 @@ const Map<String, String> _osNames = const <String, String>{
};
String osName() {
String os = platform.operatingSystem;
final String os = platform.operatingSystem;
return _osNames.containsKey(os) ? _osNames[os] : os;
}
......@@ -59,7 +59,7 @@ class Doctor {
if (_iosWorkflow.appliesToHostPlatform)
_validators.add(_iosWorkflow);
List<DoctorValidator> ideValidators = <DoctorValidator>[];
final List<DoctorValidator> ideValidators = <DoctorValidator>[];
ideValidators.addAll(AndroidStudioValidator.allValidators);
ideValidators.addAll(IntelliJValidator.installedValidators);
if (ideValidators.isNotEmpty)
......@@ -82,12 +82,12 @@ class Doctor {
}
Future<String> get summaryText async {
StringBuffer buffer = new StringBuffer();
final StringBuffer buffer = new StringBuffer();
bool allGood = true;
for (DoctorValidator validator in validators) {
ValidationResult result = await validator.validate();
final ValidationResult result = await validator.validate();
buffer.write('${result.leadingBox} ${validator.title} is ');
if (result.type == ValidationType.missing)
buffer.write('not installed.');
......@@ -123,7 +123,7 @@ class Doctor {
printStatus('');
firstLine = false;
ValidationResult result = await validator.validate();
final ValidationResult result = await validator.validate();
if (result.type == ValidationType.missing)
doctorResult = false;
......@@ -134,7 +134,7 @@ class Doctor {
printStatus('${result.leadingBox} ${validator.title}');
for (ValidationMessage message in result.messages) {
String text = message.message.replaceAll('\n', '\n ');
final String text = message.message.replaceAll('\n', '\n ');
if (message.isError) {
printStatus(' ✗ $text', emphasis: true);
} else {
......@@ -211,10 +211,10 @@ class _FlutterValidator extends DoctorValidator {
@override
Future<ValidationResult> validate() async {
List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType valid = ValidationType.installed;
final List<ValidationMessage> messages = <ValidationMessage>[];
final ValidationType valid = ValidationType.installed;
FlutterVersion version = FlutterVersion.getVersion();
final FlutterVersion version = FlutterVersion.getVersion();
messages.add(new ValidationMessage('Flutter at ${version.flutterRoot}'));
messages.add(new ValidationMessage(
......@@ -262,7 +262,7 @@ abstract class IntelliJValidator extends DoctorValidator {
@override
Future<ValidationResult> validate() async {
List<ValidationMessage> messages = <ValidationMessage>[];
final List<ValidationMessage> messages = <ValidationMessage>[];
int installCount = 0;
......@@ -300,25 +300,25 @@ abstract class IntelliJValidator extends DoctorValidator {
));
return false;
}
String version = _readPackageVersion(packageName);
final String version = _readPackageVersion(packageName);
messages.add(new ValidationMessage('$title plugin '
'${version != null ? "version $version" : "installed"}'));
return true;
}
String _readPackageVersion(String packageName) {
String jarPath = packageName.endsWith('.jar')
final String jarPath = packageName.endsWith('.jar')
? fs.path.join(pluginsPath, packageName)
: fs.path.join(pluginsPath, packageName, 'lib', '$packageName.jar');
// TODO(danrubel) look for a better way to extract a single 2K file from the zip
// rather than reading the entire file into memory.
try {
Archive archive = new ZipDecoder().decodeBytes(fs.file(jarPath).readAsBytesSync());
ArchiveFile file = archive.findFile('META-INF/plugin.xml');
String content = UTF8.decode(file.content);
String versionStartTag = '<version>';
int start = content.indexOf(versionStartTag);
int end = content.indexOf('</version>', start);
final Archive archive = new ZipDecoder().decodeBytes(fs.file(jarPath).readAsBytesSync());
final ArchiveFile file = archive.findFile('META-INF/plugin.xml');
final String content = UTF8.decode(file.content);
final String versionStartTag = '<version>';
final int start = content.indexOf(versionStartTag);
final int end = content.indexOf('</version>', start);
return content.substring(start + versionStartTag.length, end);
} catch (_) {
return null;
......@@ -326,7 +326,7 @@ abstract class IntelliJValidator extends DoctorValidator {
}
bool hasPackage(String packageName) {
String packagePath = fs.path.join(pluginsPath, packageName);
final String packagePath = fs.path.join(pluginsPath, packageName);
if (packageName.endsWith('.jar'))
return fs.isFileSync(packagePath);
return fs.isDirectorySync(packagePath);
......@@ -345,14 +345,14 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator {
String pluginsPath;
static Iterable<DoctorValidator> get installed {
List<DoctorValidator> validators = <DoctorValidator>[];
final List<DoctorValidator> validators = <DoctorValidator>[];
if (homeDirPath == null) return validators;
void addValidator(String title, String version, String installPath, String pluginsPath) {
IntelliJValidatorOnLinuxAndWindows validator =
final IntelliJValidatorOnLinuxAndWindows validator =
new IntelliJValidatorOnLinuxAndWindows(title, version, installPath, pluginsPath);
for (int index = 0; index < validators.length; ++index) {
DoctorValidator other = validators[index];
final DoctorValidator other = validators[index];
if (other is IntelliJValidatorOnLinuxAndWindows && validator.installPath == other.installPath) {
if (validator.version.compareTo(other.version) > 0)
validators[index] = validator;
......@@ -364,10 +364,10 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator {
for (FileSystemEntity dir in fs.directory(homeDirPath).listSync()) {
if (dir is Directory) {
String name = fs.path.basename(dir.path);
final String name = fs.path.basename(dir.path);
IntelliJValidator._idToTitle.forEach((String id, String title) {
if (name.startsWith('.$id')) {
String version = name.substring(id.length + 1);
final String version = name.substring(id.length + 1);
String installPath;
try {
installPath = fs.file(fs.path.join(dir.path, 'system', '.home')).readAsStringSync();
......@@ -375,7 +375,7 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator {
// ignored
}
if (installPath != null && fs.isDirectorySync(installPath)) {
String pluginsPath = fs.path.join(dir.path, 'config', 'plugins');
final String pluginsPath = fs.path.join(dir.path, 'config', 'plugins');
addValidator(title, version, installPath, pluginsPath);
}
}
......@@ -400,21 +400,21 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
};
static Iterable<DoctorValidator> get installed {
List<DoctorValidator> validators = <DoctorValidator>[];
List<String> installPaths = <String>['/Applications', fs.path.join(homeDirPath, 'Applications')];
final List<DoctorValidator> validators = <DoctorValidator>[];
final List<String> installPaths = <String>['/Applications', fs.path.join(homeDirPath, 'Applications')];
void checkForIntelliJ(Directory dir) {
String name = fs.path.basename(dir.path);
final String name = fs.path.basename(dir.path);
_dirNameToId.forEach((String dirName, String id) {
if (name == dirName) {
String title = IntelliJValidator._idToTitle[id];
final String title = IntelliJValidator._idToTitle[id];
validators.add(new IntelliJValidatorOnMac(title, id, dir.path));
}
});
}
try {
Iterable<FileSystemEntity> installDirs = installPaths
final Iterable<FileSystemEntity> installDirs = installPaths
.map((String installPath) => fs.directory(installPath).listSync())
.expand((List<FileSystemEntity> mappedDirs) => mappedDirs)
.where((FileSystemEntity mappedDir) => mappedDir is Directory);
......@@ -444,7 +444,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
@override
String get version {
if (_version == null) {
String plistFile = fs.path.join(installPath, 'Contents', 'Info.plist');
final String plistFile = fs.path.join(installPath, 'Contents', 'Info.plist');
_version = getValueFromFile(plistFile, kCFBundleShortVersionStringKey) ?? 'unknown';
}
return _version;
......@@ -453,9 +453,9 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
@override
String get pluginsPath {
List<String> split = version.split('.');
String major = split[0];
String minor = split[1];
final List<String> split = version.split('.');
final String major = split[0];
final String minor = split[1];
return fs.path.join(homeDirPath, 'Library', 'Application Support', '$id$major.$minor');
}
}
......@@ -465,7 +465,7 @@ class DeviceValidator extends DoctorValidator {
@override
Future<ValidationResult> validate() async {
List<Device> devices = await deviceManager.getAllConnectedDevices();
final List<Device> devices = await deviceManager.getAllConnectedDevices();
List<ValidationMessage> messages;
if (devices.isEmpty) {
messages = <ValidationMessage>[new ValidationMessage('None')];
......
......@@ -59,7 +59,7 @@ Future<int> _createScriptSnapshotWithSkySnapshot({
assert(mainPath != null);
assert(snapshotPath != null);
assert(packages != null);
String snapshotterPath = artifacts.getArtifactPath(Artifact.skySnapshot);
final String snapshotterPath = artifacts.getArtifactPath(Artifact.skySnapshot);
final List<String> args = <String>[
snapshotterPath,
......@@ -83,9 +83,9 @@ Future<int> _creteScriptSnapshotWithGenSnapshot({
assert(mainPath != null);
assert(snapshotPath != null);
assert(packages != null);
String snapshotterPath = artifacts.getArtifactPath(Artifact.genSnapshot);
String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData);
String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData);
final String snapshotterPath = artifacts.getArtifactPath(Artifact.genSnapshot);
final String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData);
final String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData);
final List<String> args = <String>[
snapshotterPath,
......@@ -149,7 +149,7 @@ Future<Null> build({
if (kernelContent != null) {
// TODO(danrubel) in the future, call the VM to generate this file
kernelFile = fs.file(kernelPath);
IOSink sink = kernelFile.openWrite();
final IOSink sink = kernelFile.openWrite();
await sink.addStream(kernelContent.contentsAsStream());
sink.close();
}
......@@ -158,7 +158,7 @@ Future<Null> build({
// In a precompiled snapshot, the instruction buffer contains script
// content equivalents
int result = await createSnapshot(
final int result = await createSnapshot(
mainPath: mainPath,
snapshotPath: snapshotPath,
depfilePath: depfilePath,
......@@ -201,8 +201,8 @@ Future<Null> assemble({
printTrace('Building $outputPath');
// Build the asset bundle.
AssetBundle assetBundle = new AssetBundle();
int result = await assetBundle.build(
final AssetBundle assetBundle = new AssetBundle();
final int result = await assetBundle.build(
manifestPath: manifestPath,
workingDirPath: workingDirPath,
packagesPath: packagesPath,
......@@ -213,7 +213,7 @@ Future<Null> assemble({
if (result != 0)
throwToolExit('Error building $outputPath: $result', exitCode: result);
ZipBuilder zipBuilder = new ZipBuilder();
final ZipBuilder zipBuilder = new ZipBuilder();
// Add all entries from the asset bundle.
zipBuilder.entries.addAll(assetBundle.entries);
......
......@@ -97,18 +97,18 @@ class IOSDevice extends Device {
if (!doctor.iosWorkflow.hasIDeviceId)
return <IOSDevice>[];
List<IOSDevice> devices = <IOSDevice>[];
final List<IOSDevice> devices = <IOSDevice>[];
for (String id in _getAttachedDeviceIDs(mockIOS)) {
String name = IOSDevice._getDeviceInfo(id, 'DeviceName', mockIOS);
final String name = IOSDevice._getDeviceInfo(id, 'DeviceName', mockIOS);
devices.add(new IOSDevice(id, name: name));
}
return devices;
}
static Iterable<String> _getAttachedDeviceIDs([IOSDevice mockIOS]) {
String listerPath = (mockIOS != null) ? mockIOS.listerPath : _checkForCommand('idevice_id');
final String listerPath = (mockIOS != null) ? mockIOS.listerPath : _checkForCommand('idevice_id');
try {
String output = runSync(<String>[listerPath, '-l']);
final String output = runSync(<String>[listerPath, '-l']);
return output.trim().split('\n').where((String s) => s != null && s.isNotEmpty);
} catch (e) {
return <String>[];
......@@ -116,7 +116,7 @@ class IOSDevice extends Device {
}
static String _getDeviceInfo(String deviceID, String infoKey, [IOSDevice mockIOS]) {
String informerPath = (mockIOS != null)
final String informerPath = (mockIOS != null)
? mockIOS.informerPath
: _checkForCommand('ideviceinfo');
return runSync(<String>[informerPath, '-k', infoKey, '-u', deviceID]).trim();
......@@ -142,7 +142,7 @@ class IOSDevice extends Device {
@override
bool isAppInstalled(ApplicationPackage app) {
try {
String apps = runCheckedSync(<String>[installerPath, '--list-apps']);
final String apps = runCheckedSync(<String>[installerPath, '--list-apps']);
if (new RegExp(app.id, multiLine: true).hasMatch(apps)) {
return true;
}
......@@ -157,8 +157,8 @@ class IOSDevice extends Device {
@override
bool installApp(ApplicationPackage app) {
IOSApp iosApp = app;
Directory bundle = fs.directory(iosApp.deviceBundlePath);
final IOSApp iosApp = app;
final Directory bundle = fs.directory(iosApp.deviceBundlePath);
if (!bundle.existsSync()) {
printError("Could not find application bundle at ${bundle.path}; have you run 'flutter build ios'?");
return false;
......@@ -203,7 +203,7 @@ class IOSDevice extends Device {
printTrace('Building ${app.name} for $id');
// Step 1: Build the precompiled/DBC application if necessary.
XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: mode, target: mainPath, buildForDevice: true);
final XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: mode, target: mainPath, buildForDevice: true);
if (!buildResult.success) {
printError('Could not build the precompiled application for the device.');
await diagnoseXcodeBuildFailure(buildResult);
......@@ -216,15 +216,15 @@ class IOSDevice extends Device {
}
// Step 2: Check that the application exists at the specified path.
IOSApp iosApp = app;
Directory bundle = fs.directory(iosApp.deviceBundlePath);
final IOSApp iosApp = app;
final Directory bundle = fs.directory(iosApp.deviceBundlePath);
if (!bundle.existsSync()) {
printError('Could not find the built application bundle at ${bundle.path}.');
return new LaunchResult.failed();
}
// Step 3: Attempt to install the application on the device.
List<String> launchArguments = <String>["--enable-dart-profiling"];
final List<String> launchArguments = <String>["--enable-dart-profiling"];
if (debuggingOptions.startPaused)
launchArguments.add("--start-paused");
......@@ -240,7 +240,7 @@ class IOSDevice extends Device {
if (platformArgs['trace-startup'] ?? false)
launchArguments.add('--trace-startup');
List<String> launchCommand = <String>[
final List<String> launchCommand = <String>[
'/usr/bin/env',
'ios-deploy',
'--id',
......@@ -271,12 +271,12 @@ class IOSDevice extends Device {
// TODO(danrubel): The Android device class does something similar to this code below.
// The various Device subclasses should be refactored and common code moved into the superclass.
ProtocolDiscovery observatoryDiscovery = new ProtocolDiscovery.observatory(
final ProtocolDiscovery observatoryDiscovery = new ProtocolDiscovery.observatory(
getLogReader(app: app), portForwarder: portForwarder, hostPort: debuggingOptions.observatoryPort);
ProtocolDiscovery diagnosticDiscovery = new ProtocolDiscovery.diagnosticService(
final ProtocolDiscovery diagnosticDiscovery = new ProtocolDiscovery.diagnosticService(
getLogReader(app: app), portForwarder: portForwarder, hostPort: debuggingOptions.diagnosticPort);
Future<Uri> forwardObsUri = observatoryDiscovery.nextUri();
final Future<Uri> forwardObsUri = observatoryDiscovery.nextUri();
Future<Uri> forwardDiagUri;
if (debuggingOptions.buildMode == BuildMode.debug) {
forwardDiagUri = diagnosticDiscovery.nextUri();
......@@ -284,9 +284,9 @@ class IOSDevice extends Device {
forwardDiagUri = new Future<Uri>.value(null);
}
Future<int> launch = runCommandAndStreamOutput(launchCommand, trace: true);
final Future<int> launch = runCommandAndStreamOutput(launchCommand, trace: true);
List<Uri> uris = await launch.then<List<Uri>>((int result) async {
final List<Uri> uris = await launch.then<List<Uri>>((int result) async {
installationResult = result;
if (result != 0) {
......@@ -392,7 +392,7 @@ class _IOSDeviceLogReader extends DeviceLogReader {
//
// iOS 9 format: Runner[297] <Notice>:
// iOS 10 format: Runner(libsystem_asl.dylib)[297] <Notice>:
String appName = app == null ? '' : app.name.replaceAll('.app', '');
final String appName = app == null ? '' : app.name.replaceAll('.app', '');
_lineRegex = new RegExp(appName + r'(\(.*\))?\[[\d]+\] <[A-Za-z]+>: ');
}
......@@ -420,7 +420,7 @@ class _IOSDeviceLogReader extends DeviceLogReader {
}
void _onLine(String line) {
Match match = _lineRegex.firstMatch(line);
final Match match = _lineRegex.firstMatch(line);
if (match != null) {
// Only display the log line after the initial device and executable information.
......@@ -451,14 +451,14 @@ class _IOSDevicePortForwarder extends DevicePortForwarder {
}
// Usage: iproxy LOCAL_TCP_PORT DEVICE_TCP_PORT UDID
Process process = await runCommand(<String>[
final Process process = await runCommand(<String>[
device.iproxyPath,
hostPort.toString(),
devicePort.toString(),
device.id,
]);
ForwardedPort forwardedPort = new ForwardedPort.withContext(hostPort,
final ForwardedPort forwardedPort = new ForwardedPort.withContext(hostPort,
devicePort, process);
printTrace("Forwarded port $forwardedPort");
......@@ -477,7 +477,7 @@ class _IOSDevicePortForwarder extends DevicePortForwarder {
printTrace("Unforwarding port $forwardedPort");
Process process = forwardedPort.context;
final Process process = forwardedPort.context;
if (process != null) {
processManager.killPid(process.pid);
......
......@@ -46,7 +46,7 @@ class IOSWorkflow extends DoctorValidator implements Workflow {
if (!hasIosDeploy)
return false;
try {
Version version = new Version.parse(iosDeployVersionText);
final Version version = new Version.parse(iosDeployVersionText);
return version >= new Version.parse(iosDeployMinimumVersion);
} on FormatException catch (_) {
return false;
......@@ -55,7 +55,7 @@ class IOSWorkflow extends DoctorValidator implements Workflow {
@override
Future<ValidationResult> validate() async {
List<ValidationMessage> messages = <ValidationMessage>[];
final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType xcodeStatus = ValidationType.missing;
ValidationType pythonStatus = ValidationType.missing;
ValidationType brewStatus = ValidationType.missing;
......@@ -143,7 +143,7 @@ class IOSWorkflow extends DoctorValidator implements Workflow {
} else {
// Check for compatibility between libimobiledevice and Xcode.
// TODO(cbracken) remove this check once libimobiledevice > 1.2.0 is released.
ProcessResult result = (await runAsync(<String>['idevice_id', '-l'])).processResult;
final ProcessResult result = (await runAsync(<String>['idevice_id', '-l'])).processResult;
if (result.exitCode == 0 && result.stdout.isNotEmpty && !exitsHappy(<String>['ideviceName'])) {
brewStatus = ValidationType.partial;
messages.add(new ValidationMessage.error(
......
......@@ -42,7 +42,7 @@ class Xcode {
} else {
try {
printTrace('xcrun clang');
ProcessResult result = processManager.runSync(<String>['/usr/bin/xcrun', 'clang']);
final ProcessResult result = processManager.runSync(<String>['/usr/bin/xcrun', 'clang']);
if (result.stdout != null && result.stdout.contains('license'))
_eulaSigned = false;
......@@ -88,8 +88,8 @@ class Xcode {
if (!xcodeVersionRegex.hasMatch(xcodeVersionText))
return false;
String version = xcodeVersionRegex.firstMatch(xcodeVersionText).group(1);
List<String> components = version.split('.');
final String version = xcodeVersionRegex.firstMatch(xcodeVersionText).group(1);
final List<String> components = version.split('.');
_xcodeMajorVersion = int.parse(components[0]);
_xcodeMinorVersion = components.length == 1 ? 0 : int.parse(components[1]);
......@@ -115,7 +115,7 @@ Future<XcodeBuildResult> buildXcodeProject({
bool buildForDevice,
bool codesign: true
}) async {
String flutterProjectPath = fs.currentDirectory.path;
final String flutterProjectPath = fs.currentDirectory.path;
updateXcodeGeneratedProperties(flutterProjectPath, mode, target);
if (!_checkXcodeVersion())
......@@ -126,7 +126,7 @@ Future<XcodeBuildResult> buildXcodeProject({
await _addServicesToBundle(fs.directory(app.appDirectory));
List<String> commands = <String>[
final List<String> commands = <String>[
'/usr/bin/env',
'xcrun',
'xcodebuild',
......@@ -136,7 +136,7 @@ Future<XcodeBuildResult> buildXcodeProject({
'ONLY_ACTIVE_ARCH=YES',
];
List<FileSystemEntity> contents = fs.directory(app.appDirectory).listSync();
final List<FileSystemEntity> contents = fs.directory(app.appDirectory).listSync();
for (FileSystemEntity entity in contents) {
if (fs.path.extension(entity.path) == '.xcworkspace') {
commands.addAll(<String>[
......@@ -164,7 +164,7 @@ Future<XcodeBuildResult> buildXcodeProject({
);
}
RunResult result = await runAsync(
final RunResult result = await runAsync(
commands,
workingDirectory: app.appDirectory,
allowReentrantFlutter: true
......@@ -192,8 +192,8 @@ Future<XcodeBuildResult> buildXcodeProject({
);
} else {
// Look for 'clean build/Release-iphoneos/Runner.app'.
RegExp regexp = new RegExp(r' clean (\S*\.app)$', multiLine: true);
Match match = regexp.firstMatch(result.stdout);
final RegExp regexp = new RegExp(r' clean (\S*\.app)$', multiLine: true);
final Match match = regexp.firstMatch(result.stdout);
String outputDir;
if (match != null)
outputDir = fs.path.join(app.appDirectory, match.group(1));
......@@ -202,9 +202,9 @@ Future<XcodeBuildResult> buildXcodeProject({
}
Future<Null> diagnoseXcodeBuildFailure(XcodeBuildResult result) async {
File plistFile = fs.file('ios/Runner/Info.plist');
final File plistFile = fs.file('ios/Runner/Info.plist');
if (plistFile.existsSync()) {
String plistContent = plistFile.readAsStringSync();
final String plistContent = plistFile.readAsStringSync();
if (plistContent.contains('com.yourcompany')) {
printError('');
printError('It appears that your application still contains the default signing identifier.');
......@@ -232,7 +232,7 @@ Future<Null> diagnoseXcodeBuildFailure(XcodeBuildResult result) async {
assert(result.xcodeBuildExecution.appDirectory != null);
if (result.xcodeBuildExecution.buildForPhysicalDevice &&
result.xcodeBuildExecution.buildCommands.contains('build')) {
RunResult checkBuildSettings = await runAsync(
final RunResult checkBuildSettings = await runAsync(
result.xcodeBuildExecution.buildCommands..add('-showBuildSettings'),
workingDirectory: result.xcodeBuildExecution.appDirectory,
allowReentrantFlutter: true
......@@ -302,8 +302,8 @@ bool _checkXcodeVersion() {
if (!platform.isMacOS)
return false;
try {
String version = runCheckedSync(<String>['xcodebuild', '-version']);
Match match = _xcodeVersionRegExp.firstMatch(version);
final String version = runCheckedSync(<String>['xcodebuild', '-version']);
final Match match = _xcodeVersionRegExp.firstMatch(version);
if (int.parse(match[1]) < 7) {
printError('Found "${match[0]}". $_xcodeRequirement');
return false;
......@@ -316,7 +316,7 @@ bool _checkXcodeVersion() {
}
Future<Null> _addServicesToBundle(Directory bundle) async {
List<Map<String, String>> services = <Map<String, String>>[];
final List<Map<String, String>> services = <Map<String, String>>[];
printTrace("Trying to resolve native pub services.");
// Step 1: Parse the service configuration yaml files present in the service
......@@ -325,12 +325,12 @@ Future<Null> _addServicesToBundle(Directory bundle) async {
printTrace("Found ${services.length} service definition(s).");
// Step 2: Copy framework dylibs to the correct spot for xcodebuild to pick up.
Directory frameworksDirectory = fs.directory(fs.path.join(bundle.path, "Frameworks"));
final Directory frameworksDirectory = fs.directory(fs.path.join(bundle.path, "Frameworks"));
await _copyServiceFrameworks(services, frameworksDirectory);
// Step 3: Copy the service definitions manifest at the correct spot for
// xcodebuild to pick up.
File manifestFile = fs.file(fs.path.join(bundle.path, "ServiceDefinitions.json"));
final File manifestFile = fs.file(fs.path.join(bundle.path, "ServiceDefinitions.json"));
_copyServiceDefinitionsManifest(services, manifestFile);
}
......@@ -338,8 +338,8 @@ Future<Null> _copyServiceFrameworks(List<Map<String, String>> services, Director
printTrace("Copying service frameworks to '${fs.path.absolute(frameworksDirectory.path)}'.");
frameworksDirectory.createSync(recursive: true);
for (Map<String, String> service in services) {
String dylibPath = await getServiceFromUrl(service['ios-framework'], service['root'], service['name']);
File dylib = fs.file(dylibPath);
final String dylibPath = await getServiceFromUrl(service['ios-framework'], service['root'], service['name']);
final File dylib = fs.file(dylibPath);
printTrace("Copying ${dylib.path} into bundle.");
if (!dylib.existsSync()) {
printError("The service dylib '${dylib.path}' does not exist.");
......@@ -352,12 +352,12 @@ Future<Null> _copyServiceFrameworks(List<Map<String, String>> services, Director
void _copyServiceDefinitionsManifest(List<Map<String, String>> services, File manifest) {
printTrace("Creating service definitions manifest at '${manifest.path}'");
List<Map<String, String>> jsonServices = services.map((Map<String, String> service) => <String, String>{
final List<Map<String, String>> jsonServices = services.map((Map<String, String> service) => <String, String>{
'name': service['name'],
// Since we have already moved it to the Frameworks directory. Strip away
// the directory and basenames.
'framework': fs.path.basenameWithoutExtension(service['ios-framework'])
}).toList();
Map<String, dynamic> json = <String, dynamic>{ 'services' : jsonServices };
final Map<String, dynamic> json = <String, dynamic>{ 'services' : jsonServices };
manifest.writeAsStringSync(JSON.encode(json), mode: FileMode.WRITE, flush: true);
}
......@@ -19,10 +19,10 @@ String getValueFromFile(String plistFilePath, String key) {
if (!fs.isFileSync(plistFilePath))
return null;
String normalizedPlistPath = fs.path.withoutExtension(fs.path.absolute(plistFilePath));
final String normalizedPlistPath = fs.path.withoutExtension(fs.path.absolute(plistFilePath));
try {
String value = runCheckedSync(<String>[
final String value = runCheckedSync(<String>[
'/usr/bin/defaults', 'read', normalizedPlistPath, key
]);
return value.isEmpty ? null : value;
......
......@@ -13,11 +13,11 @@ final RegExp _settingExpr = new RegExp(r'(\w+)\s*=\s*(\S+)');
final RegExp _varExpr = new RegExp(r'\$\((.*)\)');
void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String target) {
StringBuffer localsBuffer = new StringBuffer();
final StringBuffer localsBuffer = new StringBuffer();
localsBuffer.writeln('// This is a generated file; do not edit or check into version control.');
String flutterRoot = fs.path.normalize(Cache.flutterRoot);
final String flutterRoot = fs.path.normalize(Cache.flutterRoot);
localsBuffer.writeln('FLUTTER_ROOT=$flutterRoot');
// This holds because requiresProjectRoot is true for this command
......@@ -34,27 +34,27 @@ void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String t
localsBuffer.writeln('SYMROOT=\${SOURCE_ROOT}/../${getIosBuildDirectory()}');
String flutterFrameworkDir = fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, mode)));
final String flutterFrameworkDir = fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, mode)));
localsBuffer.writeln('FLUTTER_FRAMEWORK_DIR=$flutterFrameworkDir');
if (artifacts is LocalEngineArtifacts) {
LocalEngineArtifacts localEngineArtifacts = artifacts;
final LocalEngineArtifacts localEngineArtifacts = artifacts;
localsBuffer.writeln('LOCAL_ENGINE=${localEngineArtifacts.engineOutPath}');
}
File localsFile = fs.file(fs.path.join(projectPath, 'ios', 'Flutter', 'Generated.xcconfig'));
final File localsFile = fs.file(fs.path.join(projectPath, 'ios', 'Flutter', 'Generated.xcconfig'));
localsFile.createSync(recursive: true);
localsFile.writeAsStringSync(localsBuffer.toString());
}
Map<String, String> getXcodeBuildSettings(String xcodeProjPath, String target) {
String absProjPath = fs.path.absolute(xcodeProjPath);
String out = runCheckedSync(<String>[
final String absProjPath = fs.path.absolute(xcodeProjPath);
final String out = runCheckedSync(<String>[
'/usr/bin/xcodebuild', '-project', absProjPath, '-target', target, '-showBuildSettings'
]);
Map<String, String> settings = <String, String>{};
final Map<String, String> settings = <String, String>{};
for (String line in out.split('\n').where(_settingExpr.hasMatch)) {
Match match = _settingExpr.firstMatch(line);
final Match match = _settingExpr.firstMatch(line);
settings[match[1]] = match[2];
}
return settings;
......@@ -64,10 +64,10 @@ Map<String, String> getXcodeBuildSettings(String xcodeProjPath, String target) {
/// Substitutes variables in [str] with their values from the specified Xcode
/// project and target.
String substituteXcodeVariables(String str, String xcodeProjPath, String target) {
Iterable<Match> matches = _varExpr.allMatches(str);
final Iterable<Match> matches = _varExpr.allMatches(str);
if (matches.isEmpty)
return str;
Map<String, String> settings = getXcodeBuildSettings(xcodeProjPath, target);
final Map<String, String> settings = getXcodeBuildSettings(xcodeProjPath, target);
return str.replaceAllMapped(_varExpr, (Match m) => settings[m[1]] ?? m[0]);
}
......@@ -50,7 +50,7 @@ class ProtocolDiscovery {
/// The [Future] returned by this function will complete when the next service
/// Uri is found.
Future<Uri> nextUri() async {
Uri deviceUri = await _completer.future.timeout(
final Uri deviceUri = await _completer.future.timeout(
const Duration(seconds: 60), onTimeout: () {
throwToolExit('Timeout while attempting to retrieve Uri for $_serviceName');
}
......@@ -58,7 +58,7 @@ class ProtocolDiscovery {
printTrace('$_serviceName Uri on device: $deviceUri');
Uri hostUri;
if (portForwarder != null) {
int devicePort = deviceUri.port;
final int devicePort = deviceUri.port;
hostPort ??= await findPreferredPort(defaultHostPort);
hostPort = await portForwarder
.forward(devicePort, hostPort: hostPort)
......@@ -79,8 +79,8 @@ class ProtocolDiscovery {
void _onLine(String line) {
Uri uri;
String prefix = '$_serviceName listening on ';
int index = line.indexOf(prefix + 'http://');
final String prefix = '$_serviceName listening on ';
final int index = line.indexOf(prefix + 'http://');
if (index >= 0) {
try {
uri = Uri.parse(line.substring(index + prefix.length));
......
......@@ -83,14 +83,14 @@ class ColdRunner extends ResidentRunner {
if (package == null) {
String message = 'No application found for ${device.platform}.';
String hint = getMissingPackageHintForPlatform(device.platform);
final String hint = getMissingPackageHintForPlatform(device.platform);
if (hint != null)
message += '\n$hint';
printError(message);
return 1;
}
Stopwatch startTime = new Stopwatch()..start();
final Stopwatch startTime = new Stopwatch()..start();
Map<String, dynamic> platformArgs;
if (traceStartup != null)
......@@ -98,7 +98,7 @@ class ColdRunner extends ResidentRunner {
await startEchoingDeviceLog(package);
String modeName = getModeName(debuggingOptions.buildMode);
final String modeName = getModeName(debuggingOptions.buildMode);
if (mainPath == null) {
assert(prebuiltMode);
printStatus('Launching ${package.displayName} on ${device.name} in $modeName mode...');
......
This diff is collapsed.
......@@ -32,7 +32,7 @@ class CoverageCollector {
assert(process != null);
assert(port != null);
int pid = process.pid;
final int pid = process.pid;
int exitCode;
process.exitCode.then<Null>((int code) {
exitCode = code;
......@@ -68,12 +68,12 @@ class CoverageCollector {
if (_globalHitmap == null)
return null;
if (formatter == null) {
coverage.Resolver resolver = new coverage.Resolver(packagesPath: PackageMap.globalPackagesPath);
String packagePath = fs.currentDirectory.path;
List<String> reportOn = <String>[fs.path.join(packagePath, 'lib')];
final coverage.Resolver resolver = new coverage.Resolver(packagesPath: PackageMap.globalPackagesPath);
final String packagePath = fs.currentDirectory.path;
final List<String> reportOn = <String>[fs.path.join(packagePath, 'lib')];
formatter = new coverage.LcovFormatter(resolver, reportOn: reportOn, basePath: packagePath);
}
String result = await formatter.format(_globalHitmap);
final String result = await formatter.format(_globalHitmap);
_globalHitmap = null;
return result;
}
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment