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