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;
......
......@@ -56,13 +56,13 @@ class AndroidDevice extends Device {
if (_properties == null) {
_properties = <String, String>{};
List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']);
final List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']);
printTrace(propCommand.join(' '));
try {
// We pass an encoding of LATIN1 so that we don't try and interpret the
// `adb shell getprop` result as UTF8.
ProcessResult result = processManager.runSync(
final ProcessResult result = processManager.runSync(
propCommand,
stdoutEncoding: LATIN1
);
......@@ -82,7 +82,7 @@ class AndroidDevice extends Device {
@override
bool get isLocalEmulator {
if (_isLocalEmulator == null) {
String characteristics = _getProperty('ro.build.characteristics');
final String characteristics = _getProperty('ro.build.characteristics');
_isLocalEmulator = characteristics != null && characteristics.contains('emulator');
}
return _isLocalEmulator;
......@@ -124,11 +124,11 @@ class AndroidDevice extends Device {
bool _isValidAdbVersion(String adbVersion) {
// Sample output: 'Android Debug Bridge version 1.0.31'
Match versionFields = new RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
final Match versionFields = new RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
if (versionFields != null) {
int majorVersion = int.parse(versionFields[1]);
int minorVersion = int.parse(versionFields[2]);
int patchVersion = int.parse(versionFields[3]);
final int majorVersion = int.parse(versionFields[1]);
final int minorVersion = int.parse(versionFields[2]);
final int patchVersion = int.parse(versionFields[3]);
if (majorVersion > 1) {
return true;
}
......@@ -150,7 +150,7 @@ class AndroidDevice extends Device {
return false;
try {
String adbVersion = runCheckedSync(<String>[getAdbPath(androidSdk), 'version']);
final String adbVersion = runCheckedSync(<String>[getAdbPath(androidSdk), 'version']);
if (_isValidAdbVersion(adbVersion))
return true;
printError('The ADB at "${getAdbPath(androidSdk)}" is too old; please install version 1.0.32 or later.');
......@@ -170,9 +170,9 @@ class AndroidDevice extends Device {
runCheckedSync(<String>[getAdbPath(androidSdk), 'start-server']);
// Sample output: '22'
String sdkVersion = _getProperty('ro.build.version.sdk');
final String sdkVersion = _getProperty('ro.build.version.sdk');
int sdkVersionParsed = int.parse(sdkVersion, onError: (String source) => null);
final int sdkVersionParsed = int.parse(sdkVersion, onError: (String source) => null);
if (sdkVersionParsed == null) {
printError('Unexpected response from getprop: "$sdkVersion"');
return false;
......@@ -201,8 +201,8 @@ class AndroidDevice extends Device {
}
String _getSourceSha1(ApplicationPackage app) {
AndroidApk apk = app;
File shaFile = fs.file('${apk.apkPath}.sha1');
final AndroidApk apk = app;
final File shaFile = fs.file('${apk.apkPath}.sha1');
return shaFile.existsSync() ? shaFile.readAsStringSync() : '';
}
......@@ -212,19 +212,19 @@ class AndroidDevice extends Device {
@override
bool isAppInstalled(ApplicationPackage app) {
// This call takes 400ms - 600ms.
String listOut = runCheckedSync(adbCommandForDevice(<String>['shell', 'pm', 'list', 'packages', app.id]));
final String listOut = runCheckedSync(adbCommandForDevice(<String>['shell', 'pm', 'list', 'packages', app.id]));
return LineSplitter.split(listOut).contains("package:${app.id}");
}
@override
bool isLatestBuildInstalled(ApplicationPackage app) {
String installedSha1 = _getDeviceApkSha1(app);
final String installedSha1 = _getDeviceApkSha1(app);
return installedSha1.isNotEmpty && installedSha1 == _getSourceSha1(app);
}
@override
bool installApp(ApplicationPackage app) {
AndroidApk apk = app;
final AndroidApk apk = app;
if (!fs.isFileSync(apk.apkPath)) {
printError('"${apk.apkPath}" does not exist.');
return false;
......@@ -233,11 +233,11 @@ class AndroidDevice extends Device {
if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
return false;
Status status = logger.startProgress('Installing ${apk.apkPath}...', expectSlowOperation: true);
String installOut = runCheckedSync(adbCommandForDevice(<String>['install', '-r', apk.apkPath]));
final Status status = logger.startProgress('Installing ${apk.apkPath}...', expectSlowOperation: true);
final String installOut = runCheckedSync(adbCommandForDevice(<String>['install', '-r', apk.apkPath]));
status.stop();
RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
String failure = failureExp.stringMatch(installOut);
final RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
final String failure = failureExp.stringMatch(installOut);
if (failure != null) {
printError('Package install error: $failure');
return false;
......@@ -252,9 +252,9 @@ class AndroidDevice extends Device {
if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
return false;
String uninstallOut = runCheckedSync(adbCommandForDevice(<String>['uninstall', app.id]));
RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
String failure = failureExp.stringMatch(uninstallOut);
final String uninstallOut = runCheckedSync(adbCommandForDevice(<String>['uninstall', app.id]));
final RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
final String failure = failureExp.stringMatch(uninstallOut);
if (failure != null) {
printError('Package uninstall error: $failure');
return false;
......@@ -352,7 +352,7 @@ class AndroidDevice extends Device {
cmd.addAll(<String>['--ez', 'start-paused', 'true']);
}
cmd.add(apk.launchActivity);
String result = runCheckedSync(cmd);
final String result = runCheckedSync(cmd);
// This invocation returns 0 even when it fails.
if (result.contains('Error: ')) {
printError(result.trim());
......@@ -373,7 +373,7 @@ class AndroidDevice extends Device {
Uri observatoryUri, diagnosticUri;
if (debuggingOptions.buildMode == BuildMode.debug) {
List<Uri> deviceUris = await Future.wait(
final List<Uri> deviceUris = await Future.wait(
<Future<Uri>>[observatoryDiscovery.nextUri(), diagnosticDiscovery.nextUri()]
);
observatoryUri = deviceUris[0];
......@@ -400,7 +400,7 @@ class AndroidDevice extends Device {
@override
Future<bool> stopApp(ApplicationPackage app) {
List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
final List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
return runCommandAndStreamOutput(command).then((int exitCode) => exitCode == 0);
}
......@@ -429,11 +429,11 @@ class AndroidDevice extends Device {
/// Return the most recent timestamp in the Android log or `null` if there is
/// no available timestamp. The format can be passed to logcat's -T option.
String get lastLogcatTimestamp {
String output = runCheckedSync(adbCommandForDevice(<String>[
final String output = runCheckedSync(adbCommandForDevice(<String>[
'logcat', '-v', 'time', '-t', '1'
]));
Match timeMatch = _timeRegExp.firstMatch(output);
final Match timeMatch = _timeRegExp.firstMatch(output);
return timeMatch?.group(0);
}
......@@ -454,12 +454,12 @@ class AndroidDevice extends Device {
@override
Future<List<DiscoveredApp>> discoverApps() {
RegExp discoverExp = new RegExp(r'DISCOVER: (.*)');
List<DiscoveredApp> result = <DiscoveredApp>[];
StreamSubscription<String> logs = getLogReader().logLines.listen((String line) {
Match match = discoverExp.firstMatch(line);
final RegExp discoverExp = new RegExp(r'DISCOVER: (.*)');
final List<DiscoveredApp> result = <DiscoveredApp>[];
final StreamSubscription<String> logs = getLogReader().logLines.listen((String line) {
final Match match = discoverExp.firstMatch(line);
if (match != null) {
Map<String, dynamic> app = JSON.decode(match.group(1));
final Map<String, dynamic> app = JSON.decode(match.group(1));
result.add(new DiscoveredApp(app['id'], app['observatoryPort'], app['diagnosticPort']));
}
});
......@@ -476,7 +476,7 @@ class AndroidDevice extends Device {
}
Map<String, String> parseAdbDeviceProperties(String str) {
Map<String, String> properties = <String, String>{};
final Map<String, String> properties = <String, String>{};
final RegExp propertyExp = new RegExp(r'\[(.*?)\]: \[(.*?)\]');
for (Match match in propertyExp.allMatches(str))
properties[match.group(1)] = match.group(2);
......@@ -490,11 +490,11 @@ final RegExp _kDeviceRegex = new RegExp(r'^(\S+)\s+(\S+)(.*)');
///
/// [mockAdbOutput] is public for testing.
List<AndroidDevice> getAdbDevices({ String mockAdbOutput }) {
List<AndroidDevice> devices = <AndroidDevice>[];
final List<AndroidDevice> devices = <AndroidDevice>[];
String text;
if (mockAdbOutput == null) {
String adbPath = getAdbPath(androidSdk);
final String adbPath = getAdbPath(androidSdk);
if (adbPath == null)
return <AndroidDevice>[];
text = runSync(<String>[adbPath, 'devices', '-l']);
......@@ -517,18 +517,18 @@ List<AndroidDevice> getAdbDevices({ String mockAdbOutput }) {
continue;
if (_kDeviceRegex.hasMatch(line)) {
Match match = _kDeviceRegex.firstMatch(line);
final Match match = _kDeviceRegex.firstMatch(line);
String deviceID = match[1];
String deviceState = match[2];
final String deviceID = match[1];
final String deviceState = match[2];
String rest = match[3];
Map<String, String> info = <String, String>{};
final Map<String, String> info = <String, String>{};
if (rest != null && rest.isNotEmpty) {
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];
}
}
......@@ -595,8 +595,8 @@ class _AdbLogReader extends DeviceLogReader {
void _start() {
// Start the adb logcat process.
List<String> args = <String>['logcat', '-v', 'time'];
String lastTimestamp = device.lastLogcatTimestamp;
final List<String> args = <String>['logcat', '-v', 'time'];
final String lastTimestamp = device.lastLogcatTimestamp;
if (lastTimestamp != null)
_timeOrigin = _adbTimestampToDateTime(lastTimestamp);
else
......@@ -637,7 +637,7 @@ class _AdbLogReader extends DeviceLogReader {
}
if (_timeOrigin != null) {
final String timestamp = timeMatch.group(0);
DateTime time = _adbTimestampToDateTime(timestamp);
final DateTime time = _adbTimestampToDateTime(timestamp);
if (!time.isAfter(_timeOrigin)) {
// Ignore log messages before the origin.
return;
......@@ -692,22 +692,22 @@ class _AndroidDevicePortForwarder extends DevicePortForwarder {
List<ForwardedPort> get forwardedPorts {
final List<ForwardedPort> ports = <ForwardedPort>[];
String stdout = runCheckedSync(device.adbCommandForDevice(
final String stdout = runCheckedSync(device.adbCommandForDevice(
<String>['forward', '--list']
));
List<String> lines = LineSplitter.split(stdout).toList();
final List<String> lines = LineSplitter.split(stdout).toList();
for (String line in lines) {
if (line.startsWith(device.id)) {
List<String> splitLine = line.split("tcp:");
final List<String> splitLine = line.split("tcp:");
// Sanity check splitLine.
if (splitLine.length != 3)
continue;
// Attempt to extract ports.
int hostPort = _extractPort(splitLine[1]);
int devicePort = _extractPort(splitLine[2]);
final int hostPort = _extractPort(splitLine[1]);
final int devicePort = _extractPort(splitLine[2]);
// Failed, skip.
if ((hostPort == null) || (devicePort == null))
......
......@@ -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',
......
......@@ -53,7 +53,7 @@ class _AssetBuilder {
}
void add(File asset, String relativePath) {
String destPath = fs.path.join(_assetDir.path, relativePath);
final String destPath = fs.path.join(_assetDir.path, relativePath);
ensureDirectoryExists(destPath);
asset.copySync(destPath);
}
......@@ -94,7 +94,7 @@ class _ApkBuilder {
}
void compileClassesDex(File classesDex, List<File> jars) {
List<String> packageArgs = <String>[_dx.path,
final List<String> packageArgs = <String>[_dx.path,
'--dex',
'--force-jumbo',
'--output', classesDex.path
......@@ -106,7 +106,7 @@ class _ApkBuilder {
}
void package(File outputApk, File androidManifest, Directory assets, Directory artifacts, Directory resources, BuildMode buildMode) {
List<String> packageArgs = <String>[_aapt.path,
final List<String> packageArgs = <String>[_aapt.path,
'package',
'-M', androidManifest.path,
'-A', assets.path,
......@@ -222,8 +222,8 @@ class BuildApkCommand extends BuildSubCommand {
Future<Null> runCommand() async {
await super.runCommand();
TargetPlatform targetPlatform = _getTargetPlatform(argResults['target-arch']);
BuildMode buildMode = getBuildMode();
final TargetPlatform targetPlatform = _getTargetPlatform(argResults['target-arch']);
final BuildMode buildMode = getBuildMode();
if (targetPlatform != TargetPlatform.android_arm && buildMode != BuildMode.debug)
throwToolExit('Profile and release builds are only supported on ARM targets.');
......@@ -277,7 +277,7 @@ Future<_ApkComponents> _findApkComponents(
String resources,
Map<String, File> extraFiles
) async {
_ApkComponents components = new _ApkComponents();
final _ApkComponents components = new _ApkComponents();
components.manifest = fs.file(manifest);
components.resources = resources == null ? null : fs.directory(resources);
components.extraFiles = extraFiles != null ? extraFiles : <String, File>{};
......@@ -290,7 +290,7 @@ Future<_ApkComponents> _findApkComponents(
await parseServiceConfigs(components.services, jars: components.jars);
List<File> allFiles = <File>[
final List<File> allFiles = <File>[
components.manifest, components.icuData, components.libSkyShell, components.debugKeystore
]..addAll(components.jars)
..addAll(components.extraFiles.values);
......@@ -316,52 +316,52 @@ int _buildApk(
assert(platform != null);
assert(buildMode != null);
Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
printTrace('Building APK; buildMode: ${getModeName(buildMode)}.');
try {
_ApkBuilder builder = new _ApkBuilder(androidSdk.latestVersion);
String error = builder.checkDependencies();
final _ApkBuilder builder = new _ApkBuilder(androidSdk.latestVersion);
final String error = builder.checkDependencies();
if (error != null) {
printError(error);
return 1;
}
File classesDex = fs.file('${tempDir.path}/classes.dex');
final File classesDex = fs.file('${tempDir.path}/classes.dex');
builder.compileClassesDex(classesDex, components.jars);
File servicesConfig =
final File servicesConfig =
generateServiceDefinitions(tempDir.path, components.services);
_AssetBuilder assetBuilder = new _AssetBuilder(tempDir, 'assets');
final _AssetBuilder assetBuilder = new _AssetBuilder(tempDir, 'assets');
assetBuilder.add(components.icuData, 'icudtl.dat');
assetBuilder.add(fs.file(flxPath), 'app.flx');
assetBuilder.add(servicesConfig, 'services.json');
_AssetBuilder artifactBuilder = new _AssetBuilder(tempDir, 'artifacts');
final _AssetBuilder artifactBuilder = new _AssetBuilder(tempDir, 'artifacts');
artifactBuilder.add(classesDex, 'classes.dex');
String abiDir = getAbiDirectory(platform);
final String abiDir = getAbiDirectory(platform);
artifactBuilder.add(components.libSkyShell, 'lib/$abiDir/libsky_shell.so');
for (String relativePath in components.extraFiles.keys)
artifactBuilder.add(components.extraFiles[relativePath], relativePath);
File unalignedApk = fs.file('${tempDir.path}/app.apk.unaligned');
final File unalignedApk = fs.file('${tempDir.path}/app.apk.unaligned');
builder.package(
unalignedApk, components.manifest, assetBuilder.directory,
artifactBuilder.directory, components.resources, buildMode
);
File finalApk = fs.file(outputFile);
final File finalApk = fs.file(outputFile);
ensureDirectoryExists(finalApk.path);
builder.align(unalignedApk, finalApk);
int signResult = _signApk(builder, components, finalApk, keystore, buildMode);
final int signResult = _signApk(builder, components, finalApk, keystore, buildMode);
if (signResult != 0)
return signResult;
printTrace('calculateSha: $outputFile');
File apkShaFile = fs.file('$outputFile.sha1');
final File apkShaFile = fs.file('$outputFile.sha1');
apkShaFile.writeAsStringSync(calculateSha(finalApk));
return 0;
......@@ -419,17 +419,17 @@ bool _needsRebuild(
BuildMode buildMode,
Map<String, File> extraFiles
) {
FileStat apkStat = fs.statSync(apkPath);
final FileStat apkStat = fs.statSync(apkPath);
// Note: This list of dependencies is imperfect, but will do for now. We
// purposely don't include the .dart files, because we can load those
// over the network without needing to rebuild (at least on Android).
List<String> dependencies = <String>[
final List<String> dependencies = <String>[
manifest,
_kFlutterManifestPath,
_kPackagesStatusPath
];
dependencies.addAll(extraFiles.values.map((File file) => file.path));
Iterable<FileStat> dependenciesStat =
final Iterable<FileStat> dependenciesStat =
dependencies.map((String path) => fs.statSync(path));
if (apkStat.type == FileSystemEntityType.NOT_FOUND)
......@@ -443,8 +443,8 @@ bool _needsRebuild(
if (!fs.isFileSync('$apkPath.sha1'))
return true;
String lastBuildType = _readBuildMeta(fs.path.dirname(apkPath))['targetBuildType'];
String targetBuildType = _getTargetBuildTypeToken(platform, buildMode, fs.file(apkPath));
final String lastBuildType = _readBuildMeta(fs.path.dirname(apkPath))['targetBuildType'];
final String targetBuildType = _getTargetBuildTypeToken(platform, buildMode, fs.file(apkPath));
if (lastBuildType != targetBuildType)
return true;
......@@ -471,18 +471,18 @@ Future<Null> buildAndroid(
if (androidSdk == null)
throwToolExit('No Android SDK found. Try setting the ANDROID_HOME environment variable.');
List<String> validationResult = androidSdk.validateSdkWellFormed();
final List<String> validationResult = androidSdk.validateSdkWellFormed();
if (validationResult.isNotEmpty) {
validationResult.forEach(printError);
throwToolExit('Try re-installing or updating your Android SDK.');
}
Map<String, File> extraFiles = <String, File>{};
final Map<String, File> extraFiles = <String, File>{};
if (fs.isDirectorySync(_kDefaultAssetsPath)) {
Directory assetsDir = fs.directory(_kDefaultAssetsPath);
final Directory assetsDir = fs.directory(_kDefaultAssetsPath);
for (FileSystemEntity entity in assetsDir.listSync(recursive: true)) {
if (entity is File) {
String targetPath = entity.path.substring(assetsDir.path.length);
final String targetPath = entity.path.substring(assetsDir.path.length);
extraFiles["assets/$targetPath"] = entity;
}
}
......@@ -508,13 +508,13 @@ Future<Null> buildAndroid(
resources = _kDefaultResourcesPath;
}
_ApkComponents components = await _findApkComponents(platform, buildMode, manifest, resources, extraFiles);
final _ApkComponents components = await _findApkComponents(platform, buildMode, manifest, resources, extraFiles);
if (components == null)
throwToolExit('Failure building APK: unable to find components.');
String typeName = artifacts.getEngineType(platform, buildMode);
Status status = logger.startProgress('Building APK in ${getModeName(buildMode)} mode ($typeName)...',
final String typeName = artifacts.getEngineType(platform, buildMode);
final Status status = logger.startProgress('Building APK in ${getModeName(buildMode)} mode ($typeName)...',
expectSlowOperation: true);
if (flxPath != null && flxPath.isNotEmpty) {
......@@ -547,20 +547,20 @@ Future<Null> buildAndroid(
if (!fs.isDirectorySync(aotPath))
throwToolExit('AOT snapshot does not exist: $aotPath');
for (String aotFilename in kAotSnapshotFiles) {
String aotFilePath = fs.path.join(aotPath, aotFilename);
final String aotFilePath = fs.path.join(aotPath, aotFilename);
if (!fs.isFileSync(aotFilePath))
throwToolExit('Missing AOT snapshot file: $aotFilePath');
components.extraFiles['assets/$aotFilename'] = fs.file(aotFilePath);
}
}
int result = _buildApk(platform, buildMode, components, flxPath, keystore, outputFile);
final int result = _buildApk(platform, buildMode, components, flxPath, keystore, outputFile);
status.stop();
if (result != 0)
throwToolExit('Build APK failed ($result)', exitCode: result);
File apkFile = fs.file(outputFile);
final File apkFile = fs.file(outputFile);
printTrace('Built $outputFile (${getSizeAsMB(apkFile.lengthSync())}).');
_writeBuildMetaEntry(
......@@ -583,7 +583,7 @@ Future<Null> buildAndroidWithGradle(
if (androidSdk == null)
throwToolExit('No Android SDK found. Try setting the ANDROID_HOME environment variable.');
List<String> validationResult = androidSdk.validateSdkWellFormed(requireApkSigner: false);
final List<String> validationResult = androidSdk.validateSdkWellFormed(requireApkSigner: false);
if (validationResult.isNotEmpty) {
validationResult.forEach(printError);
throwToolExit('Try re-installing or updating your Android SDK.');
......@@ -622,23 +622,23 @@ Future<Null> buildApk(
}
Map<String, dynamic> _readBuildMeta(String buildDirectoryPath) {
File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
final File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
if (buildMetaFile.existsSync())
return JSON.decode(buildMetaFile.readAsStringSync());
return <String, dynamic>{};
}
void _writeBuildMetaEntry(String buildDirectoryPath, String key, dynamic value) {
Map<String, dynamic> meta = _readBuildMeta(buildDirectoryPath);
final Map<String, dynamic> meta = _readBuildMeta(buildDirectoryPath);
meta[key] = value;
File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
final File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
buildMetaFile.writeAsStringSync(toPrettyJson(meta));
}
String _getTargetBuildTypeToken(TargetPlatform platform, BuildMode buildMode, File outputBinary) {
String buildType = getNameForTargetPlatform(platform) + '-' + getModeName(buildMode);
if (artifacts is LocalEngineArtifacts) {
LocalEngineArtifacts localEngineArtifacts = artifacts;
final LocalEngineArtifacts localEngineArtifacts = artifacts;
buildType += ' [${localEngineArtifacts.engineOutPath}]';
}
if (outputBinary.existsSync())
......
......@@ -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;
......
......@@ -48,18 +48,18 @@ class DaemonCommand extends FlutterCommand {
Future<Null> runCommand() {
printStatus('Starting device daemon...');
AppContext appContext = new AppContext();
NotifyingLogger notifyingLogger = new NotifyingLogger();
final AppContext appContext = new AppContext();
final NotifyingLogger notifyingLogger = new NotifyingLogger();
appContext.setVariable(Logger, notifyingLogger);
Cache.releaseLockEarly();
return appContext.runInZone(() async {
Daemon daemon = new Daemon(
final Daemon daemon = new Daemon(
stdinCommandStream, stdoutCommandResponse,
daemonCommand: this, notifyingLogger: notifyingLogger);
int code = await daemon.onExit;
final int code = await daemon.onExit;
if (code != 0)
throwToolExit('Daemon exited with non-zero exit code: $code', exitCode: code);
}, onError: _handleError);
......@@ -118,7 +118,7 @@ class Daemon {
// {id, method, params}
// [id] is an opaque type to us.
dynamic id = request['id'];
final dynamic id = request['id'];
if (id == null) {
stderr.writeln('no id for request: $request');
......@@ -126,12 +126,12 @@ class Daemon {
}
try {
String method = request['method'];
final String method = request['method'];
if (!method.contains('.'))
throw 'method not understood: $method';
String prefix = method.substring(0, method.indexOf('.'));
String name = method.substring(method.indexOf('.') + 1);
final String prefix = method.substring(0, method.indexOf('.'));
final String name = method.substring(method.indexOf('.') + 1);
if (_domainMap[prefix] == null)
throw 'no domain for method: $method';
......@@ -183,7 +183,7 @@ abstract class Domain {
}
void sendEvent(String name, [dynamic args]) {
Map<String, dynamic> map = <String, dynamic>{ 'event': name };
final Map<String, dynamic> map = <String, dynamic>{ 'event': name };
if (args != null)
map['params'] = _toJsonable(args);
_send(map);
......@@ -194,7 +194,7 @@ abstract class Domain {
String _getStringArg(Map<String, dynamic> args, String name, { bool required: false }) {
if (required && !args.containsKey(name))
throw "$name is required";
dynamic val = args[name];
final dynamic val = args[name];
if (val != null && val is! String)
throw "$name is not a String";
return val;
......@@ -203,7 +203,7 @@ abstract class Domain {
bool _getBoolArg(Map<String, dynamic> args, String name, { bool required: false }) {
if (required && !args.containsKey(name))
throw "$name is required";
dynamic val = args[name];
final dynamic val = args[name];
if (val != null && val is! bool)
throw "$name is not a bool";
return val;
......@@ -212,7 +212,7 @@ abstract class Domain {
int _getIntArg(Map<String, dynamic> args, String name, { bool required: false }) {
if (required && !args.containsKey(name))
throw "$name is required";
dynamic val = args[name];
final dynamic val = args[name];
if (val != null && val is! int)
throw "$name is not an int";
return val;
......@@ -293,24 +293,24 @@ class AppDomain extends Domain {
List<AppInstance> _apps = <AppInstance>[];
Future<Map<String, dynamic>> start(Map<String, dynamic> args) async {
String deviceId = _getStringArg(args, 'deviceId', required: true);
String projectDirectory = _getStringArg(args, 'projectDirectory', required: true);
bool startPaused = _getBoolArg(args, 'startPaused') ?? false;
String route = _getStringArg(args, 'route');
String mode = _getStringArg(args, 'mode');
String target = _getStringArg(args, 'target');
bool enableHotReload = _getBoolArg(args, 'hot') ?? kHotReloadDefault;
Device device = daemon.deviceDomain._getOrLocateDevice(deviceId);
final String deviceId = _getStringArg(args, 'deviceId', required: true);
final String projectDirectory = _getStringArg(args, 'projectDirectory', required: true);
final bool startPaused = _getBoolArg(args, 'startPaused') ?? false;
final String route = _getStringArg(args, 'route');
final String mode = _getStringArg(args, 'mode');
final String target = _getStringArg(args, 'target');
final bool enableHotReload = _getBoolArg(args, 'hot') ?? kHotReloadDefault;
final Device device = daemon.deviceDomain._getOrLocateDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
if (!fs.isDirectorySync(projectDirectory))
throw "'$projectDirectory' does not exist";
BuildMode buildMode = getBuildModeForName(mode) ?? BuildMode.debug;
final BuildMode buildMode = getBuildModeForName(mode) ?? BuildMode.debug;
AppInstance app = await startApp(
final AppInstance app = await startApp(
device, projectDirectory, target, route,
buildMode, startPaused, enableHotReload);
......@@ -348,7 +348,7 @@ class AppDomain extends Domain {
throw '${toTitleCase(getModeName(buildMode))} mode is not supported for emulators.';
// We change the current working directory for the duration of the `start` command.
Directory cwd = fs.currentDirectory;
final Directory cwd = fs.currentDirectory;
fs.currentDirectory = fs.directory(projectDirectory);
ResidentRunner runner;
......@@ -374,7 +374,7 @@ class AppDomain extends Domain {
);
}
AppInstance app = new AppInstance(_getNewAppId(), runner: runner, logToStdout: daemon.logToStdout);
final AppInstance app = new AppInstance(_getNewAppId(), runner: runner, logToStdout: daemon.logToStdout);
_apps.add(app);
_sendAppEvent(app, 'start', <String, dynamic>{
'deviceId': device.id,
......@@ -387,7 +387,7 @@ class AppDomain extends Domain {
if (options.debuggingEnabled) {
connectionInfoCompleter = new Completer<DebugConnectionInfo>();
connectionInfoCompleter.future.then<Null>((DebugConnectionInfo info) {
Map<String, dynamic> params = <String, dynamic>{
final Map<String, dynamic> params = <String, dynamic>{
'port': info.httpUri.port,
'wsUri': info.wsUri.toString(),
};
......@@ -396,7 +396,7 @@ class AppDomain extends Domain {
_sendAppEvent(app, 'debugPort', params);
});
}
Completer<Null> appStartedCompleter = new Completer<Null>();
final Completer<Null> appStartedCompleter = new Completer<Null>();
appStartedCompleter.future.then<Null>((Null value) {
_sendAppEvent(app, 'started');
});
......@@ -424,11 +424,11 @@ class AppDomain extends Domain {
enableHotReload && device.supportsHotMode;
Future<OperationResult> restart(Map<String, dynamic> args) async {
String appId = _getStringArg(args, 'appId', required: true);
bool fullRestart = _getBoolArg(args, 'fullRestart') ?? false;
bool pauseAfterRestart = _getBoolArg(args, 'pause') ?? false;
final String appId = _getStringArg(args, 'appId', required: true);
final bool fullRestart = _getBoolArg(args, 'fullRestart') ?? false;
final bool pauseAfterRestart = _getBoolArg(args, 'pause') ?? false;
AppInstance app = _getApp(appId);
final AppInstance app = _getApp(appId);
if (app == null)
throw "app '$appId' not found";
......@@ -438,16 +438,16 @@ class AppDomain extends Domain {
}
Future<OperationResult> callServiceExtension(Map<String, dynamic> args) async {
String appId = _getStringArg(args, 'appId', required: true);
String methodName = _getStringArg(args, 'methodName');
Map<String, String> params = args['params'] ?? <String, String>{};
final String appId = _getStringArg(args, 'appId', required: true);
final String methodName = _getStringArg(args, 'methodName');
final Map<String, String> params = args['params'] ?? <String, String>{};
AppInstance app = _getApp(appId);
final AppInstance app = _getApp(appId);
if (app == null)
throw "app '$appId' not found";
Isolate isolate = app.runner.currentView.uiIsolate;
Map<String, dynamic> result = await isolate.invokeFlutterExtensionRpcRaw(methodName, params: params);
final Isolate isolate = app.runner.currentView.uiIsolate;
final Map<String, dynamic> result = await isolate.invokeFlutterExtensionRpcRaw(methodName, params: params);
if (result == null)
return new OperationResult(1, 'method not available: $methodName');
......@@ -458,9 +458,9 @@ class AppDomain extends Domain {
}
Future<bool> stop(Map<String, dynamic> args) async {
String appId = _getStringArg(args, 'appId', required: true);
final String appId = _getStringArg(args, 'appId', required: true);
AppInstance app = _getApp(appId);
final AppInstance app = _getApp(appId);
if (app == null)
throw "app '$appId' not found";
......@@ -475,13 +475,13 @@ class AppDomain extends Domain {
}
Future<List<Map<String, dynamic>>> discover(Map<String, dynamic> args) async {
String deviceId = _getStringArg(args, 'deviceId', required: true);
final String deviceId = _getStringArg(args, 'deviceId', required: true);
Device device = daemon.deviceDomain._getDevice(deviceId);
final Device device = daemon.deviceDomain._getDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
List<DiscoveredApp> apps = await device.discoverApps();
final List<DiscoveredApp> apps = await device.discoverApps();
return apps.map((DiscoveredApp app) {
return <String, dynamic>{
'id': app.id,
......@@ -496,7 +496,7 @@ class AppDomain extends Domain {
}
void _sendAppEvent(AppInstance app, String name, [Map<String, dynamic> args]) {
Map<String, dynamic> eventArgs = <String, dynamic> { 'appId': app.id };
final Map<String, dynamic> eventArgs = <String, dynamic> { 'appId': app.id };
if (args != null)
eventArgs.addAll(args);
sendEvent('app.$name', eventArgs);
......@@ -540,7 +540,7 @@ class DeviceDomain extends Domain {
List<PollingDeviceDiscovery> _discoverers = <PollingDeviceDiscovery>[];
Future<List<Device>> getDevices([Map<String, dynamic> args]) {
List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
final List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
return discoverer.devices;
}).toList();
return new Future<List<Device>>.value(devices);
......@@ -562,11 +562,11 @@ class DeviceDomain extends Domain {
/// Forward a host port to a device port.
Future<Map<String, dynamic>> forward(Map<String, dynamic> args) async {
String deviceId = _getStringArg(args, 'deviceId', required: true);
int devicePort = _getIntArg(args, 'devicePort', required: true);
final String deviceId = _getStringArg(args, 'deviceId', required: true);
final int devicePort = _getIntArg(args, 'devicePort', required: true);
int hostPort = _getIntArg(args, 'hostPort');
Device device = daemon.deviceDomain._getDevice(deviceId);
final Device device = daemon.deviceDomain._getDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
......@@ -577,11 +577,11 @@ class DeviceDomain extends Domain {
/// Removes a forwarded port.
Future<Null> unforward(Map<String, dynamic> args) async {
String deviceId = _getStringArg(args, 'deviceId', required: true);
int devicePort = _getIntArg(args, 'devicePort', required: true);
int hostPort = _getIntArg(args, 'hostPort', required: true);
final String deviceId = _getStringArg(args, 'deviceId', required: true);
final int devicePort = _getIntArg(args, 'devicePort', required: true);
final int hostPort = _getIntArg(args, 'hostPort', required: true);
Device device = daemon.deviceDomain._getDevice(deviceId);
final Device device = daemon.deviceDomain._getDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
......@@ -596,7 +596,7 @@ class DeviceDomain extends Domain {
/// Return the device matching the deviceId field in the args.
Device _getDevice(String deviceId) {
List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
final List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
return discoverer.devices;
}).toList();
return devices.firstWhere((Device device) => device.id == deviceId, orElse: () => null);
......@@ -605,13 +605,13 @@ class DeviceDomain extends Domain {
/// Return a known matching device, or scan for devices if no known match is found.
Device _getOrLocateDevice(String deviceId) {
// Look for an already known device.
Device device = _getDevice(deviceId);
final Device device = _getDevice(deviceId);
if (device != null)
return device;
// Scan the different device providers for a match.
for (PollingDeviceDiscovery discoverer in _discoverers) {
List<Device> devices = discoverer.pollingGetDevices();
final List<Device> devices = discoverer.pollingGetDevices();
for (Device device in devices)
if (device.id == deviceId)
return device;
......@@ -727,7 +727,7 @@ class AppInstance {
if (_logger == null)
_logger = new _AppRunLogger(domain, this, logToStdout: logToStdout);
AppContext appContext = new AppContext();
final AppContext appContext = new AppContext();
appContext.setVariable(Logger, _logger);
return appContext.runInZone(method);
}
......@@ -787,7 +787,7 @@ class _AppRunLogger extends Logger {
if (_status != null)
return new Status();
int id = _nextProgressId++;
final int id = _nextProgressId++;
_sendProgressEvent(<String, dynamic>{
'id': id.toString(),
......
......@@ -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;
......
......@@ -61,7 +61,7 @@ class SimControl {
return true;
if (deviceName == null) {
SimDevice testDevice = _createTestDevice();
final SimDevice testDevice = _createTestDevice();
if (testDevice == null) {
return false;
}
......@@ -72,7 +72,7 @@ class SimControl {
// "template" is but the built-in 'Blank' seems to work. -l causes xcrun to
// quit after a time limit without killing the simulator. We quit after
// 1 second.
List<String> args = <String>[_xcrunPath, 'instruments', '-w', deviceName, '-t', 'Blank', '-l', '1'];
final List<String> args = <String>[_xcrunPath, 'instruments', '-w', deviceName, '-t', 'Blank', '-l', '1'];
printTrace(args.join(' '));
runDetached(args);
printStatus('Waiting for iOS Simulator to boot...');
......@@ -98,11 +98,11 @@ class SimControl {
}
SimDevice _createTestDevice() {
SimDeviceType deviceType = _findSuitableDeviceType();
final SimDeviceType deviceType = _findSuitableDeviceType();
if (deviceType == null)
return null;
String runtime = _findSuitableRuntime();
final String runtime = _findSuitableRuntime();
if (runtime == null)
return null;
......@@ -112,8 +112,8 @@ class SimControl {
.forEach(_deleteDevice);
// Create new device
String deviceName = '${deviceType.name} $_kFlutterTestDeviceSuffix';
List<String> args = <String>[_xcrunPath, 'simctl', 'create', deviceName, deviceType.identifier, runtime];
final String deviceName = '${deviceType.name} $_kFlutterTestDeviceSuffix';
final List<String> args = <String>[_xcrunPath, 'simctl', 'create', deviceName, deviceType.identifier, runtime];
printTrace(args.join(' '));
runCheckedSync(args);
......@@ -121,8 +121,8 @@ class SimControl {
}
SimDeviceType _findSuitableDeviceType() {
List<Map<String, dynamic>> allTypes = _list(SimControlListSection.devicetypes);
List<Map<String, dynamic>> usableTypes = allTypes
final List<Map<String, dynamic>> allTypes = _list(SimControlListSection.devicetypes);
final List<Map<String, dynamic>> usableTypes = allTypes
.where((Map<String, dynamic> info) => info['name'].startsWith('iPhone'))
.toList()
..sort((Map<String, dynamic> r1, Map<String, dynamic> r2) => -compareIphoneVersions(r1['identifier'], r2['identifier']));
......@@ -141,8 +141,8 @@ class SimControl {
}
String _findSuitableRuntime() {
List<Map<String, dynamic>> allRuntimes = _list(SimControlListSection.runtimes);
List<Map<String, dynamic>> usableRuntimes = allRuntimes
final List<Map<String, dynamic>> allRuntimes = _list(SimControlListSection.runtimes);
final List<Map<String, dynamic>> usableRuntimes = allRuntimes
.where((Map<String, dynamic> info) => info['name'].startsWith('iOS'))
.toList()
..sort((Map<String, dynamic> r1, Map<String, dynamic> r2) => -compareIosVersions(r1['version'], r2['version']));
......@@ -159,7 +159,7 @@ class SimControl {
void _deleteDevice(SimDevice device) {
try {
List<String> args = <String>[_xcrunPath, 'simctl', 'delete', device.name];
final List<String> args = <String>[_xcrunPath, 'simctl', 'delete', device.name];
printTrace(args.join(' '));
runCheckedSync(args);
} catch(e) {
......@@ -190,9 +190,9 @@ class SimControl {
// },
// "pairs": { ... },
List<String> command = <String>[_xcrunPath, 'simctl', 'list', '--json', section.name];
final List<String> command = <String>[_xcrunPath, 'simctl', 'list', '--json', section.name];
printTrace(command.join(' '));
ProcessResult results = processManager.runSync(command);
final ProcessResult results = processManager.runSync(command);
if (results.exitCode != 0) {
printError('Error executing simctl: ${results.exitCode}\n${results.stderr}');
return <String, Map<String, dynamic>>{};
......@@ -203,12 +203,12 @@ class SimControl {
/// Returns a list of all available devices, both potential and connected.
List<SimDevice> getDevices() {
List<SimDevice> devices = <SimDevice>[];
final List<SimDevice> devices = <SimDevice>[];
Map<String, dynamic> devicesSection = _list(SimControlListSection.devices);
final Map<String, dynamic> devicesSection = _list(SimControlListSection.devices);
for (String deviceCategory in devicesSection.keys) {
List<Map<String, String>> devicesData = devicesSection[deviceCategory];
final List<Map<String, String>> devicesData = devicesSection[deviceCategory];
for (Map<String, String> data in devicesData) {
devices.add(new SimDevice(deviceCategory, data));
......@@ -244,7 +244,7 @@ class SimControl {
}
void launch(String deviceId, String appIdentifier, [List<String> launchArgs]) {
List<String> args = <String>[_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier];
final List<String> args = <String>[_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier];
if (launchArgs != null)
args.addAll(launchArgs);
runCheckedSync(args);
......@@ -329,7 +329,7 @@ class IOSSimulator extends Device {
}
String _getSimulatorAppHomeDirectory(ApplicationPackage app) {
String simulatorPath = _getSimulatorPath();
final String simulatorPath = _getSimulatorPath();
if (simulatorPath == null)
return null;
return fs.path.join(simulatorPath, 'data');
......@@ -346,7 +346,7 @@ class IOSSimulator extends Device {
@override
bool installApp(ApplicationPackage app) {
try {
IOSApp iosApp = app;
final IOSApp iosApp = app;
SimControl.instance.install(id, iosApp.simulatorBundlePath);
return true;
} catch (e) {
......@@ -374,7 +374,7 @@ class IOSSimulator extends Device {
// Step 1: Check if the device is part of a blacklisted category.
// We do not support WatchOS or tvOS devices.
RegExp blacklist = new RegExp(r'Apple (TV|Watch)', caseSensitive: false);
final RegExp blacklist = new RegExp(r'Apple (TV|Watch)', caseSensitive: false);
if (blacklist.hasMatch(name)) {
_supportMessage = 'Flutter does not support Apple TV or Apple Watch. Select an iPhone 5s or above.';
return false;
......@@ -386,14 +386,14 @@ class IOSSimulator extends Device {
// runner on the simulator is completely different).
// Check for unsupported iPads.
Match iPadMatch = new RegExp(r'iPad (2|Retina)', caseSensitive: false).firstMatch(name);
final Match iPadMatch = new RegExp(r'iPad (2|Retina)', caseSensitive: false).firstMatch(name);
if (iPadMatch != null) {
_supportMessage = 'Flutter does not yet support iPad 2 or iPad Retina. Select an iPad Air or above.';
return false;
}
// Check for unsupported iPhones.
Match iPhoneMatch = new RegExp(r'iPhone [0-5]').firstMatch(name);
final Match iPhoneMatch = new RegExp(r'iPhone [0-5]').firstMatch(name);
if (iPhoneMatch != null) {
if (name == 'iPhone 5s')
return true;
......@@ -441,7 +441,7 @@ class IOSSimulator extends Device {
}
// Prepare launch arguments.
List<String> args = <String>['--enable-dart-profiling'];
final List<String> args = <String>['--enable-dart-profiling'];
if (!prebuiltApplication) {
args.addAll(<String>[
......@@ -457,9 +457,9 @@ class IOSSimulator extends Device {
if (debuggingOptions.startPaused)
args.add('--start-paused');
int observatoryPort = await debuggingOptions.findBestObservatoryPort();
final int observatoryPort = await debuggingOptions.findBestObservatoryPort();
args.add('--observatory-port=$observatoryPort');
int diagnosticPort = await debuggingOptions.findBestDiagnosticPort();
final int diagnosticPort = await debuggingOptions.findBestDiagnosticPort();
args.add('--diagnostic-port=$diagnosticPort');
}
......@@ -484,7 +484,7 @@ class IOSSimulator extends Device {
printTrace('Waiting for observatory port to be available...');
try {
Uri deviceUri = await observatoryDiscovery.nextUri();
final Uri deviceUri = await observatoryDiscovery.nextUri();
return new LaunchResult.succeeded(observatoryUri: deviceUri);
} catch (error) {
printError('Error waiting for a debug connection: $error');
......@@ -495,9 +495,9 @@ class IOSSimulator extends Device {
}
bool _applicationIsInstalledAndRunning(ApplicationPackage app) {
bool isInstalled = isAppInstalled(app);
final bool isInstalled = isAppInstalled(app);
bool isRunning = exitsHappy(<String>[
final bool isRunning = exitsHappy(<String>[
'/usr/bin/killall',
'Runner',
]);
......@@ -515,14 +515,14 @@ class IOSSimulator extends Device {
Future<Null> _buildAndInstallApplicationBundle(ApplicationPackage app) async {
// Step 1: Build the Xcode project.
// The build mode for the simulator is always debug.
XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: BuildMode.debug, buildForDevice: false);
final XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: BuildMode.debug, buildForDevice: false);
if (!buildResult.success)
throwToolExit('Could not build the application for the simulator.');
// Step 2: Assert that the Xcode project was successfully built.
IOSApp iosApp = app;
Directory bundle = fs.directory(iosApp.simulatorBundlePath);
bool bundleExists = bundle.existsSync();
final IOSApp iosApp = app;
final Directory bundle = fs.directory(iosApp.simulatorBundlePath);
final bool bundleExists = bundle.existsSync();
if (!bundleExists)
throwToolExit('Could not find the built application bundle at ${bundle.path}.');
......@@ -542,7 +542,7 @@ class IOSSimulator extends Device {
Future<bool> pushFile(
ApplicationPackage app, String localFile, String targetFile) async {
if (p.platform.isMacOS) {
String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app);
final String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app);
runCheckedSync(<String>['cp', localFile, fs.path.join(simulatorHomeDirectory, targetFile)]);
return true;
}
......@@ -575,16 +575,16 @@ class IOSSimulator extends Device {
@override
void clearLogs() {
File logFile = fs.file(logFilePath);
final File logFile = fs.file(logFilePath);
if (logFile.existsSync()) {
RandomAccessFile randomFile = logFile.openSync(mode: FileMode.WRITE);
final RandomAccessFile randomFile = logFile.openSync(mode: FileMode.WRITE);
randomFile.truncateSync(0);
randomFile.closeSync();
}
}
void ensureLogsExists() {
File logFile = fs.file(logFilePath);
final File logFile = fs.file(logFilePath);
if (!logFile.existsSync())
logFile.writeAsBytesSync(<int>[]);
}
......@@ -667,10 +667,10 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
];
String _filterDeviceLine(String string) {
Match match = _mapRegex.matchAsPrefix(string);
final Match match = _mapRegex.matchAsPrefix(string);
if (match != null) {
String category = match.group(1);
String content = match.group(2);
final String category = match.group(1);
final String content = match.group(2);
// Filter out some messages that clearly aren't related to Flutter.
if (string.contains(': could not find icon for representation -> com.apple.'))
......@@ -720,7 +720,7 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
void _onDeviceLine(String line) {
printTrace('[DEVICE LOG] $line');
Match multi = _lastMessageMultipleRegex.matchAsPrefix(line);
final Match multi = _lastMessageMultipleRegex.matchAsPrefix(line);
if (multi != null) {
if (_lastLine != null) {
......@@ -737,7 +737,7 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
}
String _filterSystemLog(String string) {
Match match = _mapRegex.matchAsPrefix(string);
final Match match = _mapRegex.matchAsPrefix(string);
return match == null ? string : '${match.group(1)}: ${match.group(2)}';
}
......@@ -746,7 +746,7 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
if (!_flutterRunnerRegex.hasMatch(line))
return;
String filteredLine = _filterSystemLog(line);
final String filteredLine = _filterSystemLog(line);
if (filteredLine == null)
return;
......@@ -760,13 +760,13 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
}
int compareIosVersions(String v1, String v2) {
List<int> v1Fragments = v1.split('.').map(int.parse).toList();
List<int> v2Fragments = v2.split('.').map(int.parse).toList();
final List<int> v1Fragments = v1.split('.').map(int.parse).toList();
final List<int> v2Fragments = v2.split('.').map(int.parse).toList();
int i = 0;
while(i < v1Fragments.length && i < v2Fragments.length) {
int v1Fragment = v1Fragments[i];
int v2Fragment = v2Fragments[i];
final int v1Fragment = v1Fragments[i];
final int v2Fragment = v2Fragments[i];
if (v1Fragment != v2Fragment)
return v1Fragment.compareTo(v2Fragment);
i++;
......@@ -786,11 +786,11 @@ final RegExp _iosDeviceTypePattern =
new RegExp(r'com.apple.CoreSimulator.SimDeviceType.iPhone-(\d+)(.*)');
int compareIphoneVersions(String id1, String id2) {
Match m1 = _iosDeviceTypePattern.firstMatch(id1);
Match m2 = _iosDeviceTypePattern.firstMatch(id2);
final Match m1 = _iosDeviceTypePattern.firstMatch(id1);
final Match m2 = _iosDeviceTypePattern.firstMatch(id2);
int v1 = int.parse(m1[1]);
int v2 = int.parse(m2[1]);
final int v1 = int.parse(m1[1]);
final int v2 = int.parse(m2[1]);
if (v1 != v2)
return v1.compareTo(v2);
......@@ -798,8 +798,8 @@ int compareIphoneVersions(String id1, String id2) {
// Sorted in the least preferred first order.
const List<String> qualifiers = const <String>['-Plus', '', 's-Plus', 's'];
int q1 = qualifiers.indexOf(m1[2]);
int q2 = qualifiers.indexOf(m2[2]);
final int q1 = qualifiers.indexOf(m1[2]);
final int q2 = qualifiers.indexOf(m2[2]);
return q1.compareTo(q2);
}
......
......@@ -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));
......
......@@ -108,8 +108,8 @@ abstract class ResidentRunner {
}
Future<Null> _screenshot() async {
Status status = logger.startProgress('Taking screenshot...');
File outputFile = getUniqueFile(fs.currentDirectory, 'flutter', 'png');
final Status status = logger.startProgress('Taking screenshot...');
final File outputFile = getUniqueFile(fs.currentDirectory, 'flutter', 'png');
try {
if (supportsServiceProtocol && isRunningDebug) {
if (vmService != null)
......@@ -133,7 +133,7 @@ abstract class ResidentRunner {
}
}
}
int sizeKB = (await outputFile.length()) ~/ 1024;
final int sizeKB = (await outputFile.length()) ~/ 1024;
status.stop();
printStatus('Screenshot written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).');
} catch (error) {
......@@ -265,7 +265,7 @@ abstract class ResidentRunner {
}
} else if (lower == 'o') {
if (supportsServiceProtocol && isRunningDebug) {
String platform = await _debugRotatePlatform();
final String platform = await _debugRotatePlatform();
print('Switched operating system to: $platform');
return true;
}
......@@ -287,7 +287,7 @@ abstract class ResidentRunner {
}
_processingTerminalRequest = true;
try {
bool handled = await _commonTerminalInputHandler(command);
final bool handled = await _commonTerminalInputHandler(command);
if (!handled)
await handleTerminalCommand(command);
} finally {
......@@ -323,18 +323,18 @@ abstract class ResidentRunner {
}
Future<int> waitForAppToFinish() async {
int exitCode = await _finished.future;
final int exitCode = await _finished.future;
await cleanupAtFinish();
return exitCode;
}
bool hasDirtyDependencies() {
DartDependencySetBuilder dartDependencySetBuilder =
final DartDependencySetBuilder dartDependencySetBuilder =
new DartDependencySetBuilder(
mainPath, projectRootPath, packagesFilePath);
DependencyChecker dependencyChecker =
final DependencyChecker dependencyChecker =
new DependencyChecker(dartDependencySetBuilder, assetBundle);
String path = package.packagePath;
final String path = package.packagePath;
if (path == null) {
return true;
}
......@@ -402,7 +402,7 @@ class OperationResult {
String findMainDartFile([String target]) {
if (target == null)
target = '';
String targetPath = fs.path.absolute(target);
final String targetPath = fs.path.absolute(target);
if (fs.isDirectorySync(targetPath))
return fs.path.join(targetPath, 'lib', 'main.dart');
else
......
......@@ -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...');
......
......@@ -98,7 +98,7 @@ class HotRunner extends ResidentRunner {
// Already computed.
return true;
}
DartDependencySetBuilder dartDependencySetBuilder =
final DartDependencySetBuilder dartDependencySetBuilder =
new DartDependencySetBuilder(
mainPath, projectRootPath, packagesFilePath);
try {
......@@ -129,7 +129,7 @@ class HotRunner 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);
......@@ -142,11 +142,11 @@ class HotRunner extends ResidentRunner {
return 1;
}
Map<String, dynamic> platformArgs = new Map<String, dynamic>();
final Map<String, dynamic> platformArgs = new Map<String, dynamic>();
await startEchoingDeviceLog(package);
String modeName = getModeName(debuggingOptions.buildMode);
final String modeName = getModeName(debuggingOptions.buildMode);
printStatus('Launching ${getDisplayPath(mainPath)} on ${device.name} in $modeName mode...');
// Include kernel code
......@@ -155,7 +155,7 @@ class HotRunner extends ResidentRunner {
kernelContent = new DevFSFileContent(fs.file(kernelFilePath));
// Start the application.
Future<LaunchResult> futureResult = device.startApp(
final Future<LaunchResult> futureResult = device.startApp(
package,
debuggingOptions.buildMode,
mainPath: mainPath,
......@@ -167,7 +167,7 @@ class HotRunner extends ResidentRunner {
applicationNeedsRebuild: shouldBuild || hasDirtyDependencies()
);
LaunchResult result = await futureResult;
final LaunchResult result = await futureResult;
if (!result.started) {
printError('Error launching application on ${device.name}.');
......@@ -184,7 +184,7 @@ class HotRunner extends ResidentRunner {
}
try {
Uri baseUri = await _initDevFS();
final Uri baseUri = await _initDevFS();
if (connectionInfoCompleter != null) {
connectionInfoCompleter.complete(
new DebugConnectionInfo(
......@@ -198,7 +198,7 @@ class HotRunner extends ResidentRunner {
printError('Error initializing DevFS: $error');
return 3;
}
bool devfsResult = await _updateDevFS();
final bool devfsResult = await _updateDevFS();
if (!devfsResult) {
printError('Could not perform initial file synchronization.');
return 3;
......@@ -229,7 +229,7 @@ class HotRunner extends ResidentRunner {
await _cleanupDevFS();
await stopEchoingDeviceLog();
await stopApp();
File benchmarkOutput = fs.file('hot_benchmark.json');
final File benchmarkOutput = fs.file('hot_benchmark.json');
benchmarkOutput.writeAsStringSync(toPrettyJson(benchmarkData));
}
......@@ -243,7 +243,7 @@ class HotRunner extends ResidentRunner {
Future<Null> handleTerminalCommand(String code) async {
final String lower = code.toLowerCase();
if ((lower == 'r') || (code == AnsiTerminal.KEY_F5)) {
OperationResult result = await restart(fullRestart: code == 'R');
final OperationResult result = await restart(fullRestart: code == 'R');
if (!result.isOk) {
// TODO(johnmccutchan): Attempt to determine the number of errors that
// occurred and tighten this message.
......@@ -255,7 +255,7 @@ class HotRunner extends ResidentRunner {
DevFS _devFS;
Future<Uri> _initDevFS() {
String fsName = fs.path.basename(projectRootPath);
final String fsName = fs.path.basename(projectRootPath);
_devFS = new DevFS(vmService,
fsName,
fs.directory(projectRootPath),
......@@ -271,13 +271,13 @@ class HotRunner extends ResidentRunner {
final bool rebuildBundle = assetBundle.needsBuild();
if (rebuildBundle) {
printTrace('Updating assets');
int result = await assetBundle.build();
final int result = await assetBundle.build();
if (result != 0)
return false;
}
Status devFSStatus = logger.startProgress('Syncing files to device...',
final Status devFSStatus = logger.startProgress('Syncing files to device...',
expectSlowOperation: true);
int bytes = await _devFS.update(progressReporter: progressReporter,
final int bytes = await _devFS.update(progressReporter: progressReporter,
bundle: assetBundle,
bundleDirty: rebuildBundle,
fileFilter: _dartDependencies);
......@@ -316,16 +316,16 @@ class HotRunner extends ResidentRunner {
Future<Null> _launchInView(Uri entryUri,
Uri packagesUri,
Uri assetsDirectoryUri) async {
FlutterView view = vmService.vm.mainView;
final FlutterView view = vmService.vm.mainView;
return view.runFromSource(entryUri, packagesUri, assetsDirectoryUri);
}
Future<Null> _launchFromDevFS(ApplicationPackage package,
String mainScript) async {
String entryUri = fs.path.relative(mainScript, from: projectRootPath);
Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryUri));
Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
Uri deviceAssetsDirectoryUri =
final String entryUri = fs.path.relative(mainScript, from: projectRootPath);
final Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryUri));
final Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
final Uri deviceAssetsDirectoryUri =
_devFS.baseUri.resolveUri(fs.path.toUri(getAssetBuildDirectory()));
await _launchInView(deviceEntryUri,
devicePackagesUri,
......@@ -333,9 +333,9 @@ class HotRunner extends ResidentRunner {
}
Future<OperationResult> _restartFromSources() async {
Stopwatch restartTimer = new Stopwatch();
final Stopwatch restartTimer = new Stopwatch();
restartTimer.start();
bool updatedDevFS = await _updateDevFS();
final bool updatedDevFS = await _updateDevFS();
if (!updatedDevFS)
return new OperationResult(1, 'Dart Source Error');
await _launchFromDevFS(package, mainPath);
......@@ -374,7 +374,7 @@ class HotRunner extends ResidentRunner {
@override
Future<OperationResult> restart({ bool fullRestart: false, bool pauseAfterRestart: false }) async {
if (fullRestart) {
Status status = logger.startProgress('Performing full restart...', progressId: 'hot.restart');
final Status status = logger.startProgress('Performing full restart...', progressId: 'hot.restart');
try {
await _restartFromSources();
status.stop();
......@@ -385,9 +385,9 @@ class HotRunner extends ResidentRunner {
rethrow;
}
} else {
Status status = logger.startProgress('Performing hot reload...', progressId: 'hot.reload');
final Status status = logger.startProgress('Performing hot reload...', progressId: 'hot.reload');
try {
OperationResult result = await _reloadSources(pause: pauseAfterRestart);
final OperationResult result = await _reloadSources(pause: pauseAfterRestart);
status.stop();
if (result.isOk)
printStatus("${result.message}.");
......@@ -409,7 +409,7 @@ class HotRunner extends ResidentRunner {
// not be affected, so we resume reporting reload times on the second
// reload.
final bool shouldReportReloadTime = !_runningFromSnapshot;
Stopwatch reloadTimer = new Stopwatch();
final Stopwatch reloadTimer = new Stopwatch();
reloadTimer.start();
Stopwatch devFSTimer;
Stopwatch vmReloadTimer;
......@@ -420,7 +420,7 @@ class HotRunner extends ResidentRunner {
vmReloadTimer = new Stopwatch();
reassembleTimer = new Stopwatch();
}
bool updatedDevFS = await _updateDevFS();
final bool updatedDevFS = await _updateDevFS();
if (benchmarkMode) {
devFSTimer.stop();
// Record time it took to synchronize to DevFS.
......@@ -431,12 +431,12 @@ class HotRunner extends ResidentRunner {
return new OperationResult(1, 'Dart Source Error');
String reloadMessage;
try {
String entryPath = fs.path.relative(mainPath, from: projectRootPath);
Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryPath));
Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
final String entryPath = fs.path.relative(mainPath, from: projectRootPath);
final Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryPath));
final Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
if (benchmarkMode)
vmReloadTimer.start();
Map<String, dynamic> reloadReport =
final Map<String, dynamic> reloadReport =
await currentView.uiIsolate.reloadSources(
pause: pause,
rootLibUri: deviceEntryUri,
......@@ -447,13 +447,13 @@ class HotRunner extends ResidentRunner {
return new OperationResult(1, 'reload rejected');
} else {
flutterUsage.sendEvent('hot', 'reload');
int loadedLibraryCount = reloadReport['details']['loadedLibraryCount'];
int finalLibraryCount = reloadReport['details']['finalLibraryCount'];
final int loadedLibraryCount = reloadReport['details']['loadedLibraryCount'];
final int finalLibraryCount = reloadReport['details']['finalLibraryCount'];
reloadMessage = 'Reloaded $loadedLibraryCount of $finalLibraryCount libraries';
}
} catch (error, st) {
int errorCode = error['code'];
String errorMessage = error['message'];
final int errorCode = error['code'];
final String errorMessage = error['message'];
if (errorCode == Isolate.kIsolateReloadBarred) {
printError('Unable to hot reload app due to an unrecoverable error in '
'the source code. Please address the error and then use '
......
......@@ -82,7 +82,7 @@ abstract class FlutterCommand extends Command<Null> {
}
BuildMode getBuildMode() {
List<bool> modeFlags = <bool>[argResults['debug'], argResults['profile'], argResults['release']];
final List<bool> modeFlags = <bool>[argResults['debug'], argResults['profile'], argResults['release']];
if (modeFlags.where((bool flag) => flag).length > 1)
throw new UsageException('Only one of --debug, --profile, or --release can be specified.', null);
if (argResults['debug'])
......@@ -110,14 +110,14 @@ abstract class FlutterCommand extends Command<Null> {
/// so that this method can record and report the overall time to analytics.
@override
Future<Null> run() {
Stopwatch stopwatch = new Stopwatch()..start();
UsageTimer analyticsTimer = usagePath == null ? null : flutterUsage.startTimer(name);
final Stopwatch stopwatch = new Stopwatch()..start();
final UsageTimer analyticsTimer = usagePath == null ? null : flutterUsage.startTimer(name);
if (flutterUsage.isFirstRun)
flutterUsage.printUsage();
return verifyThenRunCommand().whenComplete(() {
int ms = stopwatch.elapsedMilliseconds;
final int ms = stopwatch.elapsedMilliseconds;
printTrace("'flutter $name' took ${ms}ms.");
analyticsTimer?.finish();
});
......@@ -141,7 +141,7 @@ abstract class FlutterCommand extends Command<Null> {
setupApplicationPackages();
String commandPath = usagePath;
final String commandPath = usagePath;
if (commandPath != null)
flutterUsage.sendCommand(usagePath);
......@@ -234,14 +234,14 @@ abstract class FlutterCommand extends Command<Null> {
}
if (_usesTargetOption) {
String targetPath = targetFile;
final String targetPath = targetFile;
if (!fs.isFileSync(targetPath))
throw new ToolExit('Target file "$targetPath" not found.');
}
// Validate the current package map only if we will not be running "pub get" later.
if (!(_usesPubOption && argResults['pub'])) {
String error = new PackageMap(PackageMap.globalPackagesPath).checkValid();
final String error = new PackageMap(PackageMap.globalPackagesPath).checkValid();
if (error != null)
throw new ToolExit(error);
}
......
......@@ -130,7 +130,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
try {
if (platform.script.scheme == 'data')
return '../..'; // we're running as a test
String script = platform.script.toFilePath();
final String script = platform.script.toFilePath();
if (fs.path.basename(script) == kSnapshotFileName)
return fs.path.dirname(fs.path.dirname(fs.path.dirname(script)));
if (fs.path.basename(script) == kFlutterToolsScriptFileName)
......@@ -171,14 +171,14 @@ class FlutterCommandRunner extends CommandRunner<Null> {
if (globalResults['bug-report']) {
// --bug-report implies --record-to=<tmp_path>
Directory tmp = await const LocalFileSystem()
final Directory tmp = await const LocalFileSystem()
.systemTempDirectory
.createTemp('flutter_tools_');
recordTo = tmp.path;
// Record the arguments that were used to invoke this runner.
File manifest = tmp.childFile('MANIFEST.txt');
StringBuffer buffer = new StringBuffer()
final File manifest = tmp.childFile('MANIFEST.txt');
final StringBuffer buffer = new StringBuffer()
..writeln('# arguments')
..writeln(globalResults.arguments)
..writeln()
......@@ -188,7 +188,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
// ZIP the recording up once the recording has been serialized.
addShutdownHook(() async {
File zipFile = getUniqueFile(fs.currentDirectory, 'bugreport', 'zip');
final File zipFile = getUniqueFile(fs.currentDirectory, 'bugreport', 'zip');
os.zip(tmp, zipFile);
printStatus(
'Bug report written to ${zipFile.basename}.\n'
......@@ -244,7 +244,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
deviceManager.specifiedDeviceId = globalResults['device-id'];
// Set up the tooling configuration.
String enginePath = _findEnginePath(globalResults);
final String enginePath = _findEnginePath(globalResults);
if (enginePath != null) {
Artifacts.useLocalEngine(enginePath, _findEngineBuildPath(globalResults, enginePath));
}
......@@ -272,10 +272,10 @@ class FlutterCommandRunner extends CommandRunner<Null> {
if (engineSourcePath == null && globalResults['local-engine'] != null) {
try {
Uri engineUri = new PackageMap(PackageMap.globalPackagesPath).map[kFlutterEnginePackageName];
final Uri engineUri = new PackageMap(PackageMap.globalPackagesPath).map[kFlutterEnginePackageName];
if (engineUri != null) {
engineSourcePath = fs.path.dirname(fs.path.dirname(fs.path.dirname(fs.path.dirname(engineUri.path))));
bool dirExists = fs.isDirectorySync(fs.path.join(engineSourcePath, 'out'));
final bool dirExists = fs.isDirectorySync(fs.path.join(engineSourcePath, 'out'));
if (engineSourcePath == '/' || engineSourcePath.isEmpty || !dirExists)
engineSourcePath = null;
}
......@@ -312,7 +312,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
throw new ProcessExit(2);
}
String engineBuildPath = fs.path.normalize(fs.path.join(enginePath, 'out', localEngine));
final String engineBuildPath = fs.path.normalize(fs.path.join(enginePath, 'out', localEngine));
if (!fs.isDirectorySync(engineBuildPath)) {
printError('No Flutter engine build found at $engineBuildPath.');
throw new ProcessExit(2);
......@@ -385,7 +385,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
break;
}
String parent = fs.path.dirname(directory);
final String parent = fs.path.dirname(directory);
if (parent == directory)
break;
directory = parent;
......@@ -393,13 +393,13 @@ class FlutterCommandRunner extends CommandRunner<Null> {
// Check that the flutter running is that same as the one referenced in the pubspec.
if (fs.isFileSync(kPackagesFileName)) {
PackageMap packageMap = new PackageMap(kPackagesFileName);
Uri flutterUri = packageMap.map['flutter'];
final PackageMap packageMap = new PackageMap(kPackagesFileName);
final Uri flutterUri = packageMap.map['flutter'];
if (flutterUri != null && (flutterUri.scheme == 'file' || flutterUri.scheme == '')) {
// .../flutter/packages/flutter/lib
Uri rootUri = flutterUri.resolve('../../..');
String flutterPath = fs.path.normalize(fs.file(rootUri).absolute.path);
final Uri rootUri = flutterUri.resolve('../../..');
final String flutterPath = fs.path.normalize(fs.file(rootUri).absolute.path);
if (!fs.isDirectorySync(flutterPath)) {
printError(
......
......@@ -19,7 +19,7 @@ dynamic _loadYamlFile(String path) {
printTrace("Looking for YAML at '$path'");
if (!fs.isFileSync(path))
return null;
String manifestString = fs.file(path).readAsStringSync();
final String manifestString = fs.file(path).readAsStringSync();
return loadYaml(manifestString);
}
......@@ -51,8 +51,8 @@ Future<Null> parseServiceConfigs(
}
for (String service in manifest['services']) {
String serviceRoot = packageMap[service].path;
dynamic serviceConfig = _loadYamlFile('$serviceRoot/$_kFlutterServicesManifestPath');
final String serviceRoot = packageMap[service].path;
final dynamic serviceConfig = _loadYamlFile('$serviceRoot/$_kFlutterServicesManifestPath');
if (serviceConfig == null) {
printStatus('No $_kFlutterServicesManifestPath found for service "$serviceRoot"; skipping.');
continue;
......@@ -99,14 +99,14 @@ Future<String> getServiceFromUrl(
File generateServiceDefinitions(
String dir, List<Map<String, String>> servicesIn
) {
List<Map<String, String>> services =
final List<Map<String, String>> services =
servicesIn.map((Map<String, String> service) => <String, String>{
'name': service['name'],
'class': service['android-class']
}).toList();
Map<String, dynamic> json = <String, dynamic>{ 'services': services };
File servicesFile = fs.file(fs.path.join(dir, 'services.json'));
final Map<String, dynamic> json = <String, dynamic>{ 'services': services };
final File servicesFile = fs.file(fs.path.join(dir, 'services.json'));
servicesFile.writeAsStringSync(JSON.encode(json), mode: FileMode.WRITE, flush: true);
return servicesFile;
}
......@@ -30,7 +30,7 @@ class Template {
return;
}
List<FileSystemEntity> templateFiles = templateSource.listSync(recursive: true);
final List<FileSystemEntity> templateFiles = templateSource.listSync(recursive: true);
for (FileSystemEntity entity in templateFiles) {
if (entity is! File) {
......@@ -38,7 +38,7 @@ class Template {
continue;
}
String relativePath = fs.path.relative(entity.path,
final String relativePath = fs.path.relative(entity.path,
from: baseDir.absolute.path);
if (relativePath.contains(_kTemplateExtension)) {
......@@ -52,7 +52,7 @@ class Template {
factory Template.fromName(String name) {
// All named templates are placed in the 'templates' directory
Directory templateDir = _templateDirectoryInPackage(name);
final Directory templateDir = _templateDirectoryInPackage(name);
return new Template(templateDir, templateDir);
}
......@@ -67,7 +67,7 @@ class Template {
destination.createSync(recursive: true);
int fileCount = 0;
String destinationDirPath = destination.absolute.path;
final String destinationDirPath = destination.absolute.path;
_templateFilePaths.forEach((String relativeDestPath, String absoluteSrcPath) {
String finalDestinationPath = fs.path
......@@ -76,8 +76,8 @@ class Template {
.replaceAll(_kTemplateExtension, '');
if (projectName != null)
finalDestinationPath = finalDestinationPath.replaceAll('projectName', projectName);
File finalDestinationFile = fs.file(finalDestinationPath);
String relativePathForLogging = fs.path.relative(finalDestinationFile.path);
final File finalDestinationFile = fs.file(finalDestinationPath);
final String relativePathForLogging = fs.path.relative(finalDestinationFile.path);
// Step 1: Check if the file needs to be overwritten.
......@@ -97,7 +97,7 @@ class Template {
fileCount++;
finalDestinationFile.createSync(recursive: true);
File sourceFile = fs.file(absoluteSrcPath);
final File sourceFile = fs.file(absoluteSrcPath);
// Step 2: If the absolute paths ends with a 'copy.tmpl', this file does
// not need mustache rendering but needs to be directly copied.
......@@ -112,8 +112,8 @@ class Template {
// rendering via mustache.
if (sourceFile.path.endsWith(_kTemplateExtension)) {
String templateContents = sourceFile.readAsStringSync();
String renderedContents = new mustache.Template(templateContents).renderString(context);
final String templateContents = sourceFile.readAsStringSync();
final String renderedContents = new mustache.Template(templateContents).renderString(context);
finalDestinationFile.writeAsStringSync(renderedContents);
......@@ -131,7 +131,7 @@ class Template {
}
Directory _templateDirectoryInPackage(String name) {
String templatesDir = fs.path.join(Cache.flutterRoot,
final String templatesDir = fs.path.join(Cache.flutterRoot,
'packages', 'flutter_tools', 'templates');
return fs.directory(fs.path.join(templatesDir, name));
}
......@@ -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;
}
......
......@@ -102,20 +102,20 @@ class _FlutterPlatform extends PlatformPlugin {
if (_testCount > 0)
throwToolExit('installHook() was called with an observatory port, a diagnostic port, both, or debugger mode enabled, but then more than one test suite was run.');
}
int ourTestCount = _testCount;
final int ourTestCount = _testCount;
_testCount += 1;
StreamController<dynamic> localController = new StreamController<dynamic>();
StreamController<dynamic> remoteController = new StreamController<dynamic>();
Completer<Null> testCompleteCompleter = new Completer<Null>();
_FlutterPlatformStreamSinkWrapper<dynamic> remoteSink = new _FlutterPlatformStreamSinkWrapper<dynamic>(
final StreamController<dynamic> localController = new StreamController<dynamic>();
final StreamController<dynamic> remoteController = new StreamController<dynamic>();
final Completer<Null> testCompleteCompleter = new Completer<Null>();
final _FlutterPlatformStreamSinkWrapper<dynamic> remoteSink = new _FlutterPlatformStreamSinkWrapper<dynamic>(
remoteController.sink,
testCompleteCompleter.future,
);
StreamChannel<dynamic> localChannel = new StreamChannel<dynamic>.withGuarantees(
final StreamChannel<dynamic> localChannel = new StreamChannel<dynamic>.withGuarantees(
remoteController.stream,
localController.sink,
);
StreamChannel<dynamic> remoteChannel = new StreamChannel<dynamic>.withGuarantees(
final StreamChannel<dynamic> remoteChannel = new StreamChannel<dynamic>.withGuarantees(
localController.stream,
remoteSink,
);
......@@ -135,12 +135,12 @@ class _FlutterPlatform extends PlatformPlugin {
controller.sink.done.whenComplete(() { controllerSinkClosed = true; });
// Prepare our WebSocket server to talk to the engine subproces.
HttpServer server = await HttpServer.bind(_kHost, 0);
final HttpServer server = await HttpServer.bind(_kHost, 0);
finalizers.add(() async {
printTrace('test $ourTestCount: shutting down test harness socket server');
await server.close(force: true);
});
Completer<WebSocket> webSocket = new Completer<WebSocket>();
final Completer<WebSocket> webSocket = new Completer<WebSocket>();
server.listen(
(HttpRequest request) {
webSocket.complete(WebSocketTransformer.upgrade(request));
......@@ -159,14 +159,14 @@ class _FlutterPlatform extends PlatformPlugin {
);
// Prepare a temporary directory to store the Dart file that will talk to us.
Directory temporaryDirectory = fs.systemTempDirectory.createTempSync('dart_test_listener');
final Directory temporaryDirectory = fs.systemTempDirectory.createTempSync('dart_test_listener');
finalizers.add(() async {
printTrace('test $ourTestCount: deleting temporary directory');
temporaryDirectory.deleteSync(recursive: true);
});
// Prepare the Dart file that will talk to us and start the test.
File listenerFile = fs.file('${temporaryDirectory.path}/listener.dart');
final File listenerFile = fs.file('${temporaryDirectory.path}/listener.dart');
listenerFile.createSync();
listenerFile.writeAsStringSync(_generateTestMain(
testUrl: fs.path.toUri(fs.path.absolute(testPath)).toString(),
......@@ -175,7 +175,7 @@ class _FlutterPlatform extends PlatformPlugin {
// Start the engine subprocess.
printTrace('test $ourTestCount: starting shell process');
Process process = await _startProcess(
final Process process = await _startProcess(
shellPath,
listenerFile.path,
packages: PackageMap.globalPackagesPath,
......@@ -194,13 +194,13 @@ class _FlutterPlatform extends PlatformPlugin {
if (!controllerSinkClosed && exitCode != -15) { // ProcessSignal.SIGTERM
// We expect SIGTERM (15) because we tried to terminate it.
// It's negative because signals are returned as negative exit codes.
String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'after tests finished'), testPath, shellPath);
final String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'after tests finished'), testPath, shellPath);
controller.sink.addError(message);
}
}
});
Completer<Null> timeout = new Completer<Null>();
final Completer<Null> timeout = new Completer<Null>();
// Pipe stdout and stderr from the subprocess to our printStatus console.
// We also keep track of what observatory port the engine used, if any.
......@@ -232,7 +232,7 @@ class _FlutterPlatform extends PlatformPlugin {
// The local test harness could get bored of us.
printTrace('test $ourTestCount: awaiting initial result for pid ${process.pid}');
_InitialResult initialResult = await Future.any(<Future<_InitialResult>>[
final _InitialResult initialResult = await Future.any(<Future<_InitialResult>>[
process.exitCode.then<_InitialResult>((int exitCode) => _InitialResult.crashed),
timeout.future.then<_InitialResult>((Null _) => _InitialResult.timedOut),
new Future<_InitialResult>.delayed(_kTestProcessTimeout, () => _InitialResult.timedOut),
......@@ -242,9 +242,9 @@ class _FlutterPlatform extends PlatformPlugin {
switch (initialResult) {
case _InitialResult.crashed:
printTrace('test $ourTestCount: process with pid ${process.pid} crashed before connecting to test harness');
int exitCode = await process.exitCode;
final int exitCode = await process.exitCode;
subprocessActive = false;
String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before connecting to test harness'), testPath, shellPath);
final String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before connecting to test harness'), testPath, shellPath);
controller.sink.addError(message);
controller.sink.close();
printTrace('test $ourTestCount: waiting for controller sink to close');
......@@ -252,7 +252,7 @@ class _FlutterPlatform extends PlatformPlugin {
break;
case _InitialResult.timedOut:
printTrace('test $ourTestCount: timed out waiting for process with pid ${process.pid} to connect to test harness');
String message = _getErrorMessage('Test never connected to test harness.', testPath, shellPath);
final String message = _getErrorMessage('Test never connected to test harness.', testPath, shellPath);
controller.sink.addError(message);
controller.sink.close();
printTrace('test $ourTestCount: waiting for controller sink to close');
......@@ -260,10 +260,10 @@ class _FlutterPlatform extends PlatformPlugin {
break;
case _InitialResult.connected:
printTrace('test $ourTestCount: process with pid ${process.pid} connected to test harness');
WebSocket testSocket = await webSocket.future;
final WebSocket testSocket = await webSocket.future;
Completer<Null> harnessDone = new Completer<Null>();
StreamSubscription<dynamic> harnessToTest = controller.stream.listen(
final Completer<Null> harnessDone = new Completer<Null>();
final StreamSubscription<dynamic> harnessToTest = controller.stream.listen(
(dynamic event) { testSocket.add(JSON.encode(event)); },
onDone: () { harnessDone.complete(); },
onError: (dynamic error, dynamic stack) {
......@@ -279,8 +279,8 @@ class _FlutterPlatform extends PlatformPlugin {
cancelOnError: true,
);
Completer<Null> testDone = new Completer<Null>();
StreamSubscription<dynamic> testToHarness = testSocket.listen(
final Completer<Null> testDone = new Completer<Null>();
final StreamSubscription<dynamic> testToHarness = testSocket.listen(
(dynamic encodedEvent) {
assert(encodedEvent is String); // we shouldn't ever get binary messages
controller.sink.add(JSON.decode(encodedEvent));
......@@ -300,7 +300,7 @@ class _FlutterPlatform extends PlatformPlugin {
);
printTrace('test $ourTestCount: awaiting test result for pid ${process.pid}');
_TestResult testResult = await Future.any(<Future<_TestResult>>[
final _TestResult testResult = await Future.any(<Future<_TestResult>>[
process.exitCode.then<_TestResult>((int exitCode) { return _TestResult.crashed; }),
harnessDone.future.then<_TestResult>((Null _) { return _TestResult.harnessBailed; }),
testDone.future.then<_TestResult>((Null _) { return _TestResult.testBailed; }),
......@@ -312,9 +312,9 @@ class _FlutterPlatform extends PlatformPlugin {
switch (testResult) {
case _TestResult.crashed:
printTrace('test $ourTestCount: process with pid ${process.pid} crashed');
int exitCode = await process.exitCode;
final int exitCode = await process.exitCode;
subprocessActive = false;
String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before test harness closed its WebSocket'), testPath, shellPath);
final String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before test harness closed its WebSocket'), testPath, shellPath);
controller.sink.addError(message);
controller.sink.close();
printTrace('test $ourTestCount: waiting for controller sink to close');
......@@ -414,13 +414,13 @@ void main() {
if (_cachedFontConfig != null)
return _cachedFontConfig;
StringBuffer sb = new StringBuffer();
final StringBuffer sb = new StringBuffer();
sb.writeln('<fontconfig>');
sb.writeln(' <dir>${cache.getCacheArtifacts().path}</dir>');
sb.writeln(' <cachedir>/var/cache/fontconfig</cachedir>');
sb.writeln('</fontconfig>');
Directory fontsDir = fs.systemTempDirectory.createTempSync('flutter_fonts');
final Directory fontsDir = fs.systemTempDirectory.createTempSync('flutter_fonts');
_cachedFontConfig = fs.file('${fontsDir.path}/fonts.conf');
_cachedFontConfig.createSync();
_cachedFontConfig.writeAsStringSync(sb.toString());
......@@ -438,7 +438,7 @@ void main() {
}) {
assert(executable != null); // Please provide the path to the shell in the SKY_SHELL environment variable.
assert(!startPaused || enableObservatory);
List<String> command = <String>[executable];
final List<String> command = <String>[executable];
if (enableObservatory) {
// Some systems drive the _FlutterPlatform class in an unusual way, where
// only one test file is processed at a time, and the operating
......@@ -467,7 +467,7 @@ void main() {
testPath,
]);
printTrace(command.join(' '));
Map<String, String> environment = <String, String>{
final Map<String, String> environment = <String, String>{
'FLUTTER_TEST': 'true',
'FONTCONFIG_FILE': _fontConfigFile.path,
};
......@@ -497,7 +497,7 @@ void main() {
} else if (line.startsWith(observatoryPortString)) {
printTrace('Shell: $line');
try {
int port = int.parse(line.substring(observatoryPortString.length, line.length - 1)); // last character is a slash
final int port = int.parse(line.substring(observatoryPortString.length, line.length - 1)); // last character is a slash
if (reportObservatoryPort != null)
reportObservatoryPort(port);
} catch (error) {
......
......@@ -20,7 +20,7 @@ Usage get flutterUsage => Usage.instance;
class Usage {
/// Create a new Usage instance; [versionOverride] is used for testing.
Usage({ String settingsName: 'flutter', String versionOverride }) {
String version = versionOverride ?? FlutterVersion.getVersionString(whitelistBranchName: true);
final String version = versionOverride ?? FlutterVersion.getVersionString(whitelistBranchName: true);
_analytics = new AnalyticsIO(_kFlutterUA, settingsName, version);
bool runningOnCI = false;
......
......@@ -19,9 +19,9 @@ class FlutterVersion {
FlutterVersion(this.flutterRoot) {
_channel = _runGit('git rev-parse --abbrev-ref --symbolic @{u}');
int slash = _channel.indexOf('/');
final int slash = _channel.indexOf('/');
if (slash != -1) {
String remote = _channel.substring(0, slash);
final String remote = _channel.substring(0, slash);
_repositoryUrl = _runGit('git ls-remote --get-url $remote');
_channel = _channel.substring(slash + 1);
} else if (_channel.isEmpty) {
......@@ -59,10 +59,10 @@ class FlutterVersion {
@override
String toString() {
String flutterText = 'Flutter • channel $channel${repositoryUrl == null ? 'unknown source' : repositoryUrl}';
String frameworkText = 'Framework • revision $frameworkRevisionShort ($frameworkAge) • $frameworkCommitDate';
String engineText = 'Engine • revision $engineRevisionShort';
String toolsText = 'Tools • Dart $dartSdkVersion';
final String flutterText = 'Flutter • channel $channel${repositoryUrl == null ? 'unknown source' : repositoryUrl}';
final String frameworkText = 'Framework • revision $frameworkRevisionShort ($frameworkAge) • $frameworkCommitDate';
final String engineText = 'Engine • revision $engineRevisionShort';
final String toolsText = 'Tools • Dart $dartSdkVersion';
// Flutter • channel master • https://github.com/flutter/flutter.git
// Framework • revision 2259c59be8 • 19 minutes ago • 2016-08-15 22:51:40
......@@ -102,7 +102,7 @@ class FlutterVersion {
}
String _runSync(List<String> command, String cwd) {
ProcessResult results = processManager.runSync(command, workingDirectory: cwd);
final ProcessResult results = processManager.runSync(command, workingDirectory: cwd);
return results.exitCode == 0 ? results.stdout.trim() : '';
}
......
......@@ -54,9 +54,9 @@ class VMService {
/// non-empty directory as long as there is no collision with the
/// `"vmservice"` subdirectory.
static void enableRecordingConnection(String location) {
Directory dir = getRecordingSink(location, _kRecordingType);
final Directory dir = getRecordingSink(location, _kRecordingType);
_openChannel = (Uri uri) {
StreamChannel<String> delegate = _defaultOpenChannel(uri);
final StreamChannel<String> delegate = _defaultOpenChannel(uri);
return new RecordingVMServiceChannel(delegate, dir);
};
}
......@@ -67,7 +67,7 @@ class VMService {
/// activity has been recorded (i.e. the result of having been previously
/// passed to [enableRecordingConnection]), or a [ToolExit] will be thrown.
static void enableReplayConnection(String location) {
Directory dir = getReplaySource(location, _kRecordingType);
final Directory dir = getReplaySource(location, _kRecordingType);
_openChannel = (Uri uri) => new ReplayVMServiceChannel(dir);
}
......@@ -79,9 +79,9 @@ class VMService {
Uri httpUri, {
Duration requestTimeout: kDefaultRequestTimeout,
}) {
Uri wsUri = httpUri.replace(scheme: 'ws', path: fs.path.join(httpUri.path, 'ws'));
StreamChannel<String> channel = _openChannel(wsUri);
rpc.Peer peer = new rpc.Peer.withoutJson(jsonDocument.bind(channel));
final Uri wsUri = httpUri.replace(scheme: 'ws', path: fs.path.join(httpUri.path, 'ws'));
final StreamChannel<String> channel = _openChannel(wsUri);
final rpc.Peer peer = new rpc.Peer.withoutJson(jsonDocument.bind(channel));
return new VMService._(peer, httpUri, wsUri, requestTimeout);
}
......@@ -144,7 +144,7 @@ class VMService {
ServiceEvent event;
if (eventIsolate != null) {
// getFromMap creates the Isolate if necessary.
Isolate isolate = vm.getFromMap(eventIsolate);
final Isolate isolate = vm.getFromMap(eventIsolate);
event = new ServiceObject._fromMap(isolate, eventData);
if (event.kind == ServiceEvent.kIsolateExit) {
vm._isolateCache.remove(isolate.id);
......@@ -217,7 +217,7 @@ void _upgradeMap(Map<String, dynamic> map, ServiceObjectOwner owner) {
void _upgradeList(List<dynamic> list, ServiceObjectOwner owner) {
for (int i = 0; i < list.length; i++) {
dynamic v = list[i];
final dynamic v = list[i];
if ((v is Map<String, dynamic>) && _isServiceMap(v)) {
list[i] = owner.getFromMap(v);
} else if (v is List) {
......@@ -243,7 +243,7 @@ abstract class ServiceObject {
if (!_isServiceMap(map))
throw new VMServiceObjectLoadError("Expected a service map", map);
String type = _stripRef(map['type']);
final String type = _stripRef(map['type']);
ServiceObject serviceObject;
switch (type) {
......@@ -310,7 +310,7 @@ abstract class ServiceObject {
/// Fetch this object from vmService and return the response directly.
Future<Map<String, dynamic>> _fetchDirect() {
Map<String, dynamic> params = <String, dynamic>{
final Map<String, dynamic> params = <String, dynamic>{
'objectId': id,
};
return _owner.isolate.invokeRpcRaw('getObject', params: params);
......@@ -319,22 +319,22 @@ abstract class ServiceObject {
Future<ServiceObject> _inProgressReload;
/// Reload the service object (if possible).
Future<ServiceObject> reload() async {
bool hasId = (id != null) && (id != '');
bool isVM = this is VM;
final bool hasId = (id != null) && (id != '');
final bool isVM = this is VM;
// We should always reload the VM.
// We can't reload objects without an id.
// We shouldn't reload an immutable and already loaded object.
bool skipLoad = !isVM && (!hasId || (immutable && loaded));
final bool skipLoad = !isVM && (!hasId || (immutable && loaded));
if (skipLoad) {
return this;
}
if (_inProgressReload == null) {
Completer<ServiceObject> completer = new Completer<ServiceObject>();
final Completer<ServiceObject> completer = new Completer<ServiceObject>();
_inProgressReload = completer.future;
try {
Map<String, dynamic> response = await _fetchDirect();
final Map<String, dynamic> response = await _fetchDirect();
if (_stripRef(response['type']) == 'Sentinel') {
// An object may have been collected.
completer.complete(new ServiceObject._fromMap(owner, response));
......@@ -515,8 +515,8 @@ class VM extends ServiceObjectOwner {
final Map<String, FlutterView> _viewCache = new Map<String, FlutterView>();
int _compareIsolates(Isolate a, Isolate b) {
DateTime aStart = a.startTime;
DateTime bStart = b.startTime;
final DateTime aStart = a.startTime;
final DateTime bStart = b.startTime;
if (aStart == null) {
if (bStart == null) {
return 0;
......@@ -531,7 +531,7 @@ class VM extends ServiceObjectOwner {
}
void _buildIsolateList() {
List<Isolate> isolateList = _isolateCache.values.toList();
final List<Isolate> isolateList = _isolateCache.values.toList();
isolateList.sort(_compareIsolates);
isolates.clear();
isolates.addAll(isolateList);
......@@ -539,11 +539,11 @@ class VM extends ServiceObjectOwner {
void _removeDeadIsolates(List<Isolate> newIsolates) {
// Build a set of new isolates.
Set<String> newIsolateSet = new Set<String>();
final Set<String> newIsolateSet = new Set<String>();
newIsolates.forEach((Isolate iso) => newIsolateSet.add(iso.id));
// Remove any old isolates which no longer exist.
List<String> toRemove = <String>[];
final List<String> toRemove = <String>[];
_isolateCache.forEach((String id, _) {
if (!newIsolateSet.contains(id)) {
toRemove.add(id);
......@@ -558,14 +558,14 @@ class VM extends ServiceObjectOwner {
if (map == null) {
return null;
}
String type = _stripRef(map['type']);
final String type = _stripRef(map['type']);
if (type == 'VM') {
// Update this VM object.
update(map);
return this;
}
String mapId = map['id'];
final String mapId = map['id'];
switch (type) {
case 'Isolate': {
......@@ -627,7 +627,7 @@ class VM extends ServiceObjectOwner {
assert(params != null);
timeout ??= _vmService._requestTimeout;
try {
Map<String, dynamic> result = await _vmService
final Map<String, dynamic> result = await _vmService
._sendRequest(method, params)
.timeout(timeout);
return result;
......@@ -647,14 +647,14 @@ class VM extends ServiceObjectOwner {
Map<String, dynamic> params: const <String, dynamic>{},
Duration timeout,
}) async {
Map<String, dynamic> response = await invokeRpcRaw(
final Map<String, dynamic> response = await invokeRpcRaw(
method,
params: params,
timeout: timeout,
);
ServiceObject serviceObject = new ServiceObject._fromMap(this, response);
final ServiceObject serviceObject = new ServiceObject._fromMap(this, response);
if ((serviceObject != null) && (serviceObject._canCache)) {
String serviceObjectId = serviceObject.id;
final String serviceObjectId = serviceObject.id;
_cache.putIfAbsent(serviceObjectId, () => serviceObject);
}
return serviceObject;
......@@ -689,7 +689,7 @@ class VM extends ServiceObjectOwner {
// Read one file from a file system.
Future<List<int>> readDevFSFile(String fsName, String path) async {
Map<String, dynamic> response = await invokeRpcRaw(
final Map<String, dynamic> response = await invokeRpcRaw(
'_readDevFSFile',
params: <String, dynamic>{
'fsName': fsName,
......@@ -774,13 +774,13 @@ class Isolate extends ServiceObjectOwner {
if (map == null) {
return null;
}
String mapType = _stripRef(map['type']);
final String mapType = _stripRef(map['type']);
if (mapType == 'Isolate') {
// There are sometimes isolate refs in ServiceEvents.
return vm.getFromMap(map);
}
String mapId = map['id'];
final String mapId = map['id'];
ServiceObject serviceObject = (mapId != null) ? _cache[mapId] : null;
if (serviceObject != null) {
serviceObject.update(map);
......@@ -827,7 +827,7 @@ class Isolate extends ServiceObjectOwner {
return;
_loaded = true;
int startTimeMillis = map['startTime'];
final int startTimeMillis = map['startTime'];
startTime = new DateTime.fromMillisecondsSinceEpoch(startTimeMillis);
_upgradeCollection(map, this);
......@@ -842,7 +842,7 @@ class Isolate extends ServiceObjectOwner {
Uri rootLibUri,
Uri packagesUri}) async {
try {
Map<String, dynamic> arguments = <String, dynamic>{
final Map<String, dynamic> arguments = <String, dynamic>{
'pause': pause
};
// TODO(goderbauer): Transfer Uri (instead of file path) when remote end supports it.
......@@ -853,7 +853,7 @@ class Isolate extends ServiceObjectOwner {
if (packagesUri != null) {
arguments['packagesUri'] = packagesUri.toFilePath(windows: false);
}
Map<String, dynamic> response = await invokeRpcRaw('_reloadSources', params: arguments);
final Map<String, dynamic> response = await invokeRpcRaw('_reloadSources', params: arguments);
return response;
} on rpc.RpcException catch(e) {
return new Future<Map<String, dynamic>>.error(<String, dynamic>{
......@@ -952,7 +952,7 @@ class Isolate extends ServiceObjectOwner {
}
Future<Null> flutterPlatformOverride([String platform]) async {
Map<String, String> result = await invokeFlutterExtensionRpcRaw(
final Map<String, String> result = await invokeFlutterExtensionRpcRaw(
'ext.flutter.platformOverride',
params: platform != null ? <String, dynamic>{ 'value': platform } : <String, String>{},
timeout: const Duration(seconds: 5),
......
......@@ -35,8 +35,8 @@ class RecordingVMServiceChannel extends DelegatingStreamChannel<String> {
// purpose other than to make the serialized format more human-readable.
_messages.sort();
File file = _getManifest(location);
String json = new JsonEncoder.withIndent(' ').convert(_messages);
final File file = _getManifest(location);
final String json = new JsonEncoder.withIndent(' ').convert(_messages);
await file.writeAsString(json, flush: true);
}, ShutdownStage.SERIALIZE_RECORDING);
}
......@@ -83,7 +83,7 @@ abstract class _Message implements Comparable<_Message> {
@override
int compareTo(_Message other) {
int result = id.compareTo(other.id);
final int result = id.compareTo(other.id);
if (result != 0) {
return result;
} else if (type == _kRequest) {
......@@ -210,12 +210,12 @@ class ReplayVMServiceChannel extends StreamChannelMixin<String> {
: _transactions = _loadTransactions(location);
static Map<int, _Transaction> _loadTransactions(Directory location) {
File file = _getManifest(location);
String json = file.readAsStringSync();
Iterable<_Message> messages = JSON.decoder.convert(json).map<_Message>(_toMessage);
Map<int, _Transaction> transactions = <int, _Transaction>{};
final File file = _getManifest(location);
final String json = file.readAsStringSync();
final Iterable<_Message> messages = JSON.decoder.convert(json).map<_Message>(_toMessage);
final Map<int, _Transaction> transactions = <int, _Transaction>{};
for (_Message message in messages) {
_Transaction transaction =
final _Transaction transaction =
transactions.putIfAbsent(message.id, () => new _Transaction());
if (message.type == _kRequest) {
assert(transaction.request == null);
......@@ -235,7 +235,7 @@ class ReplayVMServiceChannel extends StreamChannelMixin<String> {
void send(_Request request) {
if (!_transactions.containsKey(request.id))
throw new ArgumentError('No matching invocation found');
_Transaction transaction = _transactions.remove(request.id);
final _Transaction transaction = _transactions.remove(request.id);
// TODO(tvolkert): validate that `transaction.request` matches `request`
if (transaction.response == null) {
// This signals that when we were recording, the VM shut down before
......@@ -295,6 +295,6 @@ class _ReplaySink implements StreamSink<String> {
}
File _getManifest(Directory location) {
String path = location.fileSystem.path.join(location.path, _kManifest);
final String path = location.fileSystem.path.join(location.path, _kManifest);
return location.fileSystem.file(path);
}
......@@ -31,7 +31,7 @@ class _ArchiveZipBuilder extends ZipBuilder {
@override
Future<Null> createZip(File outFile, Directory zipBuildDir) async {
Archive archive = new Archive();
final Archive archive = new Archive();
final Completer<Null> finished = new Completer<Null>();
int count = entries.length;
......@@ -45,7 +45,7 @@ class _ArchiveZipBuilder extends ZipBuilder {
});
await finished.future;
List<int> zipData = new ZipEncoder().encode(archive);
final List<int> zipData = new ZipEncoder().encode(archive);
await outFile.writeAsBytes(zipData);
}
}
......@@ -57,7 +57,7 @@ class _ZipToolBuilder extends ZipBuilder {
Future<Null> createZip(File outFile, Directory zipBuildDir) async {
// If there are no assets, then create an empty zip file.
if (entries.isEmpty) {
List<int> zipData = new ZipEncoder().encode(new Archive());
final List<int> zipData = new ZipEncoder().encode(new Archive());
await outFile.writeAsBytes(zipData);
return;
}
......@@ -73,7 +73,7 @@ class _ZipToolBuilder extends ZipBuilder {
int count = entries.length;
entries.forEach((String archivePath, DevFSContent content) {
content.contentsAsBytes().then<Null>((List<int> data) {
File file = fs.file(fs.path.join(zipBuildDir.path, archivePath));
final File file = fs.file(fs.path.join(zipBuildDir.path, archivePath));
file.parent.createSync(recursive: true);
file.writeAsBytes(data).then<Null>((File value) {
count -= 1;
......
......@@ -6,7 +6,7 @@ import 'package:flutter_tools/src/android/adb.dart';
import 'package:test/test.dart';
void main() {
Adb adb = new Adb('adb');
final Adb adb = new Adb('adb');
// We only test the [Adb] class is we're able to locate the adb binary.
if (!adb.exists())
......@@ -20,14 +20,14 @@ void main() {
test('getServerVersion', () async {
adb.startServer();
String version = await adb.getServerVersion();
final String version = await adb.getServerVersion();
expect(version, isNotEmpty);
});
test('listDevices', () async {
adb.startServer();
List<AdbDevice> devices = await adb.listDevices();
final List<AdbDevice> devices = await adb.listDevices();
// Any result is ok.
expect(devices, isList);
......
......@@ -33,7 +33,7 @@ void main() {
flutterUsage.onSend.listen((Map<String, dynamic> data) => count++);
flutterUsage.enabled = false;
CreateCommand command = new CreateCommand();
final CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['create', '--no-pub', temp.path]);
expect(count, 0);
......@@ -44,7 +44,7 @@ void main() {
count = 0;
flutterUsage.enabled = false;
DoctorCommand doctorCommand = new DoctorCommand();
final DoctorCommand doctorCommand = new DoctorCommand();
runner = createTestCommandRunner(doctorCommand);
await runner.run(<String>['doctor']);
expect(count, 0);
......@@ -58,8 +58,8 @@ void main() {
flutterUsage.onSend.listen((Map<String, dynamic> data) => count++);
flutterUsage.enabled = false;
ConfigCommand command = new ConfigCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final ConfigCommand command = new ConfigCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['config']);
expect(count, 0);
......
......@@ -37,7 +37,7 @@ void main() {
server = new AnalysisServer(dartSdkPath, <String>[tempDir.path]);
int errorCount = 0;
Future<bool> onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first;
final Future<bool> onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first;
server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length);
await server.start();
......@@ -57,7 +57,7 @@ void main() {
server = new AnalysisServer(dartSdkPath, <String>[tempDir.path]);
int errorCount = 0;
Future<bool> onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first;
final Future<bool> onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first;
server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length);
await server.start();
......@@ -70,12 +70,12 @@ void main() {
}
void _createSampleProject(Directory directory, { bool brokenCode: false }) {
File pubspecFile = fs.file(fs.path.join(directory.path, 'pubspec.yaml'));
final File pubspecFile = fs.file(fs.path.join(directory.path, 'pubspec.yaml'));
pubspecFile.writeAsStringSync('''
name: foo_project
''');
File dartFile = fs.file(fs.path.join(directory.path, 'lib', 'main.dart'));
final File dartFile = fs.file(fs.path.join(directory.path, 'lib', 'main.dart'));
dartFile.parent.createSync();
dartFile.writeAsStringSync('''
void main() {
......
......@@ -23,13 +23,13 @@ void main() {
group('analyze', () {
testUsingContext('flutter analyze with two files with the same name', () async {
File dartFileA = fs.file(fs.path.join(tempDir.path, 'a.dart'));
final File dartFileA = fs.file(fs.path.join(tempDir.path, 'a.dart'));
dartFileA.parent.createSync();
dartFileA.writeAsStringSync('library test;');
File dartFileB = fs.file(fs.path.join(tempDir.path, 'b.dart'));
final File dartFileB = fs.file(fs.path.join(tempDir.path, 'b.dart'));
dartFileB.writeAsStringSync('library test;');
AnalyzeCommand command = new AnalyzeCommand();
final AnalyzeCommand command = new AnalyzeCommand();
applyMocksToCommand(command);
return createTestCommandRunner(command).run(
<String>['analyze', '--no-current-package', '--no-current-directory', dartFileA.path, dartFileB.path]
......
......@@ -31,7 +31,7 @@ void main() {
expect(inRepo(<String>[Cache.flutterRoot]), isTrue);
expect(inRepo(<String>[fs.path.join(Cache.flutterRoot, 'foo')]), isTrue);
// Relative paths
String oldWorkingDirectory = fs.currentDirectory.path;
final String oldWorkingDirectory = fs.currentDirectory.path;
try {
fs.currentDirectory = Cache.flutterRoot;
expect(inRepo(<String>['.']), isTrue);
......
......@@ -10,15 +10,15 @@ import 'src/context.dart';
void main() {
group('android_device', () {
testUsingContext('stores the requested id', () {
String deviceId = '1234';
AndroidDevice device = new AndroidDevice(deviceId);
final String deviceId = '1234';
final AndroidDevice device = new AndroidDevice(deviceId);
expect(device.id, deviceId);
});
});
group('getAdbDevices', () {
testUsingContext('physical devices', () {
List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
final List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
List of devices attached
05a02bac device usb:336592896X product:razor model:Nexus_7 device:flo
......@@ -28,7 +28,7 @@ List of devices attached
});
testUsingContext('emulators and short listings', () {
List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
final List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
List of devices attached
localhost:36790 device
0149947A0D01500C device usb:340787200X
......@@ -40,7 +40,7 @@ emulator-5612 host features:shell_2
});
testUsingContext('android n', () {
List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
final List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
List of devices attached
ZX1G22JJWR device usb:3-3 product:shamu model:Nexus_6 device:shamu features:cmd,shell_v2
''');
......@@ -49,7 +49,7 @@ ZX1G22JJWR device usb:3-3 product:shamu model:Nexus_6 device:shamu f
});
testUsingContext('adb error message', () {
List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
final List<AndroidDevice> devices = getAdbDevices(mockAdbOutput: '''
It appears you do not have 'Android SDK Platform-tools' installed.
Use the 'android' tool to install them:
android update sdk --no-ui --filter 'platform-tools'
......@@ -61,7 +61,7 @@ Use the 'android' tool to install them:
group('parseAdbDeviceProperties', () {
test('parse adb shell output', () {
Map<String, String> properties = parseAdbDeviceProperties(kAdbShellGetprop);
final Map<String, String> properties = parseAdbDeviceProperties(kAdbShellGetprop);
expect(properties, isNotNull);
expect(properties['ro.build.characteristics'], 'emulator');
expect(properties['ro.product.cpu.abi'], 'x86_64');
......
......@@ -18,7 +18,7 @@ void main() {
testUsingContext('parse sdk', () {
sdkDir = _createSdkDirectory();
AndroidSdk sdk = new AndroidSdk(sdkDir.path);
final AndroidSdk sdk = new AndroidSdk(sdkDir.path);
expect(sdk.latestVersion, isNotNull);
expect(sdk.latestVersion.sdkLevel, 23);
......@@ -26,7 +26,7 @@ void main() {
testUsingContext('parse sdk N', () {
sdkDir = _createSdkDirectory(withAndroidN: true);
AndroidSdk sdk = new AndroidSdk(sdkDir.path);
final AndroidSdk sdk = new AndroidSdk(sdkDir.path);
expect(sdk.latestVersion, isNotNull);
expect(sdk.latestVersion.sdkLevel, 24);
......@@ -35,15 +35,15 @@ void main() {
group('android_sdk AndroidSdkVersion', () {
testUsingContext('parse normal', () {
AndroidSdk sdk = new AndroidSdk('.');
AndroidSdkVersion ver = new AndroidSdkVersion(sdk,
final AndroidSdk sdk = new AndroidSdk('.');
final AndroidSdkVersion ver = new AndroidSdkVersion(sdk,
platformVersionName: 'android-23', buildToolsVersionName: '23.0.0');
expect(ver.sdkLevel, 23);
});
testUsingContext('parse android n', () {
AndroidSdk sdk = new AndroidSdk('.');
AndroidSdkVersion ver = new AndroidSdkVersion(sdk,
final AndroidSdk sdk = new AndroidSdk('.');
final AndroidSdkVersion ver = new AndroidSdkVersion(sdk,
platformVersionName: 'android-N', buildToolsVersionName: '24.0.0');
expect(ver.sdkLevel, 24);
});
......@@ -51,7 +51,7 @@ void main() {
}
Directory _createSdkDirectory({ bool withAndroidN: false }) {
Directory dir = fs.systemTempDirectory.createTempSync('android-sdk');
final Directory dir = fs.systemTempDirectory.createTempSync('android-sdk');
_createSdkFile(dir, 'platform-tools/adb');
......@@ -70,6 +70,6 @@ Directory _createSdkDirectory({ bool withAndroidN: false }) {
}
void _createSdkFile(Directory dir, String filePath) {
File file = fs.file(fs.path.join(dir.path, filePath));
final File file = fs.file(fs.path.join(dir.path, filePath));
file.createSync(recursive: true);
}
......@@ -10,7 +10,7 @@ import 'src/context.dart';
void main() {
group('ApkManifestData', () {
testUsingContext('parse sdk', () {
ApkManifestData data = ApkManifestData.parseFromAaptBadging(_aaptData);
final ApkManifestData data = ApkManifestData.parseFromAaptBadging(_aaptData);
expect(data, isNotNull);
expect(data.packageName, 'io.flutter.gallery');
expect(data.launchableActivityName, 'io.flutter.app.FlutterActivity');
......
......@@ -10,12 +10,12 @@ import 'package:test/test.dart';
void main() {
// Create a temporary directory and write a single file into it.
FileSystem fs = const LocalFileSystem();
Directory tempDir = fs.systemTempDirectory.createTempSync();
String projectRoot = tempDir.path;
String assetPath = 'banana.txt';
String assetContents = 'banana';
File tempFile = fs.file(fs.path.join(projectRoot, assetPath));
final FileSystem fs = const LocalFileSystem();
final Directory tempDir = fs.systemTempDirectory.createTempSync();
final String projectRoot = tempDir.path;
final String assetPath = 'banana.txt';
final String assetContents = 'banana';
final File tempFile = fs.file(fs.path.join(projectRoot, assetPath));
tempFile.parent.createSync(recursive: true);
tempFile.writeAsBytesSync(UTF8.encode(assetContents));
......@@ -30,31 +30,31 @@ void main() {
expect(new AssetBundle.fixed(null, null).needsBuild(), isFalse);
});
test('empty string', () async {
AssetBundle ab = new AssetBundle.fixed('', '');
final AssetBundle ab = new AssetBundle.fixed('', '');
expect(ab.entries, isEmpty);
});
test('single entry', () async {
AssetBundle ab = new AssetBundle.fixed('', 'apple.txt');
final AssetBundle ab = new AssetBundle.fixed('', 'apple.txt');
expect(ab.entries, isNotEmpty);
expect(ab.entries.length, 1);
String archivePath = ab.entries.keys.first;
final String archivePath = ab.entries.keys.first;
expect(archivePath, isNotNull);
expect(archivePath, 'apple.txt');
});
test('two entries', () async {
AssetBundle ab = new AssetBundle.fixed('', 'apple.txt,packages/flutter_gallery_assets/shrine/products/heels.png');
final AssetBundle ab = new AssetBundle.fixed('', 'apple.txt,packages/flutter_gallery_assets/shrine/products/heels.png');
expect(ab.entries, isNotEmpty);
expect(ab.entries.length, 2);
List<String> archivePaths = ab.entries.keys.toList()..sort();
final List<String> archivePaths = ab.entries.keys.toList()..sort();
expect(archivePaths[0], 'apple.txt');
expect(archivePaths[1], 'packages/flutter_gallery_assets/shrine/products/heels.png');
});
test('file contents', () async {
AssetBundle ab = new AssetBundle.fixed(projectRoot, assetPath);
final AssetBundle ab = new AssetBundle.fixed(projectRoot, assetPath);
expect(ab.entries, isNotEmpty);
expect(ab.entries.length, 1);
String archivePath = ab.entries.keys.first;
DevFSContent content = ab.entries[archivePath];
final String archivePath = ab.entries.keys.first;
final DevFSContent content = ab.entries[archivePath];
expect(archivePath, assetPath);
expect(assetContents, UTF8.decode(await content.contentsAsBytes()));
});
......@@ -62,7 +62,7 @@ void main() {
group('AssetBundle.build', () {
test('nonempty', () async {
AssetBundle ab = new AssetBundle();
final AssetBundle ab = new AssetBundle();
expect(await ab.build(), 0);
expect(ab.entries.length, greaterThan(0));
});
......
......@@ -10,19 +10,19 @@ import 'package:test/test.dart';
void main() {
group('ItemListNotifier', () {
test('sends notifications', () async {
ItemListNotifier<String> list = new ItemListNotifier<String>();
final ItemListNotifier<String> list = new ItemListNotifier<String>();
expect(list.items, isEmpty);
Future<List<String>> addedStreamItems = list.onAdded.toList();
Future<List<String>> removedStreamItems = list.onRemoved.toList();
final Future<List<String>> addedStreamItems = list.onAdded.toList();
final Future<List<String>> removedStreamItems = list.onRemoved.toList();
list.updateWithNewList(<String>['aaa']);
list.updateWithNewList(<String>['aaa', 'bbb']);
list.updateWithNewList(<String>['bbb']);
list.dispose();
List<String> addedItems = await addedStreamItems;
List<String> removedItems = await removedStreamItems;
final List<String> addedItems = await addedStreamItems;
final List<String> removedItems = await removedStreamItems;
expect(addedItems.length, 2);
expect(addedItems.first, 'aaa');
......
......@@ -12,8 +12,8 @@ import 'src/context.dart';
void main() {
group('channel', () {
testUsingContext('list', () async {
ChannelCommand command = new ChannelCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final ChannelCommand command = new ChannelCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['channel']);
expect(testLogger.errorText, hasLength(0));
// The bots may return an empty list of channels (network hiccup?)
......
......@@ -10,8 +10,8 @@ void main() {
Config config;
setUp(() {
Directory tempDiretory = fs.systemTempDirectory.createTempSync('flutter_test');
File file = fs.file(fs.path.join(tempDiretory.path, '.settings'));
final Directory tempDiretory = fs.systemTempDirectory.createTempSync('flutter_test');
final File file = fs.file(fs.path.join(tempDiretory.path, '.settings'));
config = new Config(file);
});
......
......@@ -11,8 +11,8 @@ import 'package:test/test.dart';
void main() {
group('AppContext', () {
test('error', () async {
AppContext context = new AppContext();
BufferLogger mockLogger = new BufferLogger();
final AppContext context = new AppContext();
final BufferLogger mockLogger = new BufferLogger();
context.setVariable(Logger, mockLogger);
await context.runInZone(() {
......@@ -25,8 +25,8 @@ void main() {
});
test('status', () async {
AppContext context = new AppContext();
BufferLogger mockLogger = new BufferLogger();
final AppContext context = new AppContext();
final BufferLogger mockLogger = new BufferLogger();
context.setVariable(Logger, mockLogger);
await context.runInZone(() {
......@@ -39,8 +39,8 @@ void main() {
});
test('trace', () async {
AppContext context = new AppContext();
BufferLogger mockLogger = new BufferLogger();
final AppContext context = new AppContext();
final BufferLogger mockLogger = new BufferLogger();
context.setVariable(Logger, mockLogger);
await context.runInZone(() {
......@@ -53,11 +53,11 @@ void main() {
});
test('awaitNestedZones', () async {
AppContext outerContext = new AppContext();
final AppContext outerContext = new AppContext();
await outerContext.runInZone(() async {
AppContext middleContext = new AppContext();
final AppContext middleContext = new AppContext();
await middleContext.runInZone(() async {
AppContext innerContext = new AppContext();
final AppContext innerContext = new AppContext();
await innerContext.runInZone(() async {
expect(innerContext.getVariable(String), isNull);
});
......@@ -66,11 +66,11 @@ void main() {
});
test('fireAndForgetNestedZones', () async {
AppContext outerContext = new AppContext();
final AppContext outerContext = new AppContext();
outerContext.runInZone(() async {
AppContext middleContext = new AppContext();
final AppContext middleContext = new AppContext();
middleContext.runInZone(() async {
AppContext innerContext = new AppContext();
final AppContext innerContext = new AppContext();
innerContext.runInZone(() async {
expect(innerContext.getVariable(String), isNull);
});
......@@ -80,15 +80,15 @@ void main() {
test('overriddenValuesInNestedZones', () async {
expect(pkg.context, isNull);
AppContext outerContext = new AppContext();
final AppContext outerContext = new AppContext();
outerContext.setVariable(String, 'outer');
outerContext.runInZone(() async {
expect(pkg.context[String], 'outer');
AppContext middleContext = new AppContext();
final AppContext middleContext = new AppContext();
middleContext.setVariable(String, 'middle');
middleContext.runInZone(() async {
expect(pkg.context[String], 'middle');
AppContext innerContext = new AppContext();
final AppContext innerContext = new AppContext();
innerContext.setVariable(String, 'inner');
innerContext.runInZone(() async {
expect(pkg.context[String], 'inner');
......
......@@ -50,7 +50,7 @@ void main() {
);
}));
int exitCode = await tools.run(
final int exitCode = await tools.run(
<String>['crash'],
<FlutterCommand>[new _CrashCommand()],
reportCrashes: true,
......@@ -71,12 +71,12 @@ void main() {
'version' : 'test-version',
},
));
BufferLogger logger = context[Logger];
final BufferLogger logger = context[Logger];
expect(logger.statusText, 'Sending crash report to Google.\n'
'Crash report sent (report ID: test-report-id)\n');
// Verify that we've written the crash report to disk.
List<String> writtenFiles =
final List<String> writtenFiles =
(await tools.crashFileSystem.directory('/').list(recursive: true).toList())
.map((FileSystemEntity e) => e.path).toList();
expect(writtenFiles, hasLength(1));
......
......@@ -42,8 +42,8 @@ void main() {
testUsingContext('content', () async {
Cache.flutterRoot = '../..';
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['create', '--no-pub', temp.path]);
......@@ -53,14 +53,14 @@ void main() {
expectExists('lib/main.dart');
for (FileSystemEntity file in temp.listSync(recursive: true)) {
if (file is File && file.path.endsWith('.dart')) {
String original= file.readAsStringSync();
final String original= file.readAsStringSync();
Process process = await Process.start(
final Process process = await Process.start(
sdkBinaryName('dartfmt'),
<String>[file.path],
workingDirectory: temp.path,
);
String formatted =
final String formatted =
await process.stdout.transform(UTF8.decoder).join();
expect(original, formatted, reason: file.path);
......@@ -68,10 +68,10 @@ void main() {
}
// Generated Xcode settings
String xcodeConfigPath = fs.path.join('ios', 'Flutter', 'Generated.xcconfig');
final String xcodeConfigPath = fs.path.join('ios', 'Flutter', 'Generated.xcconfig');
expectExists(xcodeConfigPath);
File xcodeConfigFile = fs.file(fs.path.join(temp.path, xcodeConfigPath));
String xcodeConfig = xcodeConfigFile.readAsStringSync();
final File xcodeConfigFile = fs.file(fs.path.join(temp.path, xcodeConfigPath));
final String xcodeConfig = xcodeConfigFile.readAsStringSync();
expect(xcodeConfig, contains('FLUTTER_ROOT='));
expect(xcodeConfig, contains('FLUTTER_APPLICATION_PATH='));
expect(xcodeConfig, contains('FLUTTER_FRAMEWORK_DIR='));
......@@ -81,8 +81,8 @@ void main() {
testUsingContext('can re-gen over existing project', () async {
Cache.flutterRoot = '../..';
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['create', '--no-pub', temp.path]);
......@@ -93,8 +93,8 @@ void main() {
testUsingContext('produces sensible error message', () async {
Cache.flutterRoot = '../..';
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
try {
await runner.run(<String>['create', temp.path, '--pub']);
......@@ -108,9 +108,9 @@ void main() {
// Verify that we fail with an error code when the file exists.
testUsingContext('fails when file exists', () async {
Cache.flutterRoot = '../..';
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
File existingFile = fs.file("${temp.path.toString()}/bad");
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
final File existingFile = fs.file("${temp.path.toString()}/bad");
if (!existingFile.existsSync()) existingFile.createSync();
try {
await runner.run(<String>['create', existingFile.path]);
......@@ -124,17 +124,17 @@ void main() {
Future<Null> _createAndAnalyzeProject(Directory dir, List<String> createArgs) async {
Cache.flutterRoot = '../..';
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
List<String> args = <String>['create'];
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
final List<String> args = <String>['create'];
args.addAll(createArgs);
args.add(dir.path);
await runner.run(args);
String mainPath = fs.path.join(dir.path, 'lib', 'main.dart');
final String mainPath = fs.path.join(dir.path, 'lib', 'main.dart');
expect(fs.file(mainPath).existsSync(), true);
String flutterToolsPath = fs.path.absolute(fs.path.join('bin', 'flutter_tools.dart'));
ProcessResult exec = Process.runSync(
final String flutterToolsPath = fs.path.absolute(fs.path.join('bin', 'flutter_tools.dart'));
final ProcessResult exec = Process.runSync(
'$dartSdkPath/bin/dart', <String>[flutterToolsPath, 'analyze'],
workingDirectory: dir.path
);
......
......@@ -47,15 +47,15 @@ void main() {
});
_testUsingContext('daemon.version', () async {
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
notifyingLogger: notifyingLogger
);
commands.add(<String, dynamic>{'id': 0, 'method': 'daemon.version'});
Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
final Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
expect(response['id'], 0);
expect(response['result'], isNotEmpty);
expect(response['result'] is String, true);
......@@ -65,20 +65,20 @@ void main() {
_testUsingContext('daemon.logMessage', () {
return appContext.runInZone(() async {
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
notifyingLogger: notifyingLogger
);
printError('daemon.logMessage test');
Map<String, dynamic> response = await responses.stream.where((Map<String, dynamic> map) {
final Map<String, dynamic> response = await responses.stream.where((Map<String, dynamic> map) {
return map['event'] == 'daemon.logMessage' && map['params']['level'] == 'error';
}).first;
expect(response['id'], isNull);
expect(response['event'], 'daemon.logMessage');
Map<String, String> logMessage = response['params'];
final Map<String, String> logMessage = response['params'];
expect(logMessage['level'], 'error');
expect(logMessage['message'], 'daemon.logMessage test');
responses.close();
......@@ -87,12 +87,12 @@ void main() {
});
_testUsingContext('daemon.logMessage logToStdout', () async {
StringBuffer buffer = new StringBuffer();
final StringBuffer buffer = new StringBuffer();
await runZoned(() async {
return appContext.runInZone(() async {
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
......@@ -111,8 +111,8 @@ void main() {
});
_testUsingContext('daemon.shutdown', () async {
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
......@@ -127,11 +127,11 @@ void main() {
});
_testUsingContext('daemon.start', () async {
DaemonCommand command = new DaemonCommand();
final DaemonCommand command = new DaemonCommand();
applyMocksToCommand(command);
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
......@@ -140,7 +140,7 @@ void main() {
);
commands.add(<String, dynamic>{ 'id': 0, 'method': 'app.start' });
Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
final Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
expect(response['id'], 0);
expect(response['error'], contains('deviceId is required'));
responses.close();
......@@ -148,11 +148,11 @@ void main() {
});
_testUsingContext('daemon.restart', () async {
DaemonCommand command = new DaemonCommand();
final DaemonCommand command = new DaemonCommand();
applyMocksToCommand(command);
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
......@@ -161,7 +161,7 @@ void main() {
);
commands.add(<String, dynamic>{ 'id': 0, 'method': 'app.restart' });
Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
final Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
expect(response['id'], 0);
expect(response['error'], contains('appId is required'));
responses.close();
......@@ -169,11 +169,11 @@ void main() {
});
_testUsingContext('daemon.callServiceExtension', () async {
DaemonCommand command = new DaemonCommand();
final DaemonCommand command = new DaemonCommand();
applyMocksToCommand(command);
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
......@@ -188,7 +188,7 @@ void main() {
'methodName': 'ext.flutter.debugPaint'
}
});
Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
final Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
expect(response['id'], 0);
expect(response['error'], contains('appId is required'));
responses.close();
......@@ -196,11 +196,11 @@ void main() {
});
_testUsingContext('daemon.stop', () async {
DaemonCommand command = new DaemonCommand();
final DaemonCommand command = new DaemonCommand();
applyMocksToCommand(command);
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
......@@ -209,7 +209,7 @@ void main() {
);
commands.add(<String, dynamic>{ 'id': 0, 'method': 'app.stop' });
Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
final Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
expect(response['id'], 0);
expect(response['error'], contains('appId is required'));
responses.close();
......@@ -217,15 +217,15 @@ void main() {
});
_testUsingContext('device.getDevices', () async {
StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> commands = new StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = new StreamController<Map<String, dynamic>>();
daemon = new Daemon(
commands.stream,
(Map<String, dynamic> result) => responses.add(result),
notifyingLogger: notifyingLogger
);
commands.add(<String, dynamic>{'id': 0, 'method': 'device.getDevices'});
Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
final Map<String, dynamic> response = await responses.stream.where(_notEvent).first;
expect(response['id'], 0);
expect(response['result'], isList);
responses.close();
......
......@@ -16,9 +16,9 @@ void main() {
final String testPath = fs.path.join(dataPath, 'good');
final String mainPath = fs.path.join(testPath, 'main.dart');
final String packagesPath = fs.path.join(testPath, '.packages');
DartDependencySetBuilder builder =
final DartDependencySetBuilder builder =
new DartDependencySetBuilder(mainPath, testPath, packagesPath);
Set<String> dependencies = builder.build();
final Set<String> dependencies = builder.build();
expect(dependencies.contains(mainPath), isTrue);
expect(dependencies.contains(fs.path.join(testPath, 'foo.dart')), isTrue);
});
......@@ -26,7 +26,7 @@ void main() {
final String testPath = fs.path.join(dataPath, 'syntax_error');
final String mainPath = fs.path.join(testPath, 'main.dart');
final String packagesPath = fs.path.join(testPath, '.packages');
DartDependencySetBuilder builder =
final DartDependencySetBuilder builder =
new DartDependencySetBuilder(mainPath, testPath, packagesPath);
try {
builder.build();
......
......@@ -30,13 +30,13 @@ void main() {
final String fooPath = fs.path.join(testPath, 'foo.dart');
final String barPath = fs.path.join(testPath, 'lib', 'bar.dart');
final String packagesPath = fs.path.join(testPath, '.packages');
DartDependencySetBuilder builder =
final DartDependencySetBuilder builder =
new DartDependencySetBuilder(mainPath, testPath, packagesPath);
DependencyChecker dependencyChecker =
final DependencyChecker dependencyChecker =
new DependencyChecker(builder, null);
// Set file modification time on all dependencies to be in the past.
DateTime baseTime = new DateTime.now();
final DateTime baseTime = new DateTime.now();
updateFileModificationTime(packagesPath, baseTime, -10);
updateFileModificationTime(mainPath, baseTime, -10);
updateFileModificationTime(fooPath, baseTime, -10);
......@@ -62,12 +62,12 @@ void main() {
final String fooPath = fs.path.join(testPath, 'foo.dart');
final String packagesPath = fs.path.join(testPath, '.packages');
DartDependencySetBuilder builder =
final DartDependencySetBuilder builder =
new DartDependencySetBuilder(mainPath, testPath, packagesPath);
DependencyChecker dependencyChecker =
final DependencyChecker dependencyChecker =
new DependencyChecker(builder, null);
DateTime baseTime = new DateTime.now();
final DateTime baseTime = new DateTime.now();
// Set file modification time on all dependencies to be in the past.
updateFileModificationTime(packagesPath, baseTime, -10);
......@@ -84,10 +84,10 @@ void main() {
/// Tests that the flutter tool doesn't crash and displays a warning when its own location
/// changed since it was last referenced to in a package's .packages file.
testUsingContext('moved flutter sdk', () async {
Directory destinationPath = fs.systemTempDirectory.createTempSync('dependency_checker_test_');
final Directory destinationPath = fs.systemTempDirectory.createTempSync('dependency_checker_test_');
// Copy the golden input and let the test run in an isolated temporary in-memory file system.
LocalFileSystem localFileSystem = const LocalFileSystem();
Directory sourcePath = localFileSystem.directory(localFileSystem.path.join(dataPath, 'changed_sdk_location'));
final LocalFileSystem localFileSystem = const LocalFileSystem();
final Directory sourcePath = localFileSystem.directory(localFileSystem.path.join(dataPath, 'changed_sdk_location'));
copyDirectorySync(sourcePath, destinationPath);
fs.currentDirectory = destinationPath;
......
......@@ -27,7 +27,7 @@ void main() {
group('DevFSContent', () {
test('bytes', () {
DevFSByteContent content = new DevFSByteContent(<int>[4, 5, 6]);
final DevFSByteContent content = new DevFSByteContent(<int>[4, 5, 6]);
expect(content.bytes, orderedEquals(<int>[4, 5, 6]));
expect(content.isModified, isTrue);
expect(content.isModified, isFalse);
......@@ -37,7 +37,7 @@ void main() {
expect(content.isModified, isFalse);
});
test('string', () {
DevFSStringContent content = new DevFSStringContent('some string');
final DevFSStringContent content = new DevFSStringContent('some string');
expect(content.string, 'some string');
expect(content.bytes, orderedEquals(UTF8.encode('some string')));
expect(content.isModified, isTrue);
......@@ -56,7 +56,7 @@ void main() {
});
group('devfs local', () {
MockDevFSOperations devFSOperations = new MockDevFSOperations();
final MockDevFSOperations devFSOperations = new MockDevFSOperations();
setUpAll(() {
tempDir = _newTempDir();
......@@ -66,7 +66,7 @@ void main() {
testUsingContext('create dev file system', () async {
// simulate workspace
File file = fs.file(fs.path.join(basePath, filePath));
final File file = fs.file(fs.path.join(basePath, filePath));
await file.parent.create(recursive: true);
file.writeAsBytesSync(<int>[1, 2, 3]);
_packages['my_project'] = fs.path.toUri('lib');
......@@ -79,7 +79,7 @@ void main() {
devFSOperations.expectMessages(<String>['create test']);
expect(devFS.assetPathsToEvict, isEmpty);
int bytes = await devFS.update();
final int bytes = await devFS.update();
devFSOperations.expectMessages(<String>[
'writeFile test .packages',
'writeFile test lib/foo.txt',
......@@ -87,7 +87,7 @@ void main() {
]);
expect(devFS.assetPathsToEvict, isEmpty);
List<String> packageSpecOnDevice = LineSplitter.split(UTF8.decode(
final List<String> packageSpecOnDevice = LineSplitter.split(UTF8.decode(
await devFSOperations.devicePathToContent[fs.path.toUri('.packages')].contentsAsBytes()
)).toList();
expect(packageSpecOnDevice,
......@@ -97,10 +97,10 @@ void main() {
expect(bytes, 48);
});
testUsingContext('add new file to local file system', () async {
File file = fs.file(fs.path.join(basePath, filePath2));
final File file = fs.file(fs.path.join(basePath, filePath2));
await file.parent.create(recursive: true);
file.writeAsBytesSync(<int>[1, 2, 3, 4, 5, 6, 7]);
int bytes = await devFS.update();
final int bytes = await devFS.update();
devFSOperations.expectMessages(<String>[
'writeFile test foo/bar.txt',
]);
......@@ -108,7 +108,7 @@ void main() {
expect(bytes, 7);
});
testUsingContext('modify existing file on local file system', () async {
File file = fs.file(fs.path.join(basePath, filePath));
final File file = fs.file(fs.path.join(basePath, filePath));
// Set the last modified time to 5 seconds in the past.
updateFileModificationTime(file.path, new DateTime.now(), -5);
int bytes = await devFS.update();
......@@ -125,9 +125,9 @@ void main() {
expect(bytes, 6);
});
testUsingContext('delete a file from the local file system', () async {
File file = fs.file(fs.path.join(basePath, filePath));
final File file = fs.file(fs.path.join(basePath, filePath));
await file.delete();
int bytes = await devFS.update();
final int bytes = await devFS.update();
devFSOperations.expectMessages(<String>[
'deleteFile test lib/foo.txt',
]);
......@@ -136,7 +136,7 @@ void main() {
});
testUsingContext('add new package', () async {
await _createPackage('newpkg', 'anotherfile.txt');
int bytes = await devFS.update();
final int bytes = await devFS.update();
devFSOperations.expectMessages(<String>[
'writeFile test .packages',
'writeFile test packages/newpkg/anotherfile.txt',
......@@ -146,7 +146,7 @@ void main() {
});
testUsingContext('add an asset bundle', () async {
assetBundle.entries['a.txt'] = new DevFSStringContent('abc');
int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true);
final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true);
devFSOperations.expectMessages(<String>[
'writeFile test ${_inAssetBuildDirectory('a.txt')}',
]);
......@@ -156,7 +156,7 @@ void main() {
});
testUsingContext('add a file to the asset bundle - bundleDirty', () async {
assetBundle.entries['b.txt'] = new DevFSStringContent('abcd');
int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true);
final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true);
// Expect entire asset bundle written because bundleDirty is true
devFSOperations.expectMessages(<String>[
'writeFile test ${_inAssetBuildDirectory('a.txt')}',
......@@ -169,7 +169,7 @@ void main() {
});
testUsingContext('add a file to the asset bundle', () async {
assetBundle.entries['c.txt'] = new DevFSStringContent('12');
int bytes = await devFS.update(bundle: assetBundle);
final int bytes = await devFS.update(bundle: assetBundle);
devFSOperations.expectMessages(<String>[
'writeFile test ${_inAssetBuildDirectory('c.txt')}',
]);
......@@ -180,7 +180,7 @@ void main() {
});
testUsingContext('delete a file from the asset bundle', () async {
assetBundle.entries.remove('c.txt');
int bytes = await devFS.update(bundle: assetBundle);
final int bytes = await devFS.update(bundle: assetBundle);
devFSOperations.expectMessages(<String>[
'deleteFile test ${_inAssetBuildDirectory('c.txt')}',
]);
......@@ -190,7 +190,7 @@ void main() {
});
testUsingContext('delete all files from the asset bundle', () async {
assetBundle.entries.clear();
int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true);
final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true);
devFSOperations.expectMessages(<String>[
'deleteFile test ${_inAssetBuildDirectory('a.txt')}',
'deleteFile test ${_inAssetBuildDirectory('b.txt')}',
......@@ -224,7 +224,7 @@ void main() {
testUsingContext('create dev file system', () async {
// simulate workspace
File file = fs.file(fs.path.join(basePath, filePath));
final File file = fs.file(fs.path.join(basePath, filePath));
await file.parent.create(recursive: true);
file.writeAsBytesSync(<int>[1, 2, 3]);
......@@ -236,7 +236,7 @@ void main() {
vmService.expectMessages(<String>['create test']);
expect(devFS.assetPathsToEvict, isEmpty);
int bytes = await devFS.update();
final int bytes = await devFS.update();
vmService.expectMessages(<String>[
'writeFile test .packages',
'writeFile test lib/foo.txt',
......@@ -273,8 +273,8 @@ class MockVMService extends BasicMock implements VMService {
_server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 0);
_httpAddress = Uri.parse('http://127.0.0.1:${_server.port}');
_server.listen((HttpRequest request) {
String fsName = request.headers.value('dev_fs_name');
String devicePath = UTF8.decode(BASE64.decode(request.headers.value('dev_fs_path_b64')));
final String fsName = request.headers.value('dev_fs_name');
final String devicePath = UTF8.decode(BASE64.decode(request.headers.value('dev_fs_path_b64')));
messages.add('writeFile $fsName $devicePath');
request.drain<List<int>>().then<Null>((List<int> value) {
request.response
......@@ -323,7 +323,7 @@ final List<Directory> _tempDirs = <Directory>[];
final Map <String, Uri> _packages = <String, Uri>{};
Directory _newTempDir() {
Directory tempDir = fs.systemTempDirectory.createTempSync('devfs${_tempDirs.length}');
final Directory tempDir = fs.systemTempDirectory.createTempSync('devfs${_tempDirs.length}');
_tempDirs.add(tempDir);
return tempDir;
}
......@@ -336,11 +336,11 @@ void _cleanupTempDirs() {
Future<Null> _createPackage(String pkgName, String pkgFileName) async {
final Directory pkgTempDir = _newTempDir();
File pkgFile = fs.file(fs.path.join(pkgTempDir.path, pkgName, 'lib', pkgFileName));
final File pkgFile = fs.file(fs.path.join(pkgTempDir.path, pkgName, 'lib', pkgFileName));
await pkgFile.parent.create(recursive: true);
pkgFile.writeAsBytesSync(<int>[11, 12, 13]);
_packages[pkgName] = fs.path.toUri(pkgFile.parent.path);
StringBuffer sb = new StringBuffer();
final StringBuffer sb = new StringBuffer();
_packages.forEach((String pkgName, Uri pkgUri) {
sb.writeln('$pkgName:$pkgUri');
});
......
......@@ -13,17 +13,17 @@ void main() {
group('DeviceManager', () {
testUsingContext('getDevices', () async {
// Test that DeviceManager.getDevices() doesn't throw.
DeviceManager deviceManager = new DeviceManager();
List<Device> devices = await deviceManager.getDevices();
final DeviceManager deviceManager = new DeviceManager();
final List<Device> devices = await deviceManager.getDevices();
expect(devices, isList);
});
testUsingContext('getDeviceById', () async {
_MockDevice device1 = new _MockDevice('Nexus 5', '0553790d0a4e726f');
_MockDevice device2 = new _MockDevice('Nexus 5X', '01abfc49119c410e');
_MockDevice device3 = new _MockDevice('iPod touch', '82564b38861a9a5');
List<Device> devices = <Device>[device1, device2, device3];
DeviceManager deviceManager = new TestDeviceManager(devices);
final _MockDevice device1 = new _MockDevice('Nexus 5', '0553790d0a4e726f');
final _MockDevice device2 = new _MockDevice('Nexus 5X', '01abfc49119c410e');
final _MockDevice device3 = new _MockDevice('iPod touch', '82564b38861a9a5');
final List<Device> devices = <Device>[device1, device2, device3];
final DeviceManager deviceManager = new TestDeviceManager(devices);
Future<Null> expectDevice(String id, List<Device> expected) async {
expect(await deviceManager.getDevicesById(id), expected);
......
......@@ -13,12 +13,12 @@ import 'src/context.dart';
void main() {
group('devices', () {
testUsingContext('returns 0 when called', () async {
DevicesCommand command = new DevicesCommand();
final DevicesCommand command = new DevicesCommand();
await createTestCommandRunner(command).run(<String>['devices']);
});
testUsingContext('no error when no connected devices', () async {
DevicesCommand command = new DevicesCommand();
final DevicesCommand command = new DevicesCommand();
await createTestCommandRunner(command).run(<String>['devices']);
expect(testLogger.statusText, contains('No devices detected'));
}, overrides: <Type, Generator>{
......
......@@ -11,7 +11,7 @@ import 'src/context.dart';
void main() {
group('doctor', () {
testUsingContext('intellij validator', () async {
ValidationResult result = await new IntelliJValidatorTestTarget('Test').validate();
final ValidationResult result = await new IntelliJValidatorTestTarget('Test').validate();
expect(result.type, ValidationType.installed);
expect(result.statusInfo, 'version test.test.test');
expect(result.messages, hasLength(2));
......
......@@ -68,10 +68,10 @@ void main() {
testUsingContext('returns 1 when test file is not found', () async {
withMockDevice();
String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart');
String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
List<String> args = <String>[
final List<String> args = <String>[
'drive',
'--target=$testApp}',
];
......@@ -90,14 +90,14 @@ void main() {
withMockDevice();
appStarter = expectAsync1((DriveCommand command) async => null);
String testApp = fs.path.join(cwd.path, 'test_driver', 'e2e.dart');
String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
final String testApp = fs.path.join(cwd.path, 'test_driver', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
MemoryFileSystem memFs = fs;
final MemoryFileSystem memFs = fs;
await memFs.file(testApp).writeAsString('main() { }');
await memFs.file(testFile).writeAsString('main() { }');
List<String> args = <String>[
final List<String> args = <String>[
'drive',
'--target=$testApp',
];
......@@ -113,8 +113,8 @@ void main() {
});
testUsingContext('returns 1 when app file is outside package', () async {
String appFile = fs.path.join(cwd.dirname, 'other_app', 'app.dart');
List<String> args = <String>[
final String appFile = fs.path.join(cwd.dirname, 'other_app', 'app.dart');
final List<String> args = <String>[
'drive',
'--target=$appFile',
];
......@@ -132,8 +132,8 @@ void main() {
});
testUsingContext('returns 1 when app file is in the root dir', () async {
String appFile = fs.path.join(cwd.path, 'main.dart');
List<String> args = <String>[
final String appFile = fs.path.join(cwd.path, 'main.dart');
final List<String> args = <String>[
'drive',
'--target=$appFile',
];
......@@ -154,8 +154,8 @@ void main() {
testUsingContext('returns 0 when test ends successfully', () async {
withMockDevice();
String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart');
String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
appStarter = expectAsync1((DriveCommand command) async {
return new LaunchResult.succeeded();
......@@ -168,11 +168,11 @@ void main() {
return true;
});
MemoryFileSystem memFs = fs;
final MemoryFileSystem memFs = fs;
await memFs.file(testApp).writeAsString('main() {}');
await memFs.file(testFile).writeAsString('main() {}');
List<String> args = <String>[
final List<String> args = <String>[
'drive',
'--target=$testApp',
];
......@@ -185,8 +185,8 @@ void main() {
testUsingContext('returns exitCode set by test runner', () async {
withMockDevice();
String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart');
String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart');
appStarter = expectAsync1((DriveCommand command) async {
return new LaunchResult.succeeded();
......@@ -198,11 +198,11 @@ void main() {
return true;
});
MemoryFileSystem memFs = fs;
final MemoryFileSystem memFs = fs;
await memFs.file(testApp).writeAsString('main() {}');
await memFs.file(testFile).writeAsString('main() {}');
List<String> args = <String>[
final List<String> args = <String>[
'drive',
'--target=$testApp',
];
......@@ -224,7 +224,7 @@ void main() {
when(mockDevice.name).thenReturn('specified-device');
when(mockDevice.id).thenReturn('123');
Device device = await findTargetDevice();
final Device device = await findTargetDevice();
expect(device.name, 'specified-device');
}, overrides: <Type, Generator>{
FileSystem: () => fs,
......@@ -239,7 +239,7 @@ void main() {
when(mockDevice.name).thenReturn('mock-simulator');
when(mockDevice.isLocalEmulator).thenReturn(true);
Device device = await findTargetDevice();
final Device device = await findTargetDevice();
expect(device.name, 'mock-simulator');
}, overrides: <Type, Generator>{
FileSystem: () => fs,
......@@ -252,7 +252,7 @@ void main() {
when(mockDevice.isLocalEmulator).thenReturn(false);
withMockDevice(mockDevice);
Device device = await findTargetDevice();
final Device device = await findTargetDevice();
expect(device.name, 'mock-android-device');
}, overrides: <Type, Generator>{
FileSystem: () => fs,
......@@ -261,12 +261,12 @@ void main() {
testUsingContext('launches emulator', () async {
when(SimControl.instance.boot()).thenReturn(true);
Device emulator = new MockDevice();
final Device emulator = new MockDevice();
when(emulator.name).thenReturn('new-simulator');
when(IOSSimulatorUtils.instance.getAttachedDevices())
.thenReturn(<Device>[emulator]);
Device device = await findTargetDevice();
final Device device = await findTargetDevice();
expect(device.name, 'new-simulator');
}, overrides: <Type, Generator>{
FileSystem: () => fs,
......@@ -291,7 +291,7 @@ void main() {
when(mockDevice.name).thenReturn('mock-android-device');
withMockDevice(mockDevice);
Device device = await findTargetDevice();
final Device device = await findTargetDevice();
expect(device.name, 'mock-android-device');
}, overrides: <Type, Generator>{
FileSystem: () => fs,
......
......@@ -8,10 +8,10 @@ import 'package:test/test.dart';
void main() {
setUp(() {
String flutterRoot = platform.environment['FLUTTER_ROOT'];
final String flutterRoot = platform.environment['FLUTTER_ROOT'];
if (flutterRoot == null)
throw new Exception('Please set FLUTTER_ROOT env var before running tests.');
String flutterTools = fs.path.join(flutterRoot, 'packages', 'flutter_tools');
final String flutterTools = fs.path.join(flutterRoot, 'packages', 'flutter_tools');
assert(fs.path.equals(fs.currentDirectory.path, flutterTools));
});
......
......@@ -28,8 +28,8 @@ void main() {
});
Future<Null> createProject() async {
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['create', '--no-pub', temp.path]);
}
......@@ -37,15 +37,15 @@ void main() {
testUsingContext('a file', () async {
await createProject();
File srcFile = fs.file(fs.path.join(temp.path, 'lib', 'main.dart'));
String original = srcFile.readAsStringSync();
final File srcFile = fs.file(fs.path.join(temp.path, 'lib', 'main.dart'));
final String original = srcFile.readAsStringSync();
srcFile.writeAsStringSync(original.replaceFirst('main()', 'main( )'));
FormatCommand command = new FormatCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final FormatCommand command = new FormatCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['format', srcFile.path]);
String formatted = srcFile.readAsStringSync();
final String formatted = srcFile.readAsStringSync();
expect(formatted, original);
});
});
......
......@@ -13,10 +13,10 @@ import 'src/mocks.dart';
void main() {
group('install', () {
testUsingContext('returns 0 when Android is connected and ready for an install', () async {
InstallCommand command = new InstallCommand();
final InstallCommand command = new InstallCommand();
applyMocksToCommand(command);
MockAndroidDevice device = new MockAndroidDevice();
final MockAndroidDevice device = new MockAndroidDevice();
when(device.isAppInstalled(any)).thenReturn(false);
when(device.installApp(any)).thenReturn(true);
testDeviceManager.addDevice(device);
......@@ -25,10 +25,10 @@ void main() {
});
testUsingContext('returns 0 when iOS is connected and ready for an install', () async {
InstallCommand command = new InstallCommand();
final InstallCommand command = new InstallCommand();
applyMocksToCommand(command);
MockIOSDevice device = new MockIOSDevice();
final MockIOSDevice device = new MockIOSDevice();
when(device.isAppInstalled(any)).thenReturn(false);
when(device.installApp(any)).thenReturn(true);
testDeviceManager.addDevice(device);
......
......@@ -13,7 +13,7 @@ import 'src/mocks.dart';
void main() {
group('logs', () {
testUsingContext('fail with a bad device id', () async {
LogsCommand command = new LogsCommand();
final LogsCommand command = new LogsCommand();
applyMocksToCommand(command);
try {
await createTestCommandRunner(command).run(<String>['-d', 'abc123', 'logs']);
......
......@@ -22,13 +22,13 @@ void main() {
});
testUsingContext('makeExecutable', () async {
File file = fs.file(fs.path.join(temp.path, 'foo.script'));
final File file = fs.file(fs.path.join(temp.path, 'foo.script'));
file.writeAsStringSync('hello world');
os.makeExecutable(file);
// Skip this test on windows.
if (!platform.isWindows) {
String mode = file.statSync().modeString();
final String mode = file.statSync().modeString();
// rwxr--r--
expect(mode.substring(0, 3), endsWith('x'));
}
......
......@@ -26,8 +26,8 @@ void main() {
});
Future<Null> createProject() async {
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['create', '--no-pub', temp.path]);
}
......@@ -35,8 +35,8 @@ void main() {
Future<Null> runCommand(String verb) async {
await createProject();
PackagesCommand command = new PackagesCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final PackagesCommand command = new PackagesCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['packages', verb, temp.path]);
}
......
......@@ -14,8 +14,8 @@ import 'src/mocks.dart';
void main() {
group('service_protocol discovery', () {
testUsingContext('no port forwarding', () async {
MockDeviceLogReader logReader = new MockDeviceLogReader();
ProtocolDiscovery discoverer =
final MockDeviceLogReader logReader = new MockDeviceLogReader();
final ProtocolDiscovery discoverer =
new ProtocolDiscovery(logReader, ProtocolDiscovery.kObservatoryService);
// Get next port future.
......@@ -41,8 +41,8 @@ void main() {
nextUri = discoverer.nextUri();
// Inject a bad line.
logReader.addLine('Observatory listening on http://127.0.0.1:apple');
Uri timeoutUri = Uri.parse('http://timeout');
Uri actualUri = await nextUri.timeout(
final Uri timeoutUri = Uri.parse('http://timeout');
final Uri actualUri = await nextUri.timeout(
const Duration(milliseconds: 100), onTimeout: () => timeoutUri);
expect(actualUri, timeoutUri);
......@@ -72,17 +72,17 @@ void main() {
});
testUsingContext('port forwarding - default port', () async {
MockDeviceLogReader logReader = new MockDeviceLogReader();
ProtocolDiscovery discoverer = new ProtocolDiscovery(
final MockDeviceLogReader logReader = new MockDeviceLogReader();
final ProtocolDiscovery discoverer = new ProtocolDiscovery(
logReader,
ProtocolDiscovery.kObservatoryService,
portForwarder: new MockPortForwarder(99),
defaultHostPort: 54777);
// Get next port future.
Future<Uri> nextUri = discoverer.nextUri();
final Future<Uri> nextUri = discoverer.nextUri();
logReader.addLine('I/flutter : Observatory listening on http://somehost:54804/PTwjm8Ii8qg=/');
Uri uri = await nextUri;
final Uri uri = await nextUri;
expect(uri.port, 54777);
expect('$uri', 'http://somehost:54777/PTwjm8Ii8qg=/');
......@@ -91,8 +91,8 @@ void main() {
});
testUsingContext('port forwarding - specified port', () async {
MockDeviceLogReader logReader = new MockDeviceLogReader();
ProtocolDiscovery discoverer = new ProtocolDiscovery(
final MockDeviceLogReader logReader = new MockDeviceLogReader();
final ProtocolDiscovery discoverer = new ProtocolDiscovery(
logReader,
ProtocolDiscovery.kObservatoryService,
portForwarder: new MockPortForwarder(99),
......@@ -100,9 +100,9 @@ void main() {
defaultHostPort: 192);
// Get next port future.
Future<Uri> nextUri = discoverer.nextUri();
final Future<Uri> nextUri = discoverer.nextUri();
logReader.addLine('I/flutter : Observatory listening on http://somehost:54804/PTwjm8Ii8qg=/');
Uri uri = await nextUri;
final Uri uri = await nextUri;
expect(uri.port, 1243);
expect('$uri', 'http://somehost:1243/PTwjm8Ii8qg=/');
......
......@@ -13,7 +13,7 @@ import 'src/mocks.dart';
void main() {
group('run', () {
testUsingContext('fails when target not found', () async {
RunCommand command = new RunCommand();
final RunCommand command = new RunCommand();
applyMocksToCommand(command);
try {
await createTestCommandRunner(command).run(<String>['run', '-t', 'abc123']);
......
......@@ -32,19 +32,19 @@ void main() {
/// Test file_systems.copyDirectorySync() using MemoryFileSystem.
/// Copies between 2 instances of file systems which is also supported by copyDirectorySync().
test('test directory copy', () async {
MemoryFileSystem sourceMemoryFs = new MemoryFileSystem();
String sourcePath = '/some/origin';
Directory sourceDirectory = await sourceMemoryFs.directory(sourcePath).create(recursive: true);
final MemoryFileSystem sourceMemoryFs = new MemoryFileSystem();
final String sourcePath = '/some/origin';
final Directory sourceDirectory = await sourceMemoryFs.directory(sourcePath).create(recursive: true);
sourceMemoryFs.currentDirectory = sourcePath;
File sourceFile1 = sourceMemoryFs.file('some_file.txt')..writeAsStringSync('bleh');
DateTime writeTime = sourceFile1.lastModifiedSync();
final File sourceFile1 = sourceMemoryFs.file('some_file.txt')..writeAsStringSync('bleh');
final DateTime writeTime = sourceFile1.lastModifiedSync();
sourceMemoryFs.file('sub_dir/another_file.txt').createSync(recursive: true);
sourceMemoryFs.directory('empty_directory').createSync();
// Copy to another memory file system instance.
MemoryFileSystem targetMemoryFs = new MemoryFileSystem();
String targetPath = '/some/non-existent/target';
Directory targetDirectory = targetMemoryFs.directory(targetPath);
final MemoryFileSystem targetMemoryFs = new MemoryFileSystem();
final String targetPath = '/some/non-existent/target';
final Directory targetDirectory = targetMemoryFs.directory(targetPath);
copyDirectorySync(sourceDirectory, targetDirectory);
expect(targetDirectory.existsSync(), true);
......
......@@ -11,7 +11,7 @@ import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/runner/flutter_command_runner.dart';
CommandRunner<Null> createTestCommandRunner([FlutterCommand command]) {
FlutterCommandRunner runner = new FlutterCommandRunner();
final FlutterCommandRunner runner = new FlutterCommandRunner();
if (command != null)
runner.addCommand(command);
return runner;
......@@ -21,7 +21,7 @@ CommandRunner<Null> createTestCommandRunner([FlutterCommand command]) {
void updateFileModificationTime(String path,
DateTime baseTime,
int seconds) {
DateTime modificationTime = baseTime.add(new Duration(seconds: seconds));
final DateTime modificationTime = baseTime.add(new Duration(seconds: seconds));
fs.file(path).setLastModifiedSync(modificationTime);
}
......
......@@ -38,7 +38,7 @@ void testUsingContext(String description, dynamic testMethod(), {
bool skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this
}) {
test(description, () async {
AppContext testContext = new AppContext();
final AppContext testContext = new AppContext();
// Initialize the test context with some default mocks.
// Seed these context entries first since others depend on them
......@@ -58,7 +58,7 @@ void testUsingContext(String description, dynamic testMethod(), {
testContext.putIfAbsent(OperatingSystemUtils, () => new MockOperatingSystemUtils());
testContext.putIfAbsent(Xcode, () => new Xcode());
testContext.putIfAbsent(IOSSimulatorUtils, () {
MockIOSSimulatorUtils mock = new MockIOSSimulatorUtils();
final MockIOSSimulatorUtils mock = new MockIOSSimulatorUtils();
when(mock.getAttachedDevices()).thenReturn(<IOSSimulator>[]);
return mock;
});
......@@ -82,7 +82,7 @@ void testUsingContext(String description, dynamic testMethod(), {
});
} catch (error) {
if (testContext[Logger] is BufferLogger) {
BufferLogger bufferLogger = testContext[Logger];
final BufferLogger bufferLogger = testContext[Logger];
if (bufferLogger.errorText.isNotEmpty)
print(bufferLogger.errorText);
}
......
......@@ -21,27 +21,27 @@ void main() {
testUsingContext('Emit missing status when nothing is installed', () async {
when(xcode.isInstalled).thenReturn(false);
when(xcode.xcodeSelectPath).thenReturn(null);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
..hasPythonSixModule = false
..hasHomebrew = false
..hasIosDeploy = false;
ValidationResult result = await workflow.validate();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.missing);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
testUsingContext('Emits partial status when Xcode is not installed', () async {
when(xcode.isInstalled).thenReturn(false);
when(xcode.xcodeSelectPath).thenReturn(null);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
ValidationResult result = await workflow.validate();
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
testUsingContext('Emits partial status when Xcode is partially installed', () async {
when(xcode.isInstalled).thenReturn(false);
when(xcode.xcodeSelectPath).thenReturn('/Library/Developer/CommandLineTools');
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
ValidationResult result = await workflow.validate();
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
......@@ -51,8 +51,8 @@ void main() {
.thenReturn('Xcode 7.0.1\nBuild version 7C1002\n');
when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(false);
when(xcode.eulaSigned).thenReturn(true);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
ValidationResult result = await workflow.validate();
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
......@@ -62,8 +62,8 @@ void main() {
.thenReturn('Xcode 8.2.1\nBuild version 8C1002\n');
when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true);
when(xcode.eulaSigned).thenReturn(false);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
ValidationResult result = await workflow.validate();
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
......@@ -73,9 +73,9 @@ void main() {
.thenReturn('Xcode 8.2.1\nBuild version 8C1002\n');
when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true);
when(xcode.eulaSigned).thenReturn(true);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
..hasPythonSixModule = false;
ValidationResult result = await workflow.validate();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
......@@ -85,9 +85,9 @@ void main() {
.thenReturn('Xcode 8.2.1\nBuild version 8C1002\n');
when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true);
when(xcode.eulaSigned).thenReturn(true);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
..hasHomebrew = false;
ValidationResult result = await workflow.validate();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
......@@ -97,9 +97,9 @@ void main() {
.thenReturn('Xcode 8.2.1\nBuild version 8C1002\n');
when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true);
when(xcode.eulaSigned).thenReturn(true);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
..hasIosDeploy = false;
ValidationResult result = await workflow.validate();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
......@@ -109,9 +109,9 @@ void main() {
.thenReturn('Xcode 8.2.1\nBuild version 8C1002\n');
when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true);
when(xcode.eulaSigned).thenReturn(true);
IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget()
..iosDeployVersionText = '1.8.0';
ValidationResult result = await workflow.validate();
final ValidationResult result = await workflow.validate();
expect(result.type, ValidationType.partial);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
......@@ -121,7 +121,7 @@ void main() {
.thenReturn('Xcode 8.2.1\nBuild version 8C1002\n');
when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true);
when(xcode.eulaSigned).thenReturn(true);
ValidationResult result = await new IOSWorkflowTestTarget().validate();
final ValidationResult result = await new IOSWorkflowTestTarget().validate();
expect(result.type, ValidationType.installed);
}, overrides: <Type, Generator>{ Xcode: () => xcode });
});
......
......@@ -18,7 +18,7 @@ void main() {
group('compareIosVersions', () {
test('compares correctly', () {
// This list must be sorted in ascending preference order
List<String> testList = <String>[
final List<String> testList = <String>[
'8', '8.0', '8.1', '8.2',
'9', '9.0', '9.1', '9.2',
'10', '10.0', '10.1',
......@@ -40,7 +40,7 @@ void main() {
group('compareIphoneVersions', () {
test('compares correctly', () {
// This list must be sorted in ascending preference order
List<String> testList = <String>[
final List<String> testList = <String>[
'com.apple.CoreSimulator.SimDeviceType.iPhone-4s',
'com.apple.CoreSimulator.SimDeviceType.iPhone-5',
'com.apple.CoreSimulator.SimDeviceType.iPhone-5s',
......@@ -132,7 +132,7 @@ void main() {
when(mockXcode.xcodeMajorVersion).thenReturn(8);
when(mockXcode.xcodeMinorVersion).thenReturn(2);
expect(deviceUnderTest.supportsScreenshot, true);
MockFile mockFile = new MockFile();
final MockFile mockFile = new MockFile();
when(mockFile.path).thenReturn(fs.path.join('some', 'path', 'to', 'screenshot.png'));
deviceUnderTest.takeScreenshot(mockFile);
verify(mockProcessManager.runSync(
......
......@@ -80,7 +80,7 @@ class BasicMock {
final List<String> messages = new List<String>();
void expectMessages(List<String> expectedMessages) {
List<String> actualMessages = new List<String>.from(messages);
final List<String> actualMessages = new List<String>.from(messages);
messages.clear();
expect(actualMessages, unorderedEquals(expectedMessages));
}
......@@ -88,7 +88,7 @@ class BasicMock {
bool contains(String match) {
print('Checking for `$match` in:');
print(messages);
bool result = messages.contains(match);
final bool result = messages.contains(match);
messages.clear();
return result;
}
......
......@@ -15,18 +15,18 @@ import 'src/mocks.dart';
void main() {
group('stop', () {
testUsingContext('returns 0 when Android is connected and ready to be stopped', () async {
StopCommand command = new StopCommand();
final StopCommand command = new StopCommand();
applyMocksToCommand(command);
MockAndroidDevice device = new MockAndroidDevice();
final MockAndroidDevice device = new MockAndroidDevice();
when(device.stopApp(any)).thenReturn(new Future<bool>.value(true));
testDeviceManager.addDevice(device);
await createTestCommandRunner(command).run(<String>['stop']);
});
testUsingContext('returns 0 when iOS is connected and ready to be stopped', () async {
StopCommand command = new StopCommand();
final StopCommand command = new StopCommand();
applyMocksToCommand(command);
MockIOSDevice device = new MockIOSDevice();
final MockIOSDevice device = new MockIOSDevice();
when(device.stopApp(any)).thenReturn(new Future<bool>.value(true));
testDeviceManager.addDevice(device);
......
......@@ -13,7 +13,7 @@ import 'src/mocks.dart';
void main() {
group('trace', () {
testUsingContext('returns 1 when no Android device is connected', () async {
TraceCommand command = new TraceCommand();
final TraceCommand command = new TraceCommand();
applyMocksToCommand(command);
try {
await createTestCommandRunner(command).run(<String>['trace']);
......
......@@ -47,19 +47,19 @@ void main() {
});
Future<Null> createProject() async {
CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command);
final CreateCommand command = new CreateCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command);
await runner.run(<String>['create', '--no-pub', temp.path]);
}
testUsingContext('in project', () async {
await createProject();
String proj = temp.path;
final String proj = temp.path;
expect(findProjectRoot(proj), proj);
expect(findProjectRoot(fs.path.join(proj, 'lib')), proj);
String hello = fs.path.join(Cache.flutterRoot, 'examples', 'hello_world');
final String hello = fs.path.join(Cache.flutterRoot, 'examples', 'hello_world');
expect(findProjectRoot(hello), hello);
expect(findProjectRoot(fs.path.join(hello, 'lib')), hello);
});
......
......@@ -9,7 +9,7 @@ import 'package:test/test.dart';
void main() {
group('SettingsFile', () {
test('parse', () {
SettingsFile file = new SettingsFile.parse('''
final SettingsFile file = new SettingsFile.parse('''
# ignore comment
foo=bar
baz=qux
......@@ -23,8 +23,8 @@ baz=qux
group('uuid', () {
// xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
test('simple', () {
Uuid uuid = new Uuid();
String result = uuid.generateV4();
final Uuid uuid = new Uuid();
final String result = uuid.generateV4();
expect(result.length, 36);
expect(result[8], '-');
expect(result[13], '-');
......@@ -33,8 +33,8 @@ baz=qux
});
test('can parse', () {
Uuid uuid = new Uuid();
String result = uuid.generateV4();
final Uuid uuid = new Uuid();
final String result = uuid.generateV4();
expect(int.parse(result.substring(0, 8), radix: 16), isNotNull);
expect(int.parse(result.substring(9, 13), radix: 16), isNotNull);
expect(int.parse(result.substring(14, 18), radix: 16), isNotNull);
......@@ -43,7 +43,7 @@ baz=qux
});
test('special bits', () {
Uuid uuid = new Uuid();
final Uuid uuid = new Uuid();
String result = uuid.generateV4();
expect(result[14], '4');
expect(result[19].toLowerCase(), isIn('89ab'));
......@@ -56,25 +56,25 @@ baz=qux
});
test('is pretty random', () {
Set<String> set = new Set<String>();
final Set<String> set = new Set<String>();
Uuid uuid = new Uuid();
for (int i = 0; i < 64; i++) {
String val = uuid.generateV4();
final String val = uuid.generateV4();
expect(set, isNot(contains(val)));
set.add(val);
}
uuid = new Uuid();
for (int i = 0; i < 64; i++) {
String val = uuid.generateV4();
final String val = uuid.generateV4();
expect(set, isNot(contains(val)));
set.add(val);
}
uuid = new Uuid();
for (int i = 0; i < 64; i++) {
String val = uuid.generateV4();
final String val = uuid.generateV4();
expect(set, isNot(contains(val)));
set.add(val);
}
......@@ -86,30 +86,30 @@ baz=qux
expect(Version.unknown.toString(), equals('unknown'));
expect(new Version(null, null, null).toString(), equals('0'));
Version v1 = new Version.parse('1');
final Version v1 = new Version.parse('1');
expect(v1.major, equals(1));
expect(v1.minor, equals(0));
expect(v1.patch, equals(0));
expect(v1, greaterThan(Version.unknown));
Version v2 = new Version.parse('1.2');
final Version v2 = new Version.parse('1.2');
expect(v2.major, equals(1));
expect(v2.minor, equals(2));
expect(v2.patch, equals(0));
Version v3 = new Version.parse('1.2.3');
final Version v3 = new Version.parse('1.2.3');
expect(v3.major, equals(1));
expect(v3.minor, equals(2));
expect(v3.patch, equals(3));
Version v4 = new Version.parse('1.12');
final Version v4 = new Version.parse('1.12');
expect(v4, greaterThan(v2));
expect(v3, greaterThan(v2));
expect(v2, greaterThan(v1));
Version v5 = new Version(1, 2, 0, text: 'foo');
final Version v5 = new Version(1, 2, 0, text: 'foo');
expect(v5, equals(v2));
expect(new Version.parse('Preview2.2'), isNull);
......
......@@ -28,7 +28,7 @@ Future<Null> main() async {
stdout.write('> ');
stdin.transform(UTF8.decoder).transform(const LineSplitter()).listen((String line) {
List<String> words = line.split(' ');
final List<String> words = line.split(' ');
if (line == 'version' || line == 'v') {
_send(<String, dynamic>{'method': 'daemon.version'});
......@@ -80,7 +80,7 @@ int id = 0;
void _send(Map<String, dynamic> map) {
map['id'] = id++;
String str = '[${JSON.encode(map)}]';
final String str = '[${JSON.encode(map)}]';
daemon.stdin.writeln(str);
print('==> $str');
}
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