Commit 8bb27034 authored by Todd Volkert's avatar Todd Volkert Committed by GitHub

Update flutter_tools to use package:file throughout (#7385)

This removes direct file access from within flutter_tools
in favor of using `package:file` via a `FileSystem` that's
accessed via the `ApplicationContext`.

This lays the groundwork for us to be able to easily swap
out the underlying file system when running Flutter tools,
which will be used to provide a record/replay file system,
analogous to what we have for process invocations.
parent 0c42c9b1
...@@ -8,7 +8,7 @@ environment: ...@@ -8,7 +8,7 @@ environment:
sdk: '>=1.19.0 <2.0.0' sdk: '>=1.19.0 <2.0.0'
dependencies: dependencies:
file: '^1.0.0' file: '^1.0.1'
json_rpc_2: '^2.0.0' json_rpc_2: '^2.0.0'
matcher: '>=0.12.0 <1.0.0' matcher: '>=0.12.0 <1.0.0'
path: '^1.4.0' path: '^1.4.0'
......
...@@ -3,13 +3,14 @@ ...@@ -3,13 +3,14 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:args/args.dart'; import 'package:args/args.dart';
import '../lib/src/base/common.dart'; import '../lib/src/base/common.dart';
import '../lib/src/base/config.dart'; import '../lib/src/base/config.dart';
import '../lib/src/base/context.dart'; import '../lib/src/base/context.dart';
import '../lib/src/base/file_system.dart';
import '../lib/src/base/logger.dart'; import '../lib/src/base/logger.dart';
import '../lib/src/base/os.dart'; import '../lib/src/base/os.dart';
import '../lib/src/base/process_manager.dart'; import '../lib/src/base/process_manager.dart';
...@@ -37,6 +38,7 @@ Future<Null> main(List<String> args) async { ...@@ -37,6 +38,7 @@ Future<Null> main(List<String> args) async {
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.
context.putIfAbsent(FileSystem, () => new LocalFileSystem());
context.putIfAbsent(ProcessManager, () => new ProcessManager()); context.putIfAbsent(ProcessManager, () => new ProcessManager());
context.putIfAbsent(Logger, () => new StdoutLogger()); context.putIfAbsent(Logger, () => new StdoutLogger());
context.putIfAbsent(Cache, () => new Cache()); context.putIfAbsent(Cache, () => new Cache());
...@@ -61,12 +63,12 @@ Future<Null> run(List<String> args) async { ...@@ -61,12 +63,12 @@ Future<Null> run(List<String> args) async {
printError('Missing option! All options must be specified.'); printError('Missing option! All options must be specified.');
exit(1); exit(1);
} }
Cache.flutterRoot = Platform.environment['FLUTTER_ROOT']; Cache.flutterRoot = io.Platform.environment['FLUTTER_ROOT'];
String outputPath = argResults[_kOptionOutput]; String outputPath = argResults[_kOptionOutput];
try { try {
await assemble( await assemble(
outputPath: outputPath, outputPath: outputPath,
snapshotFile: new File(argResults[_kOptionSnapshot]), snapshotFile: fs.file(argResults[_kOptionSnapshot]),
workingDirPath: argResults[_kOptionWorking], workingDirPath: argResults[_kOptionWorking],
packagesPath: argResults[_kOptionPackages], packagesPath: argResults[_kOptionPackages],
manifestPath: argResults[_kOptionsManifest] ?? defaultManifestPath, manifestPath: argResults[_kOptionsManifest] ?? defaultManifestPath,
...@@ -85,7 +87,7 @@ Future<Null> run(List<String> args) async { ...@@ -85,7 +87,7 @@ Future<Null> run(List<String> args) async {
int _addHeader(String outputPath, String header) { int _addHeader(String outputPath, String header) {
try { try {
final File outputFile = new File(outputPath); final File outputFile = fs.file(outputPath);
final List<int> content = outputFile.readAsBytesSync(); final List<int> content = outputFile.readAsBytesSync();
outputFile.writeAsStringSync('$header\n'); outputFile.writeAsStringSync('$header\n');
outputFile.writeAsBytesSync(content, mode: FileMode.APPEND); outputFile.writeAsBytesSync(content, mode: FileMode.APPEND);
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:args/command_runner.dart'; import 'package:args/command_runner.dart';
import 'package:stack_trace/stack_trace.dart'; import 'package:stack_trace/stack_trace.dart';
...@@ -11,6 +11,7 @@ import 'package:stack_trace/stack_trace.dart'; ...@@ -11,6 +11,7 @@ import 'package:stack_trace/stack_trace.dart';
import 'src/base/common.dart'; import 'src/base/common.dart';
import 'src/base/config.dart'; import 'src/base/config.dart';
import 'src/base/context.dart'; import 'src/base/context.dart';
import 'src/base/file_system.dart';
import 'src/base/logger.dart'; import 'src/base/logger.dart';
import 'src/base/os.dart'; import 'src/base/os.dart';
import 'src/base/process.dart'; import 'src/base/process.dart';
...@@ -101,6 +102,7 @@ Future<Null> main(List<String> args) async { ...@@ -101,6 +102,7 @@ Future<Null> main(List<String> args) async {
// in those locations as well to see if you need a similar update there. // in those locations as well to see if you need a similar update there.
// Seed these context entries first since others depend on them // Seed these context entries first since others depend on them
context.putIfAbsent(FileSystem, () => new LocalFileSystem());
context.putIfAbsent(ProcessManager, () => new ProcessManager()); context.putIfAbsent(ProcessManager, () => new ProcessManager());
context.putIfAbsent(Logger, () => new StdoutLogger()); context.putIfAbsent(Logger, () => new StdoutLogger());
...@@ -123,9 +125,9 @@ Future<Null> main(List<String> args) async { ...@@ -123,9 +125,9 @@ Future<Null> main(List<String> args) async {
_exit(0); _exit(0);
}, onError: (dynamic error, Chain chain) { }, onError: (dynamic error, Chain chain) {
if (error is UsageException) { if (error is UsageException) {
stderr.writeln(error.message); io.stderr.writeln(error.message);
stderr.writeln(); io.stderr.writeln();
stderr.writeln( io.stderr.writeln(
"Run 'flutter -h' (or 'flutter <command> -h') for available " "Run 'flutter -h' (or 'flutter <command> -h') for available "
"flutter commands and options." "flutter commands and options."
); );
...@@ -133,11 +135,11 @@ Future<Null> main(List<String> args) async { ...@@ -133,11 +135,11 @@ Future<Null> main(List<String> args) async {
_exit(64); _exit(64);
} else if (error is ToolExit) { } else if (error is ToolExit) {
if (error.message != null) if (error.message != null)
stderr.writeln(error.message); io.stderr.writeln(error.message);
if (verbose) { if (verbose) {
stderr.writeln(); io.stderr.writeln();
stderr.writeln(chain.terse.toString()); io.stderr.writeln(chain.terse.toString());
stderr.writeln(); io.stderr.writeln();
} }
_exit(error.exitCode ?? 1); _exit(error.exitCode ?? 1);
} else if (error is ProcessExit) { } else if (error is ProcessExit) {
...@@ -145,23 +147,23 @@ Future<Null> main(List<String> args) async { ...@@ -145,23 +147,23 @@ Future<Null> main(List<String> args) async {
_exit(error.exitCode); _exit(error.exitCode);
} else { } else {
// We've crashed; emit a log report. // We've crashed; emit a log report.
stderr.writeln(); io.stderr.writeln();
flutterUsage.sendException(error, chain); flutterUsage.sendException(error, chain);
if (isRunningOnBot) { if (isRunningOnBot) {
// Print the stack trace on the bots - don't write a crash report. // Print the stack trace on the bots - don't write a crash report.
stderr.writeln('$error'); io.stderr.writeln('$error');
stderr.writeln(chain.terse.toString()); io.stderr.writeln(chain.terse.toString());
_exit(1); _exit(1);
} else { } else {
if (error is String) if (error is String)
stderr.writeln('Oops; flutter has exited unexpectedly: "$error".'); io.stderr.writeln('Oops; flutter has exited unexpectedly: "$error".');
else else
stderr.writeln('Oops; flutter has exited unexpectedly.'); io.stderr.writeln('Oops; flutter has exited unexpectedly.');
_createCrashReport(args, error, chain).then((File file) { _createCrashReport(args, error, chain).then((File file) {
stderr.writeln( io.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.'
); );
...@@ -174,7 +176,7 @@ Future<Null> main(List<String> args) async { ...@@ -174,7 +176,7 @@ Future<Null> main(List<String> args) async {
} }
Future<File> _createCrashReport(List<String> args, dynamic error, Chain chain) async { Future<File> _createCrashReport(List<String> args, dynamic error, Chain chain) async {
File crashFile = getUniqueFile(Directory.current, 'flutter', 'log'); File crashFile = getUniqueFile(fs.currentDirectory, 'flutter', 'log');
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
...@@ -194,7 +196,7 @@ Future<File> _createCrashReport(List<String> args, dynamic error, Chain chain) a ...@@ -194,7 +196,7 @@ Future<File> _createCrashReport(List<String> args, dynamic error, Chain chain) a
crashFile.writeAsStringSync(buffer.toString()); crashFile.writeAsStringSync(buffer.toString());
} on FileSystemException catch (_) { } on FileSystemException catch (_) {
// Fallback to the system temporary directory. // Fallback to the system temporary directory.
crashFile = getUniqueFile(Directory.systemTemp, 'flutter', 'log'); crashFile = getUniqueFile(fs.systemTempDirectory, 'flutter', 'log');
try { try {
crashFile.writeAsStringSync(buffer.toString()); crashFile.writeAsStringSync(buffer.toString());
} on FileSystemException catch (e) { } on FileSystemException catch (e) {
......
...@@ -4,12 +4,13 @@ ...@@ -4,12 +4,13 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import '../android/android_sdk.dart'; import '../android/android_sdk.dart';
import '../application_package.dart'; import '../application_package.dart';
import '../base/os.dart'; import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/os.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
import '../build_info.dart'; import '../build_info.dart';
...@@ -60,7 +61,7 @@ class AndroidDevice extends Device { ...@@ -60,7 +61,7 @@ class AndroidDevice extends Device {
try { try {
// We pass an encoding of LATIN1 so that we don't try and interpret the // We pass an encoding of LATIN1 so that we don't try and interpret the
// `adb shell getprop` result as UTF8. // `adb shell getprop` result as UTF8.
ProcessResult result = processManager.runSync( io.ProcessResult result = processManager.runSync(
propCommand.first, propCommand.first,
propCommand.sublist(1), propCommand.sublist(1),
stdoutEncoding: LATIN1 stdoutEncoding: LATIN1
...@@ -201,7 +202,7 @@ class AndroidDevice extends Device { ...@@ -201,7 +202,7 @@ class AndroidDevice extends Device {
String _getSourceSha1(ApplicationPackage app) { String _getSourceSha1(ApplicationPackage app) {
AndroidApk apk = app; AndroidApk apk = app;
File shaFile = new File('${apk.apkPath}.sha1'); File shaFile = fs.file('${apk.apkPath}.sha1');
return shaFile.existsSync() ? shaFile.readAsStringSync() : ''; return shaFile.existsSync() ? shaFile.readAsStringSync() : '';
} }
...@@ -222,7 +223,7 @@ class AndroidDevice extends Device { ...@@ -222,7 +223,7 @@ class AndroidDevice extends Device {
@override @override
bool installApp(ApplicationPackage app) { bool installApp(ApplicationPackage app) {
AndroidApk apk = app; AndroidApk apk = app;
if (!FileSystemEntity.isFileSync(apk.apkPath)) { if (!fs.isFileSync(apk.apkPath)) {
printError('"${apk.apkPath}" does not exist.'); printError('"${apk.apkPath}" does not exist.');
return false; return false;
} }
...@@ -558,7 +559,7 @@ class _AdbLogReader extends DeviceLogReader { ...@@ -558,7 +559,7 @@ class _AdbLogReader extends DeviceLogReader {
final AndroidDevice device; final AndroidDevice device;
StreamController<String> _linesController; StreamController<String> _linesController;
Process _process; io.Process _process;
@override @override
Stream<String> get logLines => _linesController.stream; Stream<String> get logLines => _linesController.stream;
...@@ -584,7 +585,7 @@ class _AdbLogReader extends DeviceLogReader { ...@@ -584,7 +585,7 @@ class _AdbLogReader extends DeviceLogReader {
_timeOrigin = _adbTimestampToDateTime(lastTimestamp); _timeOrigin = _adbTimestampToDateTime(lastTimestamp);
else else
_timeOrigin = null; _timeOrigin = null;
runCommand(device.adbCommandForDevice(args)).then((Process process) { runCommand(device.adbCommandForDevice(args)).then((io.Process process) {
_process = process; _process = process;
_process.stdout.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine); _process.stdout.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine);
_process.stderr.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine); _process.stderr.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine);
......
...@@ -2,13 +2,14 @@ ...@@ -2,13 +2,14 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io'; import 'dart:io' as io;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:pub_semver/pub_semver.dart'; import 'package:pub_semver/pub_semver.dart';
import '../base/common.dart'; import '../base/common.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart';
import '../base/os.dart'; import '../base/os.dart';
import '../globals.dart'; import '../globals.dart';
...@@ -64,12 +65,12 @@ class AndroidSdk { ...@@ -64,12 +65,12 @@ class AndroidSdk {
static AndroidSdk locateAndroidSdk() { static AndroidSdk locateAndroidSdk() {
String androidHomeDir; String androidHomeDir;
if (Platform.environment.containsKey(kAndroidHome)) { if (io.Platform.environment.containsKey(kAndroidHome)) {
androidHomeDir = Platform.environment[kAndroidHome]; androidHomeDir = io.Platform.environment[kAndroidHome];
} else if (Platform.isLinux) { } else if (io.Platform.isLinux) {
if (homeDirPath != null) if (homeDirPath != null)
androidHomeDir = '$homeDirPath/Android/Sdk'; androidHomeDir = '$homeDirPath/Android/Sdk';
} else if (Platform.isMacOS) { } else if (io.Platform.isMacOS) {
if (homeDirPath != null) if (homeDirPath != null)
androidHomeDir = '$homeDirPath/Library/Android/sdk'; androidHomeDir = '$homeDirPath/Library/Android/sdk';
} }
...@@ -84,7 +85,7 @@ class AndroidSdk { ...@@ -84,7 +85,7 @@ class AndroidSdk {
File aaptBin = os.which('aapt'); // in build-tools/$version/aapt File aaptBin = os.which('aapt'); // in build-tools/$version/aapt
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 = new File(aaptBin.resolveSymbolicLinksSync()); aaptBin = fs.file(aaptBin.resolveSymbolicLinksSync());
String dir = aaptBin.parent.parent.parent.path; String dir = aaptBin.parent.parent.parent.path;
if (validSdkDirectory(dir)) if (validSdkDirectory(dir))
return new AndroidSdk(dir); return new AndroidSdk(dir);
...@@ -93,7 +94,7 @@ class AndroidSdk { ...@@ -93,7 +94,7 @@ class AndroidSdk {
File adbBin = os.which('adb'); // in platform-tools/adb File adbBin = os.which('adb'); // in platform-tools/adb
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 = new File(adbBin.resolveSymbolicLinksSync()); adbBin = fs.file(adbBin.resolveSymbolicLinksSync());
String dir = adbBin.parent.parent.path; String dir = adbBin.parent.parent.path;
if (validSdkDirectory(dir)) if (validSdkDirectory(dir))
return new AndroidSdk(dir); return new AndroidSdk(dir);
...@@ -105,7 +106,7 @@ class AndroidSdk { ...@@ -105,7 +106,7 @@ class AndroidSdk {
} }
static bool validSdkDirectory(String dir) { static bool validSdkDirectory(String dir) {
return FileSystemEntity.isDirectorySync(path.join(dir, 'platform-tools')); return fs.isDirectorySync(path.join(dir, 'platform-tools'));
} }
List<AndroidSdkVersion> get sdkVersions => _sdkVersions; List<AndroidSdkVersion> get sdkVersions => _sdkVersions;
...@@ -117,7 +118,7 @@ class AndroidSdk { ...@@ -117,7 +118,7 @@ class AndroidSdk {
/// Validate the Android SDK. This returns an empty list if there are no /// Validate the Android SDK. This returns an empty list if there are no
/// issues; otherwise, it returns a list of issues found. /// issues; otherwise, it returns a list of issues found.
List<String> validateSdkWellFormed() { List<String> validateSdkWellFormed() {
if (!FileSystemEntity.isFileSync(adbPath)) if (!fs.isFileSync(adbPath))
return <String>['Android SDK file not found: $adbPath.']; return <String>['Android SDK file not found: $adbPath.'];
if (sdkVersions.isEmpty || latestVersion == null) if (sdkVersions.isEmpty || latestVersion == null)
...@@ -133,7 +134,7 @@ class AndroidSdk { ...@@ -133,7 +134,7 @@ class AndroidSdk {
void _init() { void _init() {
List<String> platforms = <String>[]; // android-22, ... List<String> platforms = <String>[]; // android-22, ...
Directory platformsDir = new Directory(path.join(directory, 'platforms')); Directory platformsDir = fs.directory(path.join(directory, 'platforms'));
if (platformsDir.existsSync()) { if (platformsDir.existsSync()) {
platforms = platformsDir platforms = platformsDir
.listSync() .listSync()
...@@ -144,7 +145,7 @@ class AndroidSdk { ...@@ -144,7 +145,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 = new Directory(path.join(directory, 'build-tools')); Directory buildToolsDir = fs.directory(path.join(directory, 'build-tools'));
if (buildToolsDir.existsSync()) { if (buildToolsDir.existsSync()) {
buildTools = buildToolsDir buildTools = buildToolsDir
.listSync() .listSync()
...@@ -253,7 +254,7 @@ class AndroidSdkVersion implements Comparable<AndroidSdkVersion> { ...@@ -253,7 +254,7 @@ class AndroidSdkVersion implements Comparable<AndroidSdkVersion> {
String toString() => '[${sdk.directory}, SDK version $sdkLevel, build-tools $buildToolsVersionName]'; String toString() => '[${sdk.directory}, SDK version $sdkLevel, build-tools $buildToolsVersionName]';
String _exists(String path) { String _exists(String path) {
if (!FileSystemEntity.isFileSync(path)) if (!fs.isFileSync(path))
return 'Android SDK file not found: $path.'; return 'Android SDK file not found: $path.';
return null; return null;
} }
......
...@@ -3,11 +3,11 @@ ...@@ -3,11 +3,11 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/os.dart'; import '../base/os.dart';
import '../base/process.dart'; import '../base/process.dart';
...@@ -21,13 +21,13 @@ const String gradleManifestPath = 'android/app/src/main/AndroidManifest.xml'; ...@@ -21,13 +21,13 @@ const String gradleManifestPath = 'android/app/src/main/AndroidManifest.xml';
const String gradleAppOut = 'android/app/build/outputs/apk/app-debug.apk'; const String gradleAppOut = 'android/app/build/outputs/apk/app-debug.apk';
bool isProjectUsingGradle() { bool isProjectUsingGradle() {
return FileSystemEntity.isFileSync('android/build.gradle'); return fs.isFileSync('android/build.gradle');
} }
String locateSystemGradle({ bool ensureExecutable: true }) { String locateSystemGradle({ bool ensureExecutable: true }) {
String gradle = _locateSystemGradle(); String gradle = _locateSystemGradle();
if (ensureExecutable && gradle != null) { if (ensureExecutable && gradle != null) {
File file = new File(gradle); File file = fs.file(gradle);
if (file.existsSync()) if (file.existsSync())
os.makeExecutable(file); os.makeExecutable(file);
} }
...@@ -38,7 +38,7 @@ String _locateSystemGradle() { ...@@ -38,7 +38,7 @@ String _locateSystemGradle() {
// See if the user has explicitly configured gradle-dir. // See if the user has explicitly configured gradle-dir.
String gradleDir = config.getValue('gradle-dir'); String gradleDir = config.getValue('gradle-dir');
if (gradleDir != null) { if (gradleDir != null) {
if (FileSystemEntity.isFileSync(gradleDir)) if (fs.isFileSync(gradleDir))
return gradleDir; return gradleDir;
return path.join(gradleDir, 'bin', 'gradle'); return path.join(gradleDir, 'bin', 'gradle');
} }
...@@ -48,7 +48,7 @@ String _locateSystemGradle() { ...@@ -48,7 +48,7 @@ String _locateSystemGradle() {
if (studioPath == null && os.isMacOS) { if (studioPath == null && os.isMacOS) {
final String kDefaultMacPath = '/Applications/Android Studio.app'; final String kDefaultMacPath = '/Applications/Android Studio.app';
if (FileSystemEntity.isDirectorySync(kDefaultMacPath)) if (fs.isDirectorySync(kDefaultMacPath))
studioPath = kDefaultMacPath; studioPath = kDefaultMacPath;
} }
...@@ -57,13 +57,13 @@ String _locateSystemGradle() { ...@@ -57,13 +57,13 @@ String _locateSystemGradle() {
if (os.isMacOS && !studioPath.endsWith('Contents')) if (os.isMacOS && !studioPath.endsWith('Contents'))
studioPath = path.join(studioPath, 'Contents'); studioPath = path.join(studioPath, 'Contents');
Directory dir = new Directory(path.join(studioPath, 'gradle')); Directory dir = fs.directory(path.join(studioPath, 'gradle'));
if (dir.existsSync()) { if (dir.existsSync()) {
// We find the first valid gradle directory. // We find the first valid gradle directory.
for (FileSystemEntity entity in dir.listSync()) { for (FileSystemEntity entity in dir.listSync()) {
if (entity is Directory && path.basename(entity.path).startsWith('gradle-')) { if (entity is Directory && path.basename(entity.path).startsWith('gradle-')) {
String executable = path.join(entity.path, 'bin', 'gradle'); String executable = path.join(entity.path, 'bin', 'gradle');
if (FileSystemEntity.isFileSync(executable)) if (fs.isFileSync(executable))
return executable; return executable;
} }
} }
...@@ -82,9 +82,9 @@ String _locateSystemGradle() { ...@@ -82,9 +82,9 @@ String _locateSystemGradle() {
String locateProjectGradlew({ bool ensureExecutable: true }) { String locateProjectGradlew({ bool ensureExecutable: true }) {
final String path = 'android/gradlew'; final String path = 'android/gradlew';
if (FileSystemEntity.isFileSync(path)) { if (fs.isFileSync(path)) {
if (ensureExecutable) if (ensureExecutable)
os.makeExecutable(new File(path)); os.makeExecutable(fs.file(path));
return path; return path;
} else { } else {
return null; return null;
...@@ -93,7 +93,7 @@ String locateProjectGradlew({ bool ensureExecutable: true }) { ...@@ -93,7 +93,7 @@ String locateProjectGradlew({ bool ensureExecutable: true }) {
Future<Null> buildGradleProject(BuildMode buildMode) async { Future<Null> buildGradleProject(BuildMode buildMode) async {
// Create android/local.properties. // Create android/local.properties.
File localProperties = new File('android/local.properties'); File localProperties = fs.file('android/local.properties');
if (!localProperties.existsSync()) { if (!localProperties.existsSync()) {
localProperties.writeAsStringSync( localProperties.writeAsStringSync(
'sdk.dir=${androidSdk.directory}\n' 'sdk.dir=${androidSdk.directory}\n'
...@@ -120,7 +120,7 @@ Future<Null> buildGradleProject(BuildMode buildMode) async { ...@@ -120,7 +120,7 @@ Future<Null> buildGradleProject(BuildMode buildMode) async {
} }
// Stamp the android/app/build.gradle file with the current android sdk and build tools version. // Stamp the android/app/build.gradle file with the current android sdk and build tools version.
File appGradleFile = new File('android/app/build.gradle'); File appGradleFile = fs.file('android/app/build.gradle');
if (appGradleFile.existsSync()) { if (appGradleFile.existsSync()) {
_GradleFile gradleFile = new _GradleFile.parse(appGradleFile); _GradleFile gradleFile = new _GradleFile.parse(appGradleFile);
AndroidSdkVersion sdkVersion = androidSdk.latestVersion; AndroidSdkVersion sdkVersion = androidSdk.latestVersion;
...@@ -152,7 +152,7 @@ Future<Null> buildGradleProject(BuildMode buildMode) async { ...@@ -152,7 +152,7 @@ Future<Null> buildGradleProject(BuildMode buildMode) async {
// Run 'gradlew build'. // Run 'gradlew build'.
Status status = logger.startProgress('Running \'gradlew build\'...'); Status status = logger.startProgress('Running \'gradlew build\'...');
int exitcode = await runCommandAndStreamOutput( int exitcode = await runCommandAndStreamOutput(
<String>[new File('android/gradlew').absolute.path, 'build'], <String>[fs.file('android/gradlew').absolute.path, 'build'],
workingDirectory: 'android', workingDirectory: 'android',
allowReentrantFlutter: true allowReentrantFlutter: true
); );
...@@ -161,7 +161,7 @@ Future<Null> buildGradleProject(BuildMode buildMode) async { ...@@ -161,7 +161,7 @@ Future<Null> buildGradleProject(BuildMode buildMode) async {
if (exitcode != 0) if (exitcode != 0)
throwToolExit('Gradlew failed: $exitcode', exitCode: exitcode); throwToolExit('Gradlew failed: $exitcode', exitCode: exitcode);
File apkFile = new File(gradleAppOut); File apkFile = fs.file(gradleAppOut);
printStatus('Built $gradleAppOut (${getSizeAsMB(apkFile.lengthSync())}).'); printStatus('Built $gradleAppOut (${getSizeAsMB(apkFile.lengthSync())}).');
} }
......
...@@ -2,13 +2,12 @@ ...@@ -2,13 +2,12 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:xml/xml.dart' as xml; import 'package:xml/xml.dart' as xml;
import 'android/android_sdk.dart'; import 'android/android_sdk.dart';
import 'android/gradle.dart'; import 'android/gradle.dart';
import 'base/file_system.dart';
import 'base/os.dart' show os; import 'base/os.dart' show os;
import 'base/process.dart'; import 'base/process.dart';
import 'build_info.dart'; import 'build_info.dart';
...@@ -89,10 +88,10 @@ class AndroidApk extends ApplicationPackage { ...@@ -89,10 +88,10 @@ class AndroidApk extends ApplicationPackage {
apkPath = path.join(getAndroidBuildDirectory(), 'app.apk'); apkPath = path.join(getAndroidBuildDirectory(), 'app.apk');
} }
if (!FileSystemEntity.isFileSync(manifestPath)) if (!fs.isFileSync(manifestPath))
return null; return null;
String manifestString = new File(manifestPath).readAsStringSync(); String manifestString = fs.file(manifestPath).readAsStringSync();
xml.XmlDocument document = xml.parse(manifestString); xml.XmlDocument document = xml.parse(manifestString);
Iterable<xml.XmlElement> manifests = document.findElements('manifest'); Iterable<xml.XmlElement> manifests = document.findElements('manifest');
...@@ -135,10 +134,10 @@ abstract class IOSApp extends ApplicationPackage { ...@@ -135,10 +134,10 @@ abstract class IOSApp extends ApplicationPackage {
factory IOSApp.fromIpa(String applicationBinary) { factory IOSApp.fromIpa(String applicationBinary) {
Directory bundleDir; Directory bundleDir;
try { try {
Directory tempDir = Directory.systemTemp.createTempSync('flutter_app_'); Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app_');
addShutdownHook(() async => await tempDir.delete(recursive: true)); addShutdownHook(() async => await tempDir.delete(recursive: true));
os.unzip(new File(applicationBinary), tempDir); os.unzip(fs.file(applicationBinary), tempDir);
Directory payloadDir = new Directory(path.join(tempDir.path, 'Payload')); Directory payloadDir = fs.directory(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);
......
...@@ -4,12 +4,13 @@ ...@@ -4,12 +4,13 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'package:json_schema/json_schema.dart'; import 'package:json_schema/json_schema.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart'; import 'package:yaml/yaml.dart';
import 'base/file_system.dart';
import 'build_info.dart'; import 'build_info.dart';
import 'cache.dart'; import 'cache.dart';
import 'dart/package_map.dart'; import 'dart/package_map.dart';
...@@ -74,7 +75,7 @@ class AssetBundle { ...@@ -74,7 +75,7 @@ class AssetBundle {
final String assetPath = path.join(projectRoot, asset); final String assetPath = path.join(projectRoot, asset);
final String archivePath = asset; final String archivePath = asset;
entries.add( entries.add(
new AssetBundleEntry.fromFile(archivePath, new File(assetPath))); new AssetBundleEntry.fromFile(archivePath, fs.file(assetPath)));
} }
} }
...@@ -84,7 +85,7 @@ class AssetBundle { ...@@ -84,7 +85,7 @@ class AssetBundle {
if (_lastBuildTimestamp == null) if (_lastBuildTimestamp == null)
return true; return true;
FileStat stat = new File(manifestPath).statSync(); FileStat stat = fs.file(manifestPath).statSync();
if (stat.type == FileSystemEntityType.NOT_FOUND) if (stat.type == FileSystemEntityType.NOT_FOUND)
return true; return true;
...@@ -206,7 +207,7 @@ class _Asset { ...@@ -206,7 +207,7 @@ class _Asset {
final String source; final String source;
File get assetFile { File get assetFile {
return new File(source != null ? '$base/$source' : '$base/$relativePath'); return fs.file(source != null ? '$base/$source' : '$base/$relativePath');
} }
bool get assetFileExists => assetFile.existsSync(); bool get assetFileExists => assetFile.existsSync();
...@@ -228,7 +229,7 @@ Map<String, dynamic> _readMaterialFontsManifest() { ...@@ -228,7 +229,7 @@ Map<String, dynamic> _readMaterialFontsManifest() {
String fontsPath = path.join(path.absolute(Cache.flutterRoot), String fontsPath = path.join(path.absolute(Cache.flutterRoot),
'packages', 'flutter_tools', 'schema', 'material_fonts.yaml'); 'packages', 'flutter_tools', 'schema', 'material_fonts.yaml');
return loadYaml(new File(fontsPath).readAsStringSync()); return loadYaml(fs.file(fontsPath).readAsStringSync());
} }
final Map<String, dynamic> _materialFontsManifest = _readMaterialFontsManifest(); final Map<String, dynamic> _materialFontsManifest = _readMaterialFontsManifest();
...@@ -280,7 +281,7 @@ Future<AssetBundleEntry> _obtainLicenses( ...@@ -280,7 +281,7 @@ Future<AssetBundleEntry> _obtainLicenses(
for (String packageName in packageMap.map.keys) { for (String packageName in packageMap.map.keys) {
final Uri package = packageMap.map[packageName]; final Uri package = packageMap.map[packageName];
if (package != null && package.scheme == 'file') { if (package != null && package.scheme == 'file') {
final File file = new File.fromUri(package.resolve('../LICENSE')); final File file = fs.file(package.resolve('../LICENSE'));
if (file.existsSync()) { if (file.existsSync()) {
final List<String> rawLicenses = final List<String> rawLicenses =
(await file.readAsString()).split(_licenseSeparator); (await file.readAsString()).split(_licenseSeparator);
...@@ -377,7 +378,7 @@ Map<_Asset, List<_Asset>> _parseAssets( ...@@ -377,7 +378,7 @@ Map<_Asset, List<_Asset>> _parseAssets(
return result; return result;
excludeDirs = excludeDirs.map( excludeDirs = excludeDirs.map(
(String exclude) => path.absolute(exclude) + Platform.pathSeparator).toList(); (String exclude) => path.absolute(exclude) + io.Platform.pathSeparator).toList();
if (manifestDescriptor.containsKey('assets')) { if (manifestDescriptor.containsKey('assets')) {
for (String asset in manifestDescriptor['assets']) { for (String asset in manifestDescriptor['assets']) {
...@@ -394,12 +395,12 @@ Map<_Asset, List<_Asset>> _parseAssets( ...@@ -394,12 +395,12 @@ Map<_Asset, List<_Asset>> _parseAssets(
// Find asset variants // Find asset variants
String assetPath = baseAsset.assetFile.path; String assetPath = baseAsset.assetFile.path;
String assetFilename = path.basename(assetPath); String assetFilename = path.basename(assetPath);
Directory assetDir = new Directory(path.dirname(assetPath)); Directory assetDir = fs.directory(path.dirname(assetPath));
List<FileSystemEntity> files = assetDir.listSync(recursive: true); List<FileSystemEntity> files = assetDir.listSync(recursive: true);
for (FileSystemEntity entity in files) { for (FileSystemEntity entity in files) {
if (!FileSystemEntity.isFileSync(entity.path)) if (!fs.isFileSync(entity.path))
continue; continue;
// Exclude any files in the given directories. // Exclude any files in the given directories.
...@@ -446,7 +447,7 @@ _Asset _resolveAsset( ...@@ -446,7 +447,7 @@ _Asset _resolveAsset(
String assetBase, String assetBase,
String asset String asset
) { ) {
if (asset.startsWith('packages/') && !FileSystemEntity.isFileSync(path.join(assetBase, asset))) { if (asset.startsWith('packages/') && !fs.isFileSync(path.join(assetBase, asset))) {
// Convert packages/flutter_gallery_assets/clouds-0.png to clouds-0.png. // Convert packages/flutter_gallery_assets/clouds-0.png to clouds-0.png.
String packageKey = asset.substring(9); String packageKey = asset.substring(9);
String relativeAsset = asset; String relativeAsset = asset;
...@@ -459,7 +460,7 @@ _Asset _resolveAsset( ...@@ -459,7 +460,7 @@ _Asset _resolveAsset(
Uri uri = packageMap.map[packageKey]; Uri uri = packageMap.map[packageKey];
if (uri != null && uri.scheme == 'file') { if (uri != null && uri.scheme == 'file') {
File file = new File.fromUri(uri); 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);
} }
} }
...@@ -468,9 +469,9 @@ _Asset _resolveAsset( ...@@ -468,9 +469,9 @@ _Asset _resolveAsset(
} }
dynamic _loadFlutterYamlManifest(String manifestPath) { dynamic _loadFlutterYamlManifest(String manifestPath) {
if (manifestPath == null || !FileSystemEntity.isFileSync(manifestPath)) if (manifestPath == null || !fs.isFileSync(manifestPath))
return null; return null;
String manifestDescriptor = new File(manifestPath).readAsStringSync(); String manifestDescriptor = fs.file(manifestPath).readAsStringSync();
return loadYaml(manifestDescriptor); return loadYaml(manifestDescriptor);
} }
......
...@@ -3,15 +3,16 @@ ...@@ -3,15 +3,16 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'context.dart'; import 'context.dart';
import 'file_system.dart';
class Config { class Config {
Config([File configFile]) { Config([File configFile]) {
_configFile = configFile ?? new File(path.join(_userHomeDir(), '.flutter_settings')); _configFile = configFile ?? fs.file(path.join(_userHomeDir(), '.flutter_settings'));
if (_configFile.existsSync()) if (_configFile.existsSync())
_values = JSON.decode(_configFile.readAsStringSync()); _values = JSON.decode(_configFile.readAsStringSync());
} }
...@@ -45,7 +46,7 @@ class Config { ...@@ -45,7 +46,7 @@ class Config {
} }
String _userHomeDir() { String _userHomeDir() {
String envKey = Platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME'; String envKey = io.Platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME';
String value = Platform.environment[envKey]; String value = io.Platform.environment[envKey];
return value == null ? '.' : value; return value == null ? '.' : value;
} }
...@@ -2,50 +2,57 @@ ...@@ -2,50 +2,57 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io' as dart_io; import 'dart:io' as io;
import 'package:file/file.dart'; import 'package:file/file.dart';
import 'package:file/local.dart'; import 'package:file/local.dart';
import 'package:file/memory.dart'; import 'package:file/memory.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'context.dart';
export 'package:file/file.dart'; export 'package:file/file.dart';
export 'package:file/local.dart'; export 'package:file/local.dart';
const FileSystem _kLocalFs = const LocalFileSystem();
/// Currently active implementation of the file system. /// Currently active implementation of the file system.
/// ///
/// By default it uses local disk-based implementation. Override this in tests /// By default it uses local disk-based implementation. Override this in tests
/// with [MemoryFileSystem]. /// with [MemoryFileSystem].
FileSystem fs = new LocalFileSystem(); FileSystem get fs => context == null ? _kLocalFs : context[FileSystem];
/// Exits the process with the given [exitCode]. /// Exits the process with the given [exitCode].
typedef void ExitFunction([int exitCode]); typedef void ExitFunction([int exitCode]);
final ExitFunction _defaultExitFunction = ([int exitCode]) { final ExitFunction _defaultExitFunction = ([int exitCode]) {
dart_io.exit(exitCode); io.exit(exitCode);
}; };
/// Exits the process. ExitFunction _exitFunction = _defaultExitFunction;
ExitFunction exit = _defaultExitFunction;
/// Restores [fs] to the default local disk-based implementation. /// Exits the process.
void restoreFileSystem() { ///
fs = new LocalFileSystem(); /// During tests, this may be set to a testing-friendly value by calling
exit = _defaultExitFunction; /// [setExitFunctionForTests] (and then restored with [restoreExitFunction]).
} ExitFunction get exit => _exitFunction;
/// Uses in-memory replacments for `dart:io` functionality. Useful in tests. /// Sets the [exit] function to a function that throws an exception rather
void useInMemoryFileSystem({ String cwd: '/', ExitFunction exitFunction }) { /// than exiting the process; intended for testing purposes.
fs = new MemoryFileSystem(); @visibleForTesting
if (!fs.directory(cwd).existsSync()) { void setExitFunctionForTests([ExitFunction exitFunction]) {
fs.directory(cwd).createSync(recursive: true); _exitFunction = exitFunction ?? ([int exitCode]) {
}
fs.currentDirectory = cwd;
exit = exitFunction ?? ([int exitCode]) {
throw new Exception('Exited with code $exitCode'); throw new Exception('Exited with code $exitCode');
}; };
} }
/// Restores the [exit] function to the `dart:io` implementation.
@visibleForTesting
void restoreExitFunction() {
_exitFunction = _defaultExitFunction;
}
/// 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 = path.dirname(filePath); String dirPath = path.dirname(filePath);
...@@ -57,20 +64,20 @@ void ensureDirectoryExists(String filePath) { ...@@ -57,20 +64,20 @@ void ensureDirectoryExists(String filePath) {
/// Recursively copies a folder from `srcPath` to `destPath` /// Recursively copies a folder from `srcPath` to `destPath`
void copyFolderSync(String srcPath, String destPath) { void copyFolderSync(String srcPath, String destPath) {
dart_io.Directory srcDir = new dart_io.Directory(srcPath); Directory srcDir = fs.directory(srcPath);
if (!srcDir.existsSync()) if (!srcDir.existsSync())
throw new Exception('Source directory "${srcDir.path}" does not exist, nothing to copy'); throw new Exception('Source directory "${srcDir.path}" does not exist, nothing to copy');
dart_io.Directory destDir = new dart_io.Directory(destPath); Directory destDir = fs.directory(destPath);
if (!destDir.existsSync()) if (!destDir.existsSync())
destDir.createSync(recursive: true); destDir.createSync(recursive: true);
srcDir.listSync().forEach((dart_io.FileSystemEntity entity) { srcDir.listSync().forEach((FileSystemEntity entity) {
String newPath = path.join(destDir.path, path.basename(entity.path)); String newPath = path.join(destDir.path, path.basename(entity.path));
if (entity is dart_io.File) { if (entity is File) {
dart_io.File newFile = new dart_io.File(newPath); File newFile = fs.file(newPath);
newFile.writeAsBytesSync(entity.readAsBytesSync()); newFile.writeAsBytesSync(entity.readAsBytesSync());
} else if (entity is dart_io.Directory) { } else if (entity is Directory) {
copyFolderSync(entity.path, newPath); copyFolderSync(entity.path, newPath);
} else { } else {
throw new Exception('${entity.path} is neither File nor Directory'); throw new Exception('${entity.path} is neither File nor Directory');
......
...@@ -3,12 +3,13 @@ ...@@ -3,12 +3,13 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:archive/archive.dart'; import 'package:archive/archive.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'context.dart'; import 'context.dart';
import 'file_system.dart';
import 'process.dart'; import 'process.dart';
import 'process_manager.dart'; import 'process_manager.dart';
...@@ -17,7 +18,7 @@ OperatingSystemUtils get os => context[OperatingSystemUtils]; ...@@ -17,7 +18,7 @@ OperatingSystemUtils get os => context[OperatingSystemUtils];
abstract class OperatingSystemUtils { abstract class OperatingSystemUtils {
factory OperatingSystemUtils() { factory OperatingSystemUtils() {
if (Platform.isWindows) { if (io.Platform.isWindows) {
return new _WindowsUtils(); return new _WindowsUtils();
} else { } else {
return new _PosixUtils(); return new _PosixUtils();
...@@ -26,14 +27,14 @@ abstract class OperatingSystemUtils { ...@@ -26,14 +27,14 @@ abstract class OperatingSystemUtils {
OperatingSystemUtils._private(); OperatingSystemUtils._private();
String get operatingSystem => Platform.operatingSystem; String get operatingSystem => io.Platform.operatingSystem;
bool get isMacOS => operatingSystem == 'macos'; bool get isMacOS => operatingSystem == 'macos';
bool get isWindows => operatingSystem == 'windows'; bool get isWindows => operatingSystem == 'windows';
bool get isLinux => operatingSystem == 'linux'; bool get isLinux => operatingSystem == 'linux';
/// Make the given file executable. This may be a no-op on some platforms. /// Make the given file executable. This may be a no-op on some platforms.
ProcessResult makeExecutable(File file); io.ProcessResult makeExecutable(File file);
/// Return the path (with symlinks resolved) to the given executable, or `null` /// Return the path (with symlinks resolved) to the given executable, or `null`
/// if `which` was not able to locate the binary. /// if `which` was not able to locate the binary.
...@@ -49,7 +50,7 @@ class _PosixUtils extends OperatingSystemUtils { ...@@ -49,7 +50,7 @@ class _PosixUtils extends OperatingSystemUtils {
_PosixUtils() : super._private(); _PosixUtils() : super._private();
@override @override
ProcessResult makeExecutable(File file) { io.ProcessResult makeExecutable(File file) {
return processManager.runSync('chmod', <String>['a+x', file.path]); return processManager.runSync('chmod', <String>['a+x', file.path]);
} }
...@@ -57,11 +58,11 @@ class _PosixUtils extends OperatingSystemUtils { ...@@ -57,11 +58,11 @@ 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('which', <String>[execName]); io.ProcessResult result = processManager.runSync('which', <String>[execName]);
if (result.exitCode != 0) if (result.exitCode != 0)
return null; return null;
String path = result.stdout.trim().split('\n').first.trim(); String path = result.stdout.trim().split('\n').first.trim();
return new File(path); return fs.file(path);
} }
// unzip -o -q zipfile -d dest // unzip -o -q zipfile -d dest
...@@ -73,7 +74,7 @@ class _PosixUtils extends OperatingSystemUtils { ...@@ -73,7 +74,7 @@ class _PosixUtils extends OperatingSystemUtils {
@override @override
File makePipe(String path) { File makePipe(String path) {
runSync(<String>['mkfifo', path]); runSync(<String>['mkfifo', path]);
return new File(path); return fs.file(path);
} }
} }
...@@ -82,16 +83,16 @@ class _WindowsUtils extends OperatingSystemUtils { ...@@ -82,16 +83,16 @@ class _WindowsUtils extends OperatingSystemUtils {
// This is a no-op. // This is a no-op.
@override @override
ProcessResult makeExecutable(File file) { io.ProcessResult makeExecutable(File file) {
return new ProcessResult(0, 0, null, null); return new io.ProcessResult(0, 0, null, null);
} }
@override @override
File which(String execName) { File which(String execName) {
ProcessResult result = processManager.runSync('where', <String>[execName]); io.ProcessResult result = processManager.runSync('where', <String>[execName]);
if (result.exitCode != 0) if (result.exitCode != 0)
return null; return null;
return new File(result.stdout.trim().split('\n').first.trim()); return fs.file(result.stdout.trim().split('\n').first.trim());
} }
@override @override
...@@ -103,7 +104,7 @@ class _WindowsUtils extends OperatingSystemUtils { ...@@ -103,7 +104,7 @@ class _WindowsUtils extends OperatingSystemUtils {
if (!archiveFile.isFile || archiveFile.name.endsWith('/')) if (!archiveFile.isFile || archiveFile.name.endsWith('/'))
continue; continue;
File destFile = new File(path.join(targetDirectory.path, archiveFile.name)); File destFile = fs.file(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);
...@@ -117,7 +118,7 @@ class _WindowsUtils extends OperatingSystemUtils { ...@@ -117,7 +118,7 @@ class _WindowsUtils extends OperatingSystemUtils {
} }
Future<int> findAvailablePort() async { Future<int> findAvailablePort() async {
ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0); io.ServerSocket socket = await io.ServerSocket.bind(io.InternetAddress.LOOPBACK_IP_V4, 0);
int port = socket.port; int port = socket.port;
await socket.close(); await socket.close();
return port; return port;
...@@ -142,7 +143,7 @@ Future<int> findPreferredPort(int defaultPort, { int searchStep: 2 }) async { ...@@ -142,7 +143,7 @@ Future<int> findPreferredPort(int defaultPort, { int searchStep: 2 }) async {
Future<bool> _isPortAvailable(int port) async { Future<bool> _isPortAvailable(int port) async {
try { try {
ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, port); io.ServerSocket socket = await io.ServerSocket.bind(io.InternetAddress.LOOPBACK_IP_V4, port);
await socket.close(); await socket.close();
return true; return true;
} catch (error) { } catch (error) {
...@@ -156,11 +157,11 @@ Future<bool> _isPortAvailable(int port) async { ...@@ -156,11 +157,11 @@ Future<bool> _isPortAvailable(int port) async {
/// or if the project root is the flutter repository root. /// or if the project root is the flutter repository root.
String findProjectRoot([String directory]) { String findProjectRoot([String directory]) {
const String kProjectRootSentinel = 'pubspec.yaml'; const String kProjectRootSentinel = 'pubspec.yaml';
directory ??= Directory.current.path; directory ??= fs.currentDirectory.path;
while (true) { while (true) {
if (FileSystemEntity.isFileSync(path.join(directory, kProjectRootSentinel))) if (fs.isFileSync(path.join(directory, kProjectRootSentinel)))
return directory; return directory;
String parent = FileSystemEntity.parentOf(directory); String parent = path.dirname(directory);
if (directory == parent) return null; if (directory == parent) return null;
directory = parent; directory = parent;
} }
......
...@@ -4,19 +4,21 @@ ...@@ -4,19 +4,21 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'dart:math' show Random; import 'dart:math' show Random;
import 'package:crypto/crypto.dart'; import 'package:crypto/crypto.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'file_system.dart';
bool get isRunningOnBot { bool get isRunningOnBot {
// https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables // https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables
// CHROME_HEADLESS is one property set on Flutter's Chrome Infra bots. // CHROME_HEADLESS is one property set on Flutter's Chrome Infra bots.
return return
Platform.environment['TRAVIS'] == 'true' || io.Platform.environment['TRAVIS'] == 'true' ||
Platform.environment['CONTINUOUS_INTEGRATION'] == 'true' || io.Platform.environment['CONTINUOUS_INTEGRATION'] == 'true' ||
Platform.environment['CHROME_HEADLESS'] == '1'; io.Platform.environment['CHROME_HEADLESS'] == '1';
} }
String hex(List<int> bytes) { String hex(List<int> bytes) {
...@@ -63,7 +65,7 @@ File getUniqueFile(Directory dir, String baseName, String ext) { ...@@ -63,7 +65,7 @@ File getUniqueFile(Directory dir, String baseName, String ext) {
while (true) { while (true) {
String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext'; String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext';
File file = new File(path.join(dir.path, name)); File file = fs.file(path.join(dir.path, name));
if (!file.existsSync()) if (!file.existsSync())
return file; return file;
i++; i++;
...@@ -91,7 +93,7 @@ String getElapsedAsMilliseconds(Duration duration) { ...@@ -91,7 +93,7 @@ String getElapsedAsMilliseconds(Duration duration) {
/// 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 = Directory.current.path + Platform.pathSeparator; String cwd = fs.currentDirectory.path + io.Platform.pathSeparator;
return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath; return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath;
} }
......
...@@ -3,13 +3,14 @@ ...@@ -3,13 +3,14 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/dart/pub.dart';
import 'package:flutter_tools/src/dart/summary.dart'; import 'package:flutter_tools/src/dart/summary.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'base/context.dart'; import 'base/context.dart';
import 'base/file_system.dart';
import 'base/logger.dart'; import 'base/logger.dart';
import 'base/net.dart'; import 'base/net.dart';
import 'base/os.dart'; import 'base/os.dart';
...@@ -53,7 +54,7 @@ class Cache { ...@@ -53,7 +54,7 @@ class Cache {
if (!_lockEnabled) if (!_lockEnabled)
return null; return null;
assert(_lock == null); assert(_lock == null);
_lock = new File(path.join(flutterRoot, 'bin', 'cache', 'lockfile')).openSync(mode: FileMode.WRITE); _lock = fs.file(path.join(flutterRoot, 'bin', 'cache', 'lockfile')).openSync(mode: FileMode.WRITE);
bool locked = false; bool locked = false;
bool printed = false; bool printed = false;
while (!locked) { while (!locked) {
...@@ -83,7 +84,7 @@ class Cache { ...@@ -83,7 +84,7 @@ class Cache {
static String get dartSdkVersion { static String get dartSdkVersion {
if (_dartSdkVersion == null) { if (_dartSdkVersion == null) {
_dartSdkVersion = Platform.version; _dartSdkVersion = io.Platform.version;
} }
return _dartSdkVersion; return _dartSdkVersion;
} }
...@@ -92,7 +93,7 @@ class Cache { ...@@ -92,7 +93,7 @@ class Cache {
static String get engineRevision { static String get engineRevision {
if (_engineRevision == null) { if (_engineRevision == null) {
File revisionFile = new File(path.join(flutterRoot, 'bin', 'internal', 'engine.version')); File revisionFile = fs.file(path.join(flutterRoot, 'bin', 'internal', 'engine.version'));
if (revisionFile.existsSync()) if (revisionFile.existsSync())
_engineRevision = revisionFile.readAsStringSync().trim(); _engineRevision = revisionFile.readAsStringSync().trim();
} }
...@@ -104,14 +105,14 @@ class Cache { ...@@ -104,14 +105,14 @@ class Cache {
/// Return the top-level directory in the cache; this is `bin/cache`. /// Return the top-level directory in the cache; this is `bin/cache`.
Directory getRoot() { Directory getRoot() {
if (_rootOverride != null) if (_rootOverride != null)
return new Directory(path.join(_rootOverride.path, 'bin', 'cache')); return fs.directory(path.join(_rootOverride.path, 'bin', 'cache'));
else else
return new Directory(path.join(flutterRoot, 'bin', 'cache')); return fs.directory(path.join(flutterRoot, 'bin', '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 = new Directory(path.join(getRoot().path, name)); Directory dir = fs.directory(path.join(getRoot().path, name));
if (!dir.existsSync()) if (!dir.existsSync())
dir.createSync(recursive: true); dir.createSync(recursive: true);
return dir; return dir;
...@@ -123,11 +124,11 @@ class Cache { ...@@ -123,11 +124,11 @@ class Cache {
/// Get a named directory from with the cache's artifact directory; for example, /// Get a named directory from with the cache's artifact directory; for example,
/// `material_fonts` would return `bin/cache/artifacts/material_fonts`. /// `material_fonts` would return `bin/cache/artifacts/material_fonts`.
Directory getArtifactDirectory(String name) { Directory getArtifactDirectory(String name) {
return new Directory(path.join(getCacheArtifacts().path, name)); return fs.directory(path.join(getCacheArtifacts().path, name));
} }
String getVersionFor(String artifactName) { String getVersionFor(String artifactName) {
File versionFile = new File(path.join(_rootOverride?.path ?? flutterRoot, 'bin', 'internal', '$artifactName.version')); File versionFile = fs.file(path.join(_rootOverride?.path ?? flutterRoot, 'bin', 'internal', '$artifactName.version'));
return versionFile.existsSync() ? versionFile.readAsStringSync().trim() : null; return versionFile.existsSync() ? versionFile.readAsStringSync().trim() : null;
} }
...@@ -141,7 +142,7 @@ class Cache { ...@@ -141,7 +142,7 @@ class Cache {
} }
File getStampFileFor(String artifactName) { File getStampFileFor(String artifactName) {
return new File(path.join(getRoot().path, '$artifactName.stamp')); return fs.file(path.join(getRoot().path, '$artifactName.stamp'));
} }
bool isUpToDate() { bool isUpToDate() {
...@@ -157,11 +158,11 @@ class Cache { ...@@ -157,11 +158,11 @@ class Cache {
Uri url = Uri.parse(urlStr); Uri url = Uri.parse(urlStr);
Directory thirdPartyDir = getArtifactDirectory('third_party'); Directory thirdPartyDir = getArtifactDirectory('third_party');
Directory serviceDir = new Directory(path.join(thirdPartyDir.path, serviceName)); Directory serviceDir = fs.directory(path.join(thirdPartyDir.path, serviceName));
if (!serviceDir.existsSync()) if (!serviceDir.existsSync())
serviceDir.createSync(recursive: true); serviceDir.createSync(recursive: true);
File cachedFile = new File(path.join(serviceDir.path, url.pathSegments.last)); File cachedFile = fs.file(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);
...@@ -198,7 +199,7 @@ class Cache { ...@@ -198,7 +199,7 @@ class Cache {
if (location is Directory && !location.existsSync()) if (location is Directory && !location.existsSync())
location.createSync(recursive: true); location.createSync(recursive: true);
File tempFile = new File(path.join(Directory.systemTemp.path, '${url.toString().hashCode}.zip')); File tempFile = fs.file(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();
...@@ -263,9 +264,9 @@ class FlutterEngine { ...@@ -263,9 +264,9 @@ class FlutterEngine {
if (cache.includeAllPlatforms) if (cache.includeAllPlatforms)
dirs.addAll(<String>['ios', 'ios-profile', 'ios-release', 'linux-x64']); dirs.addAll(<String>['ios', 'ios-profile', 'ios-release', 'linux-x64']);
else if (Platform.isMacOS) else if (io.Platform.isMacOS)
dirs.addAll(<String>['ios', 'ios-profile', 'ios-release']); dirs.addAll(<String>['ios', 'ios-profile', 'ios-release']);
else if (Platform.isLinux) else if (io.Platform.isLinux)
dirs.add('linux-x64'); dirs.add('linux-x64');
return dirs; return dirs;
...@@ -277,9 +278,9 @@ class FlutterEngine { ...@@ -277,9 +278,9 @@ class FlutterEngine {
return <List<String>>[] return <List<String>>[]
..addAll(_osxToolsDirs) ..addAll(_osxToolsDirs)
..addAll(_linuxToolsDirs); ..addAll(_linuxToolsDirs);
else if (Platform.isMacOS) else if (io.Platform.isMacOS)
return _osxToolsDirs; return _osxToolsDirs;
else if (Platform.isLinux) else if (io.Platform.isLinux)
return _linuxToolsDirs; return _linuxToolsDirs;
else else
return <List<String>>[]; return <List<String>>[];
...@@ -302,24 +303,24 @@ class FlutterEngine { ...@@ -302,24 +303,24 @@ class FlutterEngine {
for (String pkgName in _getPackageDirs()) { for (String pkgName in _getPackageDirs()) {
String pkgPath = path.join(pkgDir.path, pkgName); String pkgPath = path.join(pkgDir.path, pkgName);
String dotPackagesPath = path.join(pkgPath, '.packages'); String dotPackagesPath = path.join(pkgPath, '.packages');
if (!new Directory(pkgPath).existsSync()) if (!fs.directory(pkgPath).existsSync())
return false; return false;
if (!new File(dotPackagesPath).existsSync()) if (!fs.file(dotPackagesPath).existsSync())
return false; return false;
} }
if (!new File(path.join(pkgDir.path, kSkyEngine, kSdkBundle)).existsSync()) if (!fs.file(path.join(pkgDir.path, kSkyEngine, kSdkBundle)).existsSync())
return false; return false;
Directory engineDir = cache.getArtifactDirectory(kName); Directory engineDir = cache.getArtifactDirectory(kName);
for (String dirName in _getEngineDirs()) { for (String dirName in _getEngineDirs()) {
Directory dir = new Directory(path.join(engineDir.path, dirName)); Directory dir = fs.directory(path.join(engineDir.path, dirName));
if (!dir.existsSync()) if (!dir.existsSync())
return false; return false;
} }
for (List<String> toolsDir in _getToolsDirs()) { for (List<String> toolsDir in _getToolsDirs()) {
Directory dir = new Directory(path.join(engineDir.path, toolsDir[0])); Directory dir = fs.directory(path.join(engineDir.path, toolsDir[0]));
if (!dir.existsSync()) if (!dir.existsSync())
return false; return false;
} }
...@@ -334,7 +335,7 @@ class FlutterEngine { ...@@ -334,7 +335,7 @@ class FlutterEngine {
Directory pkgDir = cache.getCacheDir('pkg'); Directory pkgDir = cache.getCacheDir('pkg');
for (String pkgName in _getPackageDirs()) { for (String pkgName in _getPackageDirs()) {
String pkgPath = path.join(pkgDir.path, pkgName); String pkgPath = path.join(pkgDir.path, pkgName);
Directory dir = new Directory(pkgPath); 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);
...@@ -354,12 +355,12 @@ class FlutterEngine { ...@@ -354,12 +355,12 @@ class FlutterEngine {
engineDir.deleteSync(recursive: true); engineDir.deleteSync(recursive: true);
for (String dirName in _getEngineDirs()) { for (String dirName in _getEngineDirs()) {
Directory dir = new Directory(path.join(engineDir.path, dirName)); Directory dir = fs.directory(path.join(engineDir.path, dirName));
await _downloadItem('Downloading engine artifacts $dirName...', await _downloadItem('Downloading engine artifacts $dirName...',
url + dirName + '/artifacts.zip', dir); url + dirName + '/artifacts.zip', dir);
File frameworkZip = new File(path.join(dir.path, 'Flutter.framework.zip')); File frameworkZip = fs.file(path.join(dir.path, 'Flutter.framework.zip'));
if (frameworkZip.existsSync()) { if (frameworkZip.existsSync()) {
Directory framework = new Directory(path.join(dir.path, 'Flutter.framework')); Directory framework = fs.directory(path.join(dir.path, 'Flutter.framework'));
framework.createSync(); framework.createSync();
os.unzip(frameworkZip, framework); os.unzip(frameworkZip, framework);
} }
...@@ -368,7 +369,7 @@ class FlutterEngine { ...@@ -368,7 +369,7 @@ class FlutterEngine {
for (List<String> toolsDir in _getToolsDirs()) { for (List<String> toolsDir in _getToolsDirs()) {
String cacheDir = toolsDir[0]; String cacheDir = toolsDir[0];
String urlPath = toolsDir[1]; String urlPath = toolsDir[1];
Directory dir = new Directory(path.join(engineDir.path, cacheDir)); Directory dir = fs.directory(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);
} }
......
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import '../base/file_system.dart';
import '../runner/flutter_command.dart'; import '../runner/flutter_command.dart';
import 'analyze_continuously.dart'; import 'analyze_continuously.dart';
import 'analyze_once.dart'; import 'analyze_once.dart';
...@@ -46,7 +46,7 @@ class AnalyzeCommand extends FlutterCommand { ...@@ -46,7 +46,7 @@ class AnalyzeCommand extends FlutterCommand {
return false; return false;
// Or we're not in a project directory. // Or we're not in a project directory.
if (!new File('pubspec.yaml').existsSync()) if (!fs.file('pubspec.yaml').existsSync())
return false; return false;
return super.shouldRunPub; return super.shouldRunPub;
......
...@@ -3,11 +3,12 @@ ...@@ -3,11 +3,12 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:args/args.dart'; import 'package:args/args.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/file_system.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../cache.dart'; import '../cache.dart';
import '../globals.dart'; import '../globals.dart';
...@@ -25,7 +26,7 @@ abstract class AnalyzeBase { ...@@ -25,7 +26,7 @@ abstract class AnalyzeBase {
void dumpErrors(Iterable<String> errors) { void dumpErrors(Iterable<String> errors) {
if (argResults['write'] != null) { if (argResults['write'] != null) {
try { try {
final RandomAccessFile resultsFile = new File(argResults['write']).openSync(mode: FileMode.WRITE); final RandomAccessFile resultsFile = fs.file(argResults['write']).openSync(mode: FileMode.WRITE);
try { try {
resultsFile.lockSync(); resultsFile.lockSync();
resultsFile.writeStringSync(errors.join('\n')); resultsFile.writeStringSync(errors.join('\n'));
...@@ -45,7 +46,7 @@ abstract class AnalyzeBase { ...@@ -45,7 +46,7 @@ abstract class AnalyzeBase {
'issues': errorCount, 'issues': errorCount,
'missingDartDocs': membersMissingDocumentation 'missingDartDocs': membersMissingDocumentation
}; };
new File(benchmarkOut).writeAsStringSync(toPrettyJson(data)); fs.file(benchmarkOut).writeAsStringSync(toPrettyJson(data));
printStatus('Analysis benchmark written to $benchmarkOut ($data).'); printStatus('Analysis benchmark written to $benchmarkOut ($data).');
} }
...@@ -58,11 +59,11 @@ bool inRepo(List<String> fileList) { ...@@ -58,11 +59,11 @@ bool inRepo(List<String> fileList) {
if (fileList == null || fileList.isEmpty) if (fileList == null || fileList.isEmpty)
fileList = <String>[path.current]; fileList = <String>[path.current];
String root = path.normalize(path.absolute(Cache.flutterRoot)); String root = path.normalize(path.absolute(Cache.flutterRoot));
String prefix = root + Platform.pathSeparator; String prefix = root + io.Platform.pathSeparator;
for (String file in fileList) { for (String file in fileList) {
file = path.normalize(path.absolute(file)); file = path.normalize(path.absolute(file));
if (file == root || file.startsWith(prefix)) if (file == root || file.startsWith(prefix))
return true; return true;
} }
return false; return false;
} }
\ No newline at end of file
...@@ -4,12 +4,13 @@ ...@@ -4,12 +4,13 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'package:args/args.dart'; import 'package:args/args.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
import '../base/utils.dart'; import '../base/utils.dart';
...@@ -42,8 +43,8 @@ class AnalyzeContinuously extends AnalyzeBase { ...@@ -42,8 +43,8 @@ class AnalyzeContinuously extends AnalyzeBase {
for (String projectPath in directories) for (String projectPath in directories)
printTrace(' ${path.relative(projectPath)}'); printTrace(' ${path.relative(projectPath)}');
} else { } else {
directories = <String>[Directory.current.path]; directories = <String>[fs.currentDirectory.path];
analysisTarget = Directory.current.path; analysisTarget = fs.currentDirectory.path;
} }
AnalysisServer server = new AnalysisServer(dartSdkPath, directories); AnalysisServer server = new AnalysisServer(dartSdkPath, directories);
...@@ -78,7 +79,7 @@ class AnalyzeContinuously extends AnalyzeBase { ...@@ -78,7 +79,7 @@ class AnalyzeContinuously extends AnalyzeBase {
// Remove errors for deleted files, sort, and print errors. // Remove errors for deleted files, sort, and print errors.
final List<AnalysisError> errors = <AnalysisError>[]; final List<AnalysisError> errors = <AnalysisError>[];
for (String path in analysisErrors.keys.toList()) { for (String path in analysisErrors.keys.toList()) {
if (FileSystemEntity.isFileSync(path)) { if (fs.isFileSync(path)) {
errors.addAll(analysisErrors[path]); errors.addAll(analysisErrors[path]);
} else { } else {
analysisErrors.remove(path); analysisErrors.remove(path);
...@@ -149,7 +150,7 @@ class AnalysisServer { ...@@ -149,7 +150,7 @@ class AnalysisServer {
final String sdk; final String sdk;
final List<String> directories; final List<String> directories;
Process _process; io.Process _process;
StreamController<bool> _analyzingController = new StreamController<bool>.broadcast(); StreamController<bool> _analyzingController = new StreamController<bool>.broadcast();
StreamController<FileAnalysisErrors> _errorsController = new StreamController<FileAnalysisErrors>.broadcast(); StreamController<FileAnalysisErrors> _errorsController = new StreamController<FileAnalysisErrors>.broadcast();
......
...@@ -4,13 +4,13 @@ ...@@ -4,13 +4,13 @@
import 'dart:async'; import 'dart:async';
import 'dart:collection'; import 'dart:collection';
import 'dart:io';
import 'package:args/args.dart'; import 'package:args/args.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart' as yaml; import 'package:yaml/yaml.dart' as yaml;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../cache.dart'; import '../cache.dart';
import '../dart/analysis.dart'; import '../dart/analysis.dart';
import '../globals.dart'; import '../globals.dart';
...@@ -36,11 +36,11 @@ class AnalyzeOnce extends AnalyzeBase { ...@@ -36,11 +36,11 @@ class AnalyzeOnce extends AnalyzeBase {
for (String file in argResults.rest.toList()) { for (String file in argResults.rest.toList()) {
file = path.normalize(path.absolute(file)); file = path.normalize(path.absolute(file));
String root = path.rootPrefix(file); String root = path.rootPrefix(file);
dartFiles.add(new File(file)); dartFiles.add(fs.file(file));
while (file != root) { while (file != root) {
file = path.dirname(file); file = path.dirname(file);
if (FileSystemEntity.isFileSync(path.join(file, 'pubspec.yaml'))) { if (fs.isFileSync(path.join(file, 'pubspec.yaml'))) {
pubSpecDirectories.add(new Directory(file)); pubSpecDirectories.add(fs.directory(file));
break; break;
} }
} }
...@@ -54,7 +54,7 @@ class AnalyzeOnce extends AnalyzeBase { ...@@ -54,7 +54,7 @@ class AnalyzeOnce extends AnalyzeBase {
if (currentDirectory && !flutterRepo) { if (currentDirectory && !flutterRepo) {
// ./*.dart // ./*.dart
Directory currentDirectory = new Directory('.'); 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)) {
...@@ -68,7 +68,7 @@ class AnalyzeOnce extends AnalyzeBase { ...@@ -68,7 +68,7 @@ class AnalyzeOnce extends AnalyzeBase {
if (currentPackage && !flutterRepo) { if (currentPackage && !flutterRepo) {
// **/.*dart // **/.*dart
Directory currentDirectory = new Directory('.'); Directory currentDirectory = fs.directory('.');
_collectDartFiles(currentDirectory, dartFiles); _collectDartFiles(currentDirectory, dartFiles);
pubSpecDirectories.add(currentDirectory); pubSpecDirectories.add(currentDirectory);
} }
...@@ -89,18 +89,18 @@ class AnalyzeOnce extends AnalyzeBase { ...@@ -89,18 +89,18 @@ class AnalyzeOnce extends AnalyzeBase {
PackageDependencyTracker dependencies = new PackageDependencyTracker(); PackageDependencyTracker dependencies = new PackageDependencyTracker();
for (Directory directory in pubSpecDirectories) { for (Directory directory in pubSpecDirectories) {
String pubSpecYamlPath = path.join(directory.path, 'pubspec.yaml'); String pubSpecYamlPath = path.join(directory.path, 'pubspec.yaml');
File pubSpecYamlFile = new File(pubSpecYamlPath); 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(new File(pubSpecYamlPath).readAsStringSync()); yaml.YamlMap pubSpecYaml = yaml.loadYaml(fs.file(pubSpecYamlPath).readAsStringSync());
String packageName = pubSpecYaml['name']; String packageName = pubSpecYaml['name'];
String packagePath = path.normalize(path.absolute(path.join(directory.path, 'lib'))); String packagePath = path.normalize(path.absolute(path.join(directory.path, 'lib')));
dependencies.addCanonicalCase(packageName, packagePath, pubSpecYamlPath); dependencies.addCanonicalCase(packageName, packagePath, pubSpecYamlPath);
} }
String dotPackagesPath = path.join(directory.path, '.packages'); String dotPackagesPath = path.join(directory.path, '.packages');
File dotPackages = new File(dotPackagesPath); 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
...@@ -228,7 +228,7 @@ class AnalyzeOnce extends AnalyzeBase { ...@@ -228,7 +228,7 @@ class AnalyzeOnce extends AnalyzeBase {
List<File> _collectDartFiles(Directory dir, List<File> collected, {FileFilter exclude}) { List<File> _collectDartFiles(Directory dir, List<File> collected, {FileFilter exclude}) {
// Bail out in case of a .dartignore. // Bail out in case of a .dartignore.
if (FileSystemEntity.isFileSync(path.join(path.dirname(dir.path), '.dartignore'))) if (fs.isFileSync(path.join(path.dirname(dir.path), '.dartignore')))
return collected; return collected;
for (FileSystemEntity entity in dir.listSync(recursive: false, followLinks: false)) { for (FileSystemEntity entity in dir.listSync(recursive: false, followLinks: false)) {
......
...@@ -3,10 +3,11 @@ ...@@ -3,10 +3,11 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import '../base/file_system.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../globals.dart'; import '../globals.dart';
import '../runner/flutter_command.dart'; import '../runner/flutter_command.dart';
...@@ -54,14 +55,14 @@ abstract class BuildSubCommand extends FlutterCommand { ...@@ -54,14 +55,14 @@ abstract class BuildSubCommand extends FlutterCommand {
@mustCallSuper @mustCallSuper
Future<Null> runCommand() async { Future<Null> runCommand() async {
if (isRunningOnBot) { if (isRunningOnBot) {
File dotPackages = new File('.packages'); 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 = new File('pubspec.lock'); 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,8 +87,8 @@ class BuildCleanCommand extends FlutterCommand { ...@@ -86,8 +87,8 @@ class BuildCleanCommand extends FlutterCommand {
@override @override
Future<Null> runCommand() async { Future<Null> runCommand() async {
Directory buildDir = new Directory(getBuildDirectory()); Directory buildDir = fs.directory(getBuildDirectory());
printStatus("Deleting '${buildDir.path}${Platform.pathSeparator}'."); printStatus("Deleting '${buildDir.path}${io.Platform.pathSeparator}'.");
if (!buildDir.existsSync()) if (!buildDir.existsSync())
return; return;
......
...@@ -3,11 +3,12 @@ ...@@ -3,11 +3,12 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/utils.dart'; import '../base/utils.dart';
...@@ -64,7 +65,7 @@ class BuildAotCommand extends BuildSubCommand { ...@@ -64,7 +65,7 @@ class BuildAotCommand extends BuildSubCommand {
if (outputPath == null) if (outputPath == null)
throwToolExit(null); throwToolExit(null);
printStatus('Built to $outputPath${Platform.pathSeparator}.'); printStatus('Built to $outputPath${io.Platform.pathSeparator}.');
} }
} }
...@@ -142,7 +143,7 @@ Future<String> _buildAotSnapshot( ...@@ -142,7 +143,7 @@ Future<String> _buildAotSnapshot(
} }
} }
Directory outputDir = new Directory(outputPath); Directory outputDir = fs.directory(outputPath);
outputDir.createSync(recursive: true); outputDir.createSync(recursive: true);
String vmIsolateSnapshot = path.join(outputDir.path, 'snapshot_aot_vmisolate'); String vmIsolateSnapshot = path.join(outputDir.path, 'snapshot_aot_vmisolate');
String isolateSnapshot = path.join(outputDir.path, 'snapshot_aot_isolate'); String isolateSnapshot = path.join(outputDir.path, 'snapshot_aot_isolate');
...@@ -201,7 +202,7 @@ Future<String> _buildAotSnapshot( ...@@ -201,7 +202,7 @@ Future<String> _buildAotSnapshot(
assert(false); assert(false);
} }
List<String> missingFiles = filePaths.where((String p) => !FileSystemEntity.isFileSync(p)).toList(); 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;
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../android/android.dart' as android; import '../android/android.dart' as android;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../cache.dart'; import '../cache.dart';
import '../dart/pub.dart'; import '../dart/pub.dart';
...@@ -72,14 +72,14 @@ class CreateCommand extends FlutterCommand { ...@@ -72,14 +72,14 @@ class CreateCommand extends FlutterCommand {
String flutterPackagesDirectory = path.join(flutterRoot, 'packages'); String flutterPackagesDirectory = path.join(flutterRoot, 'packages');
String flutterPackagePath = path.join(flutterPackagesDirectory, 'flutter'); String flutterPackagePath = path.join(flutterPackagesDirectory, 'flutter');
if (!FileSystemEntity.isFileSync(path.join(flutterPackagePath, 'pubspec.yaml'))) if (!fs.isFileSync(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 = path.join(flutterRoot, 'packages', 'flutter_driver'); String flutterDriverPackagePath = path.join(flutterRoot, 'packages', 'flutter_driver');
if (!FileSystemEntity.isFileSync(path.join(flutterDriverPackagePath, 'pubspec.yaml'))) if (!fs.isFileSync(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 = new Directory(argResults.rest.first); Directory projectDir = fs.directory(argResults.rest.first);
String dirPath = path.normalize(projectDir.absolute.path); String dirPath = path.normalize(projectDir.absolute.path);
String relativePath = path.relative(dirPath); String relativePath = path.relative(dirPath);
String projectName = _normalizeProjectName(path.basename(dirPath)); String projectName = _normalizeProjectName(path.basename(dirPath));
...@@ -139,7 +139,7 @@ Your main program file is lib/main.dart in the $relativePath directory. ...@@ -139,7 +139,7 @@ Your main program file is lib/main.dart in the $relativePath directory.
int _renderTemplates(String projectName, String projectDescription, String dirPath, int _renderTemplates(String projectName, String projectDescription, String dirPath,
String flutterPackagesDirectory, { bool renderDriverTest: false }) { String flutterPackagesDirectory, { bool renderDriverTest: false }) {
new Directory(dirPath).createSync(recursive: true); fs.directory(dirPath).createSync(recursive: true);
flutterPackagesDirectory = path.normalize(flutterPackagesDirectory); flutterPackagesDirectory = path.normalize(flutterPackagesDirectory);
flutterPackagesDirectory = _relativePath(from: dirPath, to: flutterPackagesDirectory); flutterPackagesDirectory = _relativePath(from: dirPath, to: flutterPackagesDirectory);
...@@ -161,14 +161,14 @@ Your main program file is lib/main.dart in the $relativePath directory. ...@@ -161,14 +161,14 @@ Your main program file is lib/main.dart in the $relativePath directory.
Template createTemplate = new Template.fromName('create'); Template createTemplate = new Template.fromName('create');
fileCount += createTemplate.render( fileCount += createTemplate.render(
new Directory(dirPath), fs.directory(dirPath),
templateContext, overwriteExisting: false, templateContext, overwriteExisting: false,
projectName: projectName projectName: projectName
); );
if (renderDriverTest) { if (renderDriverTest) {
Template driverTemplate = new Template.fromName('driver'); Template driverTemplate = new Template.fromName('driver');
fileCount += driverTemplate.render(new Directory(path.join(dirPath, 'test_driver')), fileCount += driverTemplate.render(fs.directory(path.join(dirPath, 'test_driver')),
templateContext, overwriteExisting: false); templateContext, overwriteExisting: false);
} }
...@@ -234,7 +234,7 @@ String _validateProjectDir(String dirPath, { String flutterRoot }) { ...@@ -234,7 +234,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 = FileSystemEntity.typeSync(dirPath); 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 = path.relative(to, from: from); String result = path.relative(to, from: from);
// `path.relative()` doesn't always return a correct result: dart-lang/path#12. // `path.relative()` doesn't always return a correct result: dart-lang/path#12.
if (FileSystemEntity.isDirectorySync(path.join(from, result))) if (fs.isDirectorySync(path.join(from, result)))
return result; return result;
return to; return to;
} }
...@@ -4,11 +4,12 @@ ...@@ -4,11 +4,12 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import '../android/android_device.dart'; import '../android/android_device.dart';
import '../base/common.dart'; import '../base/common.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../build_info.dart'; import '../build_info.dart';
...@@ -119,7 +120,7 @@ class Daemon { ...@@ -119,7 +120,7 @@ class Daemon {
dynamic id = request['id']; dynamic id = request['id'];
if (id == null) { if (id == null) {
stderr.writeln('no id for request: $request'); io.stderr.writeln('no id for request: $request');
return; return;
} }
...@@ -234,9 +235,9 @@ class DaemonDomain extends Domain { ...@@ -234,9 +235,9 @@ class DaemonDomain extends Domain {
// capture the print output for testing. // capture the print output for testing.
print(message.message); print(message.message);
} else if (message.level == 'error') { } else if (message.level == 'error') {
stderr.writeln(message.message); io.stderr.writeln(message.message);
if (message.stackTrace != null) if (message.stackTrace != null)
stderr.writeln(message.stackTrace.toString().trimRight()); io.stderr.writeln(message.stackTrace.toString().trimRight());
} }
} else { } else {
if (message.stackTrace != null) { if (message.stackTrace != null) {
...@@ -302,7 +303,7 @@ class AppDomain extends Domain { ...@@ -302,7 +303,7 @@ class AppDomain extends Domain {
if (device == null) if (device == null)
throw "device '$deviceId' not found"; throw "device '$deviceId' not found";
if (!FileSystemEntity.isDirectorySync(projectDirectory)) if (!fs.isDirectorySync(projectDirectory))
throw "'$projectDirectory' does not exist"; throw "'$projectDirectory' does not exist";
BuildMode buildMode = getBuildModeForName(mode) ?? BuildMode.debug; BuildMode buildMode = getBuildModeForName(mode) ?? BuildMode.debug;
...@@ -341,8 +342,8 @@ class AppDomain extends Domain { ...@@ -341,8 +342,8 @@ class AppDomain extends Domain {
throw '${toTitleCase(getModeName(buildMode))} mode is not supported for emulators.'; throw '${toTitleCase(getModeName(buildMode))} mode is not supported for emulators.';
// We change the current working directory for the duration of the `start` command. // We change the current working directory for the duration of the `start` command.
Directory cwd = Directory.current; Directory cwd = fs.currentDirectory;
Directory.current = new Directory(projectDirectory); fs.currentDirectory = fs.directory(projectDirectory);
ResidentRunner runner; ResidentRunner runner;
...@@ -400,7 +401,7 @@ class AppDomain extends Domain { ...@@ -400,7 +401,7 @@ class AppDomain extends Domain {
} catch (error) { } catch (error) {
_sendAppEvent(app, 'stop', <String, dynamic>{'error': error.toString()}); _sendAppEvent(app, 'stop', <String, dynamic>{'error': error.toString()});
} finally { } finally {
Directory.current = cwd; fs.currentDirectory = cwd;
_apps.remove(app); _apps.remove(app);
} }
}); });
...@@ -589,7 +590,7 @@ class DeviceDomain extends Domain { ...@@ -589,7 +590,7 @@ class DeviceDomain extends Domain {
} }
} }
Stream<Map<String, dynamic>> get stdinCommandStream => stdin Stream<Map<String, dynamic>> get stdinCommandStream => io.stdin
.transform(UTF8.decoder) .transform(UTF8.decoder)
.transform(const LineSplitter()) .transform(const LineSplitter())
.where((String line) => line.startsWith('[{') && line.endsWith('}]')) .where((String line) => line.startsWith('[{') && line.endsWith('}]'))
...@@ -599,7 +600,7 @@ Stream<Map<String, dynamic>> get stdinCommandStream => stdin ...@@ -599,7 +600,7 @@ Stream<Map<String, dynamic>> get stdinCommandStream => stdin
}); });
void stdoutCommandResponse(Map<String, dynamic> command) { void stdoutCommandResponse(Map<String, dynamic> command) {
stdout.writeln('[${JSON.encode(command, toEncodable: _jsonEncodeObject)}]'); io.stdout.writeln('[${JSON.encode(command, toEncodable: _jsonEncodeObject)}]');
} }
dynamic _jsonEncodeObject(dynamic object) { dynamic _jsonEncodeObject(dynamic object) {
...@@ -709,9 +710,9 @@ class _AppRunLogger extends Logger { ...@@ -709,9 +710,9 @@ class _AppRunLogger extends Logger {
@override @override
void printError(String message, [StackTrace stackTrace]) { void printError(String message, [StackTrace stackTrace]) {
if (logToStdout) { if (logToStdout) {
stderr.writeln(message); io.stderr.writeln(message);
if (stackTrace != null) if (stackTrace != null)
stderr.writeln(stackTrace.toString().trimRight()); io.stderr.writeln(stackTrace.toString().trimRight());
} else { } else {
if (stackTrace != null) { if (stackTrace != null) {
_sendLogEvent(<String, dynamic>{ _sendLogEvent(<String, dynamic>{
......
...@@ -3,9 +3,10 @@ ...@@ -3,9 +3,10 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../cache.dart'; import '../cache.dart';
...@@ -174,7 +175,7 @@ class RunCommand extends RunCommandBase { ...@@ -174,7 +175,7 @@ class RunCommand extends RunCommandBase {
AppInstance app; AppInstance app;
try { try {
app = daemon.appDomain.startApp( app = daemon.appDomain.startApp(
device, Directory.current.path, targetFile, route, device, fs.currentDirectory.path, targetFile, route,
getBuildMode(), argResults['start-paused'], hotMode); getBuildMode(), argResults['start-paused'], hotMode);
} catch (error) { } catch (error) {
throwToolExit(error.toString()); throwToolExit(error.toString());
...@@ -217,7 +218,7 @@ class RunCommand extends RunCommandBase { ...@@ -217,7 +218,7 @@ class RunCommand extends RunCommandBase {
String pidFile = argResults['pid-file']; String pidFile = argResults['pid-file'];
if (pidFile != null) { if (pidFile != null) {
// Write our pid to the file. // Write our pid to the file.
new File(pidFile).writeAsStringSync(pid.toString()); fs.file(pidFile).writeAsStringSync(io.pid.toString());
} }
ResidentRunner runner; ResidentRunner runner;
......
...@@ -3,12 +3,13 @@ ...@@ -3,12 +3,13 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../device.dart'; import '../device.dart';
import '../globals.dart'; import '../globals.dart';
...@@ -72,7 +73,7 @@ class ScreenshotCommand extends FlutterCommand { ...@@ -72,7 +73,7 @@ class ScreenshotCommand extends FlutterCommand {
Future<Null> runCommand() async { Future<Null> runCommand() async {
File outputFile; File outputFile;
if (argResults.wasParsed(_kOut)) if (argResults.wasParsed(_kOut))
outputFile = new File(argResults[_kOut]); outputFile = fs.file(argResults[_kOut]);
if (argResults[_kSkia] != null) { if (argResults[_kSkia] != null) {
return runSkia(outputFile); return runSkia(outputFile);
...@@ -82,7 +83,7 @@ class ScreenshotCommand extends FlutterCommand { ...@@ -82,7 +83,7 @@ class ScreenshotCommand extends FlutterCommand {
} }
Future<Null> runScreenshot(File outputFile) async { Future<Null> runScreenshot(File outputFile) async {
outputFile ??= getUniqueFile(Directory.current, 'flutter', 'png'); outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'png');
try { try {
if (!await device.takeScreenshot(outputFile)) if (!await device.takeScreenshot(outputFile))
throwToolExit('Screenshot failed'); throwToolExit('Screenshot failed');
...@@ -105,10 +106,10 @@ class ScreenshotCommand extends FlutterCommand { ...@@ -105,10 +106,10 @@ class ScreenshotCommand extends FlutterCommand {
http.StreamedResponse skpResponse; http.StreamedResponse skpResponse;
try { try {
skpResponse = await new http.Request('GET', skpUri).send(); skpResponse = await new http.Request('GET', skpUri).send();
} on SocketException catch (e) { } on io.SocketException catch (e) {
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 != io.HttpStatus.OK) {
String error = await skpResponse.stream.toStringStream().join(); String error = await skpResponse.stream.toStringStream().join();
throwToolExit('Error: $error\n\n$errorHelpText'); throwToolExit('Error: $error\n\n$errorHelpText');
} }
...@@ -121,10 +122,10 @@ class ScreenshotCommand extends FlutterCommand { ...@@ -121,10 +122,10 @@ class ScreenshotCommand extends FlutterCommand {
'file', skpResponse.stream, skpResponse.contentLength)); 'file', skpResponse.stream, skpResponse.contentLength));
http.StreamedResponse postResponse = await postRequest.send(); http.StreamedResponse postResponse = await postRequest.send();
if (postResponse.statusCode != HttpStatus.OK) if (postResponse.statusCode != io.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(Directory.current, 'flutter', 'skp'); outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'skp');
IOSink sink = outputFile.openWrite(); IOSink sink = outputFile.openWrite();
await sink.addStream(skpResponse.stream); await sink.addStream(skpResponse.stream);
await sink.close(); await sink.close();
......
...@@ -3,12 +3,13 @@ ...@@ -3,12 +3,13 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:test/src/executable.dart' as test; // ignore: implementation_imports import 'package:test/src/executable.dart' as test; // ignore: implementation_imports
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
import '../base/os.dart'; import '../base/os.dart';
...@@ -39,7 +40,7 @@ class TestCommand extends FlutterCommand { ...@@ -39,7 +40,7 @@ class TestCommand extends FlutterCommand {
help: 'Where to store coverage information (if coverage is enabled).' help: 'Where to store coverage information (if coverage is enabled).'
); );
commandValidator = () { commandValidator = () {
if (!FileSystemEntity.isFileSync('pubspec.yaml')) { if (!fs.isFileSync('pubspec.yaml')) {
throwToolExit( throwToolExit(
'Error: No pubspec.yaml file found in the current working directory.\n' 'Error: No pubspec.yaml file found in the current working directory.\n'
'Run this command from the root of your project. Test files must be\n' 'Run this command from the root of your project. Test files must be\n'
...@@ -58,31 +59,31 @@ class TestCommand extends FlutterCommand { ...@@ -58,31 +59,31 @@ class TestCommand extends FlutterCommand {
Iterable<String> _findTests(Directory directory) { Iterable<String> _findTests(Directory directory) {
return directory.listSync(recursive: true, followLinks: false) return directory.listSync(recursive: true, followLinks: false)
.where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') && .where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') &&
FileSystemEntity.isFileSync(entity.path)) fs.isFileSync(entity.path))
.map((FileSystemEntity entity) => path.absolute(entity.path)); .map((FileSystemEntity entity) => path.absolute(entity.path));
} }
Directory get _currentPackageTestDir { Directory get _currentPackageTestDir {
// We don't scan the entire package, only the test/ subdirectory, so that // We don't scan the entire package, only the test/ subdirectory, so that
// files with names like like "hit_test.dart" don't get run. // files with names like like "hit_test.dart" don't get run.
return new Directory('test'); return fs.directory('test');
} }
Future<int> _runTests(List<String> testArgs, Directory testDirectory) async { Future<int> _runTests(List<String> testArgs, Directory testDirectory) async {
Directory currentDirectory = Directory.current; 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');
PackageMap.globalPackagesPath = path.normalize(path.absolute(PackageMap.globalPackagesPath)); PackageMap.globalPackagesPath = path.normalize(path.absolute(PackageMap.globalPackagesPath));
Directory.current = testDirectory; fs.currentDirectory = testDirectory;
} }
printTrace('running test package with arguments: $testArgs'); printTrace('running test package with arguments: $testArgs');
await test.main(testArgs); await test.main(testArgs);
// test.main() sets dart:io's exitCode global. // test.main() sets dart:io's exitCode global.
printTrace('test package returned with exit code $exitCode'); printTrace('test package returned with exit code ${io.exitCode}');
return exitCode; return io.exitCode;
} finally { } finally {
Directory.current = currentDirectory; fs.currentDirectory = currentDirectory;
} }
} }
...@@ -94,7 +95,7 @@ class TestCommand extends FlutterCommand { ...@@ -94,7 +95,7 @@ class TestCommand extends FlutterCommand {
return false; return false;
String coveragePath = argResults['coverage-path']; String coveragePath = argResults['coverage-path'];
File coverageFile = new File(coveragePath) 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})');
...@@ -109,7 +110,7 @@ class TestCommand extends FlutterCommand { ...@@ -109,7 +110,7 @@ class TestCommand extends FlutterCommand {
return false; return false;
} }
if (!FileSystemEntity.isFileSync(baseCoverageData)) { if (!fs.isFileSync(baseCoverageData)) {
printError('Missing "$baseCoverageData". Unable to merge coverage data.'); printError('Missing "$baseCoverageData". Unable to merge coverage data.');
return false; return false;
} }
...@@ -124,10 +125,10 @@ class TestCommand extends FlutterCommand { ...@@ -124,10 +125,10 @@ class TestCommand extends FlutterCommand {
return false; return false;
} }
Directory tempDir = Directory.systemTemp.createTempSync('flutter_tools'); Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
try { try {
File sourceFile = coverageFile.copySync(path.join(tempDir.path, 'lcov.source.info')); File sourceFile = coverageFile.copySync(path.join(tempDir.path, 'lcov.source.info'));
ProcessResult result = processManager.runSync('lcov', <String>[ io.ProcessResult result = processManager.runSync('lcov', <String>[
'--add-tracefile', baseCoverageData, '--add-tracefile', baseCoverageData,
'--add-tracefile', sourceFile.path, '--add-tracefile', sourceFile.path,
'--output-file', coverageFile.path, '--output-file', coverageFile.path,
...@@ -164,8 +165,8 @@ class TestCommand extends FlutterCommand { ...@@ -164,8 +165,8 @@ class TestCommand extends FlutterCommand {
if (argResults['coverage']) if (argResults['coverage'])
testArgs.insert(0, '--concurrency=1'); testArgs.insert(0, '--concurrency=1');
final String shellPath = tools.getHostToolPath(HostTool.SkyShell) ?? Platform.environment['SKY_SHELL']; final String shellPath = tools.getHostToolPath(HostTool.SkyShell) ?? io.Platform.environment['SKY_SHELL'];
if (!FileSystemEntity.isFileSync(shellPath)) if (!fs.isFileSync(shellPath))
throwToolExit('Cannot find Flutter shell at $shellPath'); throwToolExit('Cannot find Flutter shell at $shellPath');
loader.installHook(shellPath: shellPath); loader.installHook(shellPath: shellPath);
......
...@@ -4,11 +4,11 @@ ...@@ -4,11 +4,11 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../cache.dart'; import '../cache.dart';
...@@ -90,9 +90,9 @@ class TraceCommand extends FlutterCommand { ...@@ -90,9 +90,9 @@ class TraceCommand extends FlutterCommand {
File localFile; File localFile;
if (argResults['out'] != null) { if (argResults['out'] != null) {
localFile = new File(argResults['out']); localFile = fs.file(argResults['out']);
} else { } else {
localFile = getUniqueFile(Directory.current, 'trace', 'json'); localFile = getUniqueFile(fs.currentDirectory, 'trace', 'json');
} }
await localFile.writeAsString(JSON.encode(timeline)); await localFile.writeAsString(JSON.encode(timeline));
...@@ -161,7 +161,7 @@ class Tracing { ...@@ -161,7 +161,7 @@ class Tracing {
/// 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 = path.join(getBuildDirectory(), 'start_up_info.json'); String traceInfoFilePath = path.join(getBuildDirectory(), 'start_up_info.json');
File traceInfoFile = new File(traceInfoFilePath); 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())
......
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/net.dart'; import '../base/net.dart';
import '../cache.dart'; import '../cache.dart';
...@@ -36,10 +36,10 @@ class UpdatePackagesCommand extends FlutterCommand { ...@@ -36,10 +36,10 @@ class UpdatePackagesCommand extends FlutterCommand {
Status status = logger.startProgress("Downloading lcov data for package:flutter..."); Status status = logger.startProgress("Downloading lcov data for package:flutter...");
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 = path.join(Cache.flutterRoot, 'packages/flutter/coverage'); final String coverageDir = path.join(Cache.flutterRoot, 'packages/flutter/coverage');
new File(path.join(coverageDir, 'lcov.base.info')) fs.file(path.join(coverageDir, 'lcov.base.info'))
..createSync(recursive: true) ..createSync(recursive: true)
..writeAsBytesSync(data, flush: true); ..writeAsBytesSync(data, flush: true);
new File(path.join(coverageDir, 'lcov.info')) fs.file(path.join(coverageDir, 'lcov.info'))
..createSync(recursive: true) ..createSync(recursive: true)
..writeAsBytesSync(data, flush: true); ..writeAsBytesSync(data, flush: true);
status.stop(); status.stop();
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:collection'; import 'dart:collection';
import 'dart:io'; import 'dart:io' as io;
import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/file_system.dart' as file_system; import 'package:analyzer/file_system/file_system.dart' as file_system;
...@@ -27,6 +27,8 @@ import 'package:path/path.dart' as path; ...@@ -27,6 +27,8 @@ import 'package:path/path.dart' as path;
import 'package:plugin/manager.dart'; import 'package:plugin/manager.dart';
import 'package:plugin/plugin.dart'; import 'package:plugin/plugin.dart';
import '../base/file_system.dart';
class AnalysisDriver { class AnalysisDriver {
Set<Source> _analyzedSources = new HashSet<Source>(); Set<Source> _analyzedSources = new HashSet<Source>();
...@@ -97,7 +99,7 @@ class AnalysisDriver { ...@@ -97,7 +99,7 @@ class AnalysisDriver {
// Create our list of resolvers. // Create our list of resolvers.
List<UriResolver> resolvers = <UriResolver>[]; List<UriResolver> resolvers = <UriResolver>[];
// Look for an embedder. // Look for an embedder.
EmbedderYamlLocator locator = new EmbedderYamlLocator(packageMap); EmbedderYamlLocator locator = new EmbedderYamlLocator(packageMap);
if (locator.embedderYamls.isNotEmpty) { if (locator.embedderYamls.isNotEmpty) {
...@@ -123,7 +125,7 @@ class AnalysisDriver { ...@@ -123,7 +125,7 @@ class AnalysisDriver {
if (options.packageRootPath != null) { if (options.packageRootPath != null) {
ContextBuilderOptions builderOptions = new ContextBuilderOptions(); ContextBuilderOptions builderOptions = new ContextBuilderOptions();
builderOptions.defaultPackagesDirectoryPath = options.packageRootPath; builderOptions.defaultPackagesDirectoryPath = options.packageRootPath;
ContextBuilder builder = new ContextBuilder(resourceProvider, null, null, ContextBuilder builder = new ContextBuilder(resourceProvider, null, null,
options: builderOptions); options: builderOptions);
PackageMapUriResolver packageUriResolver = new PackageMapUriResolver(resourceProvider, PackageMapUriResolver packageUriResolver = new PackageMapUriResolver(resourceProvider,
builder.convertPackagesToMap(builder.createPackageMap(''))); builder.convertPackagesToMap(builder.createPackageMap('')));
...@@ -183,7 +185,7 @@ class AnalysisDriverException implements Exception { ...@@ -183,7 +185,7 @@ class AnalysisDriverException implements Exception {
} }
class AnalysisErrorDescription { class AnalysisErrorDescription {
static Directory cwd = Directory.current.absolute; static Directory cwd = fs.currentDirectory.absolute;
final AnalysisError error; final AnalysisError error;
final LineInfo line; final LineInfo line;
...@@ -238,10 +240,10 @@ class DriverOptions extends AnalysisOptionsImpl { ...@@ -238,10 +240,10 @@ class DriverOptions extends AnalysisOptionsImpl {
Map<Object, Object> analysisOptions; Map<Object, Object> analysisOptions;
/// Out sink for logging. /// Out sink for logging.
IOSink outSink = stdout; io.IOSink outSink = io.stdout;
/// Error sink for logging. /// Error sink for logging.
IOSink errorSink = stderr; io.IOSink errorSink = io.stderr;
} }
class PackageInfo { class PackageInfo {
...@@ -267,8 +269,8 @@ class PackageInfo { ...@@ -267,8 +269,8 @@ class PackageInfo {
} }
class _StdLogger extends Logger { class _StdLogger extends Logger {
final IOSink outSink; final io.IOSink outSink;
final IOSink errorSink; final io.IOSink errorSink;
_StdLogger({this.outSink, this.errorSink}); _StdLogger({this.outSink, this.errorSink});
@override @override
......
...@@ -2,15 +2,15 @@ ...@@ -2,15 +2,15 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:package_config/packages_file.dart' as packages_file; import 'package:package_config/packages_file.dart' as packages_file;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
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 = new File(packagesPath).readAsBytesSync(); 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));
} }
...@@ -51,11 +51,11 @@ class PackageMap { ...@@ -51,11 +51,11 @@ class PackageMap {
} }
String checkValid() { String checkValid() {
if (FileSystemEntity.isFileSync(packagesPath)) if (fs.isFileSync(packagesPath))
return null; return null;
String message = '$packagesPath does not exist.'; String message = '$packagesPath does not exist.';
String pubspecPath = path.absolute(path.dirname(packagesPath), 'pubspec.yaml'); String pubspecPath = path.absolute(path.dirname(packagesPath), 'pubspec.yaml');
if (FileSystemEntity.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
message += '\nDid you run this command from the same directory as your pubspec.yaml file?'; message += '\nDid you run this command from the same directory as your pubspec.yaml file?';
......
...@@ -3,11 +3,11 @@ ...@@ -3,11 +3,11 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../cache.dart'; import '../cache.dart';
...@@ -21,7 +21,8 @@ bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) { ...@@ -21,7 +21,8 @@ bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) {
if (pubSpecYaml.lastModifiedSync().isAfter(dotPackagesLastModified)) if (pubSpecYaml.lastModifiedSync().isAfter(dotPackagesLastModified))
return true; return true;
File flutterToolsStamp = Cache.instance.getStampFileFor('flutter_tools'); File flutterToolsStamp = Cache.instance.getStampFileFor('flutter_tools');
if (flutterToolsStamp.lastModifiedSync().isAfter(dotPackagesLastModified)) if (flutterToolsStamp.existsSync() &&
flutterToolsStamp.lastModifiedSync().isAfter(dotPackagesLastModified))
return true; return true;
return false; return false;
} }
...@@ -33,10 +34,10 @@ Future<Null> pubGet({ ...@@ -33,10 +34,10 @@ Future<Null> pubGet({
bool checkLastModified: true bool checkLastModified: true
}) async { }) async {
if (directory == null) if (directory == null)
directory = Directory.current.path; directory = fs.currentDirectory.path;
File pubSpecYaml = new File(path.join(directory, 'pubspec.yaml')); File pubSpecYaml = fs.file(path.join(directory, 'pubspec.yaml'));
File dotPackages = new File(path.join(directory, '.packages')); File dotPackages = fs.file(path.join(directory, '.packages'));
if (!pubSpecYaml.existsSync()) { if (!pubSpecYaml.existsSync()) {
if (!skipIfAbsent) if (!skipIfAbsent)
......
...@@ -2,10 +2,9 @@ ...@@ -2,10 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'globals.dart'; import 'globals.dart';
import 'base/file_system.dart';
import 'dart/dependencies.dart'; import 'dart/dependencies.dart';
import 'dart/package_map.dart'; import 'dart/package_map.dart';
import 'asset.dart'; import 'asset.dart';
...@@ -51,7 +50,7 @@ class DependencyChecker { ...@@ -51,7 +50,7 @@ class DependencyChecker {
// Check all dependency modification times. // Check all dependency modification times.
for (String path in _dependencies) { for (String path in _dependencies) {
File file = new File(path); File file = fs.file(path);
FileStat stat = file.statSync(); 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.');
......
...@@ -4,11 +4,12 @@ ...@@ -4,11 +4,12 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert' show BASE64, UTF8; import 'dart:convert' show BASE64, UTF8;
import 'dart:io'; import 'dart:io' as io;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'base/context.dart'; import 'base/context.dart';
import 'base/file_system.dart';
import 'build_info.dart'; import 'build_info.dart';
import 'dart/package_map.dart'; import 'dart/package_map.dart';
import 'asset.dart'; import 'asset.dart';
...@@ -89,7 +90,7 @@ class DevFSEntry { ...@@ -89,7 +90,7 @@ class DevFSEntry {
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(); String resolved = file.resolveSymbolicLinksSync();
FileSystemEntity linkTarget = new File(resolved); 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) {
...@@ -104,7 +105,7 @@ class DevFSEntry { ...@@ -104,7 +105,7 @@ class DevFSEntry {
} }
if (file is Link) { if (file is Link) {
// The link target. // The link target.
return new File(file.resolveSymbolicLinksSync()); return fs.file(file.resolveSymbolicLinksSync());
} }
return file; return file;
} }
...@@ -126,7 +127,7 @@ class DevFSEntry { ...@@ -126,7 +127,7 @@ class DevFSEntry {
} }
Stream<List<int>> contentsAsCompressedStream() { Stream<List<int>> contentsAsCompressedStream() {
return contentsAsStream().transform(GZIP.encoder); return contentsAsStream().transform(io.GZIP.encoder);
} }
} }
...@@ -213,13 +214,13 @@ class _DevFSHttpWriter { ...@@ -213,13 +214,13 @@ class _DevFSHttpWriter {
int _inFlight = 0; int _inFlight = 0;
List<DevFSEntry> _outstanding; List<DevFSEntry> _outstanding;
Completer<Null> _completer; Completer<Null> _completer;
HttpClient _client; io.HttpClient _client;
int _done; int _done;
int _max; int _max;
Future<Null> write(Set<DevFSEntry> entries, Future<Null> write(Set<DevFSEntry> entries,
{DevFSProgressReporter progressReporter}) async { {DevFSProgressReporter progressReporter}) async {
_client = new HttpClient(); _client = new io.HttpClient();
_client.maxConnectionsPerHost = kMaxInFlight; _client.maxConnectionsPerHost = kMaxInFlight;
_completer = new Completer<Null>(); _completer = new Completer<Null>();
_outstanding = entries.toList(); _outstanding = entries.toList();
...@@ -245,14 +246,14 @@ class _DevFSHttpWriter { ...@@ -245,14 +246,14 @@ class _DevFSHttpWriter {
Future<Null> _scheduleWrite(DevFSEntry entry, Future<Null> _scheduleWrite(DevFSEntry entry,
DevFSProgressReporter progressReporter) async { DevFSProgressReporter progressReporter) async {
try { try {
HttpClientRequest request = await _client.putUrl(httpAddress); io.HttpClientRequest request = await _client.putUrl(httpAddress);
request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING); request.headers.removeAll(io.HttpHeaders.ACCEPT_ENCODING);
request.headers.add('dev_fs_name', fsName); request.headers.add('dev_fs_name', fsName);
request.headers.add('dev_fs_path_b64', request.headers.add('dev_fs_path_b64',
BASE64.encode(UTF8.encode(entry.devicePath))); BASE64.encode(UTF8.encode(entry.devicePath)));
Stream<List<int>> contents = entry.contentsAsCompressedStream(); Stream<List<int>> contents = entry.contentsAsCompressedStream();
await request.addStream(contents); await request.addStream(contents);
HttpClientResponse response = await request.close(); io.HttpClientResponse response = await request.close();
await response.drain(); await response.drain();
} catch (e, stackTrace) { } catch (e, stackTrace) {
printError('Error writing "${entry.devicePath}" to DevFS: $e\n$stackTrace'); printError('Error writing "${entry.devicePath}" to DevFS: $e\n$stackTrace');
...@@ -353,7 +354,7 @@ class DevFS { ...@@ -353,7 +354,7 @@ class DevFS {
printTrace('Scanning package files'); printTrace('Scanning package files');
StringBuffer sb; StringBuffer sb;
if (FileSystemEntity.isFileSync(_packagesFilePath)) { if (fs.isFileSync(_packagesFilePath)) {
PackageMap packageMap = new PackageMap(_packagesFilePath); PackageMap packageMap = new PackageMap(_packagesFilePath);
for (String packageName in packageMap.map.keys) { for (String packageName in packageMap.map.keys) {
...@@ -368,7 +369,7 @@ class DevFS { ...@@ -368,7 +369,7 @@ class DevFS {
// path imports within the project's own code. // path imports within the project's own code.
final String packagesDirectoryName = final String packagesDirectoryName =
isProjectPackage ? 'packages/$packageName' : null; isProjectPackage ? 'packages/$packageName' : null;
Directory directory = new Directory.fromUri(uri); Directory directory = fs.directory(uri);
bool packageExists = bool packageExists =
await _scanDirectory(directory, await _scanDirectory(directory,
directoryName: directoryName, directoryName: directoryName,
...@@ -527,7 +528,7 @@ class DevFS { ...@@ -527,7 +528,7 @@ class DevFS {
// Check if this is a symlink to a directory and skip it. // Check if this is a symlink to a directory and skip it.
final String linkPath = file.resolveSymbolicLinksSync(); final String linkPath = file.resolveSymbolicLinksSync();
final FileSystemEntityType linkType = final FileSystemEntityType linkType =
FileStat.statSync(linkPath).type; fs.statSync(linkPath).type;
if (linkType == FileSystemEntityType.DIRECTORY) { if (linkType == FileSystemEntityType.DIRECTORY) {
continue; continue;
} }
......
...@@ -3,13 +3,13 @@ ...@@ -3,13 +3,13 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'dart:math' as math; import 'dart:math' as math;
import 'android/android_device.dart'; import 'android/android_device.dart';
import 'application_package.dart'; import 'application_package.dart';
import 'base/common.dart'; import 'base/common.dart';
import 'base/context.dart'; import 'base/context.dart';
import 'base/file_system.dart';
import 'base/os.dart'; import 'base/os.dart';
import 'base/utils.dart'; import 'base/utils.dart';
import 'build_info.dart'; import 'build_info.dart';
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:archive/archive.dart'; import 'package:archive/archive.dart';
import 'dart:convert' show UTF8; import 'dart:convert' show UTF8;
...@@ -12,6 +12,7 @@ import 'package:path/path.dart' as path; ...@@ -12,6 +12,7 @@ import 'package:path/path.dart' as path;
import 'android/android_workflow.dart'; import 'android/android_workflow.dart';
import 'base/common.dart'; import 'base/common.dart';
import 'base/context.dart'; import 'base/context.dart';
import 'base/file_system.dart';
import 'device.dart'; import 'device.dart';
import 'globals.dart'; import 'globals.dart';
import 'ios/ios_workflow.dart'; import 'ios/ios_workflow.dart';
...@@ -26,7 +27,7 @@ const Map<String, String> _osNames = const <String, String>{ ...@@ -26,7 +27,7 @@ const Map<String, String> _osNames = const <String, String>{
}; };
String osName() { String osName() {
String os = Platform.operatingSystem; String os = io.Platform.operatingSystem;
return _osNames.containsKey(os) ? _osNames[os] : os; return _osNames.containsKey(os) ? _osNames[os] : os;
} }
...@@ -123,7 +124,7 @@ class Doctor { ...@@ -123,7 +124,7 @@ class Doctor {
else else
printStatus('${result.leadingBox} ${validator.title}'); printStatus('${result.leadingBox} ${validator.title}');
final String separator = Platform.isWindows ? ' ' : '•'; final String separator = io.Platform.isWindows ? ' ' : '•';
for (ValidationMessage message in result.messages) { for (ValidationMessage message in result.messages) {
String text = message.message.replaceAll('\n', '\n '); String text = message.message.replaceAll('\n', '\n ');
...@@ -181,7 +182,7 @@ class ValidationResult { ...@@ -181,7 +182,7 @@ class ValidationResult {
if (type == ValidationType.missing) if (type == ValidationType.missing)
return '[x]'; return '[x]';
else if (type == ValidationType.installed) else if (type == ValidationType.installed)
return Platform.isWindows ? '[+]' : '[✓]'; return io.Platform.isWindows ? '[+]' : '[✓]';
else else
return '[-]'; return '[-]';
} }
...@@ -216,7 +217,7 @@ class _FlutterValidator extends DoctorValidator { ...@@ -216,7 +217,7 @@ class _FlutterValidator extends DoctorValidator {
messages.add(new ValidationMessage('Engine revision ${version.engineRevisionShort}')); messages.add(new ValidationMessage('Engine revision ${version.engineRevisionShort}'));
messages.add(new ValidationMessage('Tools Dart version ${version.dartSdkVersion}')); messages.add(new ValidationMessage('Tools Dart version ${version.dartSdkVersion}'));
if (Platform.isWindows) { if (io.Platform.isWindows) {
valid = ValidationType.missing; valid = ValidationType.missing;
messages.add(new ValidationMessage.error( messages.add(new ValidationMessage.error(
...@@ -253,9 +254,9 @@ abstract class IntelliJValidator extends DoctorValidator { ...@@ -253,9 +254,9 @@ abstract class IntelliJValidator extends DoctorValidator {
}; };
static Iterable<DoctorValidator> get installedValidators { static Iterable<DoctorValidator> get installedValidators {
if (Platform.isLinux) if (io.Platform.isLinux)
return IntelliJValidatorOnLinux.installed; return IntelliJValidatorOnLinux.installed;
if (Platform.isMacOS) if (io.Platform.isMacOS)
return IntelliJValidatorOnMac.installed; return IntelliJValidatorOnMac.installed;
// TODO(danrubel): add support for Windows // TODO(danrubel): add support for Windows
return <DoctorValidator>[]; return <DoctorValidator>[];
...@@ -307,7 +308,7 @@ abstract class IntelliJValidator extends DoctorValidator { ...@@ -307,7 +308,7 @@ abstract class IntelliJValidator extends DoctorValidator {
// 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(new File(jarPath).readAsBytesSync()); Archive archive = new ZipDecoder().decodeBytes(fs.file(jarPath).readAsBytesSync());
ArchiveFile file = archive.findFile('META-INF/plugin.xml'); ArchiveFile file = archive.findFile('META-INF/plugin.xml');
String content = UTF8.decode(file.content); String content = UTF8.decode(file.content);
String versionStartTag = '<version>'; String versionStartTag = '<version>';
...@@ -322,8 +323,8 @@ abstract class IntelliJValidator extends DoctorValidator { ...@@ -322,8 +323,8 @@ abstract class IntelliJValidator extends DoctorValidator {
bool hasPackage(String packageName) { bool hasPackage(String packageName) {
String packagePath = path.join(pluginsPath, packageName); String packagePath = path.join(pluginsPath, packageName);
if (packageName.endsWith('.jar')) if (packageName.endsWith('.jar'))
return FileSystemEntity.isFileSync(packagePath); return fs.isFileSync(packagePath);
return FileSystemEntity.isDirectorySync(packagePath); return fs.isDirectorySync(packagePath);
} }
} }
...@@ -356,7 +357,7 @@ class IntelliJValidatorOnLinux extends IntelliJValidator { ...@@ -356,7 +357,7 @@ class IntelliJValidatorOnLinux extends IntelliJValidator {
validators.add(validator); validators.add(validator);
} }
for (FileSystemEntity dir in new Directory(homeDirPath).listSync()) { for (FileSystemEntity dir in fs.directory(homeDirPath).listSync()) {
if (dir is Directory) { if (dir is Directory) {
String name = path.basename(dir.path); String name = path.basename(dir.path);
IntelliJValidator._idToTitle.forEach((String id, String title) { IntelliJValidator._idToTitle.forEach((String id, String title) {
...@@ -364,11 +365,11 @@ class IntelliJValidatorOnLinux extends IntelliJValidator { ...@@ -364,11 +365,11 @@ class IntelliJValidatorOnLinux extends IntelliJValidator {
String version = name.substring(id.length + 1); String version = name.substring(id.length + 1);
String installPath; String installPath;
try { try {
installPath = new File(path.join(dir.path, 'system', '.home')).readAsStringSync(); installPath = fs.file(path.join(dir.path, 'system', '.home')).readAsStringSync();
} catch (e) { } catch (e) {
// ignored // ignored
} }
if (installPath != null && FileSystemEntity.isDirectorySync(installPath)) { if (installPath != null && fs.isDirectorySync(installPath)) {
String pluginsPath = path.join(dir.path, 'config', 'plugins'); String pluginsPath = path.join(dir.path, 'config', 'plugins');
addValidator(title, version, installPath, pluginsPath); addValidator(title, version, installPath, pluginsPath);
} }
...@@ -405,7 +406,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator { ...@@ -405,7 +406,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
} }
try { try {
for (FileSystemEntity dir in new Directory('/Applications').listSync()) { for (FileSystemEntity dir in fs.directory('/Applications').listSync()) {
if (dir is Directory) { if (dir is Directory) {
checkForIntelliJ(dir); checkForIntelliJ(dir);
if (!dir.path.endsWith('.app')) { if (!dir.path.endsWith('.app')) {
...@@ -432,7 +433,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator { ...@@ -432,7 +433,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
if (_version == null) { if (_version == null) {
String plist; String plist;
try { try {
plist = new File(path.join(installPath, 'Contents', 'Info.plist')).readAsStringSync(); plist = fs.file(path.join(installPath, 'Contents', 'Info.plist')).readAsStringSync();
int index = plist.indexOf('CFBundleShortVersionString'); int index = plist.indexOf('CFBundleShortVersionString');
if (index > 0) { if (index > 0) {
int start = plist.indexOf('<string>', index); int start = plist.indexOf('<string>', index);
......
...@@ -3,13 +3,12 @@ ...@@ -3,13 +3,12 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'asset.dart'; import 'asset.dart';
import 'base/common.dart'; import 'base/common.dart';
import 'base/file_system.dart' show ensureDirectoryExists; import 'base/file_system.dart';
import 'base/process.dart'; import 'base/process.dart';
import 'dart/package_map.dart'; import 'dart/package_map.dart';
import 'build_info.dart'; import 'build_info.dart';
...@@ -107,7 +106,7 @@ Future<Null> build({ ...@@ -107,7 +106,7 @@ Future<Null> build({
if (result != 0) if (result != 0)
throwToolExit('Failed to run the Flutter compiler. Exit code: $result', exitCode: result); throwToolExit('Failed to run the Flutter compiler. Exit code: $result', exitCode: result);
snapshotFile = new File(snapshotPath); snapshotFile = fs.file(snapshotPath);
} }
return assemble( return assemble(
...@@ -162,7 +161,7 @@ Future<Null> assemble({ ...@@ -162,7 +161,7 @@ Future<Null> assemble({
ensureDirectoryExists(outputPath); ensureDirectoryExists(outputPath);
printTrace('Encoding zip file to $outputPath'); printTrace('Encoding zip file to $outputPath');
zipBuilder.createZip(new File(outputPath), new Directory(workingDirPath)); zipBuilder.createZip(fs.file(outputPath), fs.directory(workingDirPath));
printTrace('Built $outputPath.'); printTrace('Built $outputPath.');
} }
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
...@@ -12,6 +11,7 @@ import 'package:stack_trace/stack_trace.dart'; ...@@ -12,6 +11,7 @@ import 'package:stack_trace/stack_trace.dart';
import 'application_package.dart'; import 'application_package.dart';
import 'asset.dart'; import 'asset.dart';
import 'base/context.dart'; import 'base/context.dart';
import 'base/file_system.dart';
import 'base/logger.dart'; import 'base/logger.dart';
import 'base/utils.dart'; import 'base/utils.dart';
import 'build_info.dart'; import 'build_info.dart';
...@@ -51,7 +51,7 @@ class HotRunner extends ResidentRunner { ...@@ -51,7 +51,7 @@ class HotRunner extends ResidentRunner {
target: target, target: target,
debuggingOptions: debuggingOptions, debuggingOptions: debuggingOptions,
usesTerminalUI: usesTerminalUI) { usesTerminalUI: usesTerminalUI) {
_projectRootPath = projectRootPath ?? Directory.current.path; _projectRootPath = projectRootPath ?? fs.currentDirectory.path;
_packagesFilePath = _packagesFilePath =
packagesFilePath ?? path.absolute(PackageMap.globalPackagesPath); packagesFilePath ?? path.absolute(PackageMap.globalPackagesPath);
if (projectAssets != null) if (projectAssets != null)
...@@ -136,7 +136,7 @@ class HotRunner extends ResidentRunner { ...@@ -136,7 +136,7 @@ class HotRunner extends ResidentRunner {
bool shouldBuild: true bool shouldBuild: true
}) async { }) async {
_mainPath = findMainDartFile(target); _mainPath = findMainDartFile(target);
if (!FileSystemEntity.isFileSync(_mainPath)) { if (!fs.isFileSync(_mainPath)) {
String message = 'Tried to run $_mainPath, but that file does not exist.'; String message = 'Tried to run $_mainPath, but that file does not exist.';
if (target == null) if (target == null)
message += '\nConsider using the -t option to specify the Dart file to start.'; message += '\nConsider using the -t option to specify the Dart file to start.';
...@@ -241,7 +241,7 @@ class HotRunner extends ResidentRunner { ...@@ -241,7 +241,7 @@ class HotRunner extends ResidentRunner {
await _cleanupDevFS(); await _cleanupDevFS();
await stopEchoingDeviceLog(); await stopEchoingDeviceLog();
await stopApp(); await stopApp();
File benchmarkOutput = new File('hot_benchmark.json'); File benchmarkOutput = fs.file('hot_benchmark.json');
benchmarkOutput.writeAsStringSync(toPrettyJson(benchmarkData)); benchmarkOutput.writeAsStringSync(toPrettyJson(benchmarkData));
} }
...@@ -267,7 +267,7 @@ class HotRunner extends ResidentRunner { ...@@ -267,7 +267,7 @@ class HotRunner extends ResidentRunner {
String fsName = path.basename(_projectRootPath); String fsName = path.basename(_projectRootPath);
_devFS = new DevFS(vmService, _devFS = new DevFS(vmService,
fsName, fsName,
new Directory(_projectRootPath), fs.directory(_projectRootPath),
packagesFilePath: _packagesFilePath); packagesFilePath: _packagesFilePath);
return _devFS.create(); return _devFS.create();
} }
......
...@@ -4,9 +4,10 @@ ...@@ -4,9 +4,10 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import '../application_package.dart'; import '../application_package.dart';
import '../base/file_system.dart';
import '../base/os.dart'; import '../base/os.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
...@@ -27,7 +28,7 @@ class IOSDevices extends PollingDeviceDiscovery { ...@@ -27,7 +28,7 @@ class IOSDevices extends PollingDeviceDiscovery {
IOSDevices() : super('IOSDevices'); IOSDevices() : super('IOSDevices');
@override @override
bool get supportsPlatform => Platform.isMacOS; bool get supportsPlatform => io.Platform.isMacOS;
@override @override
List<Device> pollingGetDevices() => IOSDevice.getAttachedDevices(); List<Device> pollingGetDevices() => IOSDevice.getAttachedDevices();
...@@ -124,7 +125,7 @@ class IOSDevice extends Device { ...@@ -124,7 +125,7 @@ class IOSDevice extends Device {
try { try {
command = runCheckedSync(<String>['which', command]).trim(); command = runCheckedSync(<String>['which', command]).trim();
} catch (e) { } catch (e) {
if (Platform.isMacOS) { if (io.Platform.isMacOS) {
printError('$command not found. $macInstructions'); printError('$command not found. $macInstructions');
} else { } else {
printError('Cannot control iOS devices or simulators. $command is not available on your platform.'); printError('Cannot control iOS devices or simulators. $command is not available on your platform.');
...@@ -150,7 +151,7 @@ class IOSDevice extends Device { ...@@ -150,7 +151,7 @@ class IOSDevice extends Device {
@override @override
bool installApp(ApplicationPackage app) { bool installApp(ApplicationPackage app) {
IOSApp iosApp = app; IOSApp iosApp = app;
Directory bundle = new Directory(iosApp.deviceBundlePath); 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;
...@@ -207,7 +208,7 @@ class IOSDevice extends Device { ...@@ -207,7 +208,7 @@ 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; IOSApp iosApp = app;
Directory bundle = new Directory(iosApp.deviceBundlePath); 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();
...@@ -312,7 +313,7 @@ class IOSDevice extends Device { ...@@ -312,7 +313,7 @@ class IOSDevice extends Device {
} }
Future<bool> pushFile(ApplicationPackage app, String localFile, String targetFile) async { Future<bool> pushFile(ApplicationPackage app, String localFile, String targetFile) async {
if (Platform.isMacOS) { if (io.Platform.isMacOS) {
runSync(<String>[ runSync(<String>[
pusherPath, pusherPath,
'-t', '-t',
...@@ -391,7 +392,7 @@ class _IOSDeviceLogReader extends DeviceLogReader { ...@@ -391,7 +392,7 @@ class _IOSDeviceLogReader extends DeviceLogReader {
final IOSDevice device; final IOSDevice device;
StreamController<String> _linesController; StreamController<String> _linesController;
Process _process; io.Process _process;
@override @override
Stream<String> get logLines => _linesController.stream; Stream<String> get logLines => _linesController.stream;
...@@ -400,7 +401,7 @@ class _IOSDeviceLogReader extends DeviceLogReader { ...@@ -400,7 +401,7 @@ class _IOSDeviceLogReader extends DeviceLogReader {
String get name => device.name; String get name => device.name;
void _start() { void _start() {
runCommand(<String>[device.loggerPath]).then((Process process) { runCommand(<String>[device.loggerPath]).then((io.Process process) {
_process = process; _process = process;
_process.stdout.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine); _process.stdout.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine);
_process.stderr.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine); _process.stderr.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine);
...@@ -444,7 +445,7 @@ class _IOSDevicePortForwarder extends DevicePortForwarder { ...@@ -444,7 +445,7 @@ 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>[ io.Process process = await runCommand(<String>[
device.iproxyPath, device.iproxyPath,
hostPort.toString(), hostPort.toString(),
devicePort.toString(), devicePort.toString(),
...@@ -470,7 +471,7 @@ class _IOSDevicePortForwarder extends DevicePortForwarder { ...@@ -470,7 +471,7 @@ class _IOSDevicePortForwarder extends DevicePortForwarder {
printTrace("Unforwarding port $forwardedPort"); printTrace("Unforwarding port $forwardedPort");
Process process = forwardedPort.context; io.Process process = forwardedPort.context;
if (process != null) { if (process != null) {
processManager.killPid(process.pid); processManager.killPid(process.pid);
......
...@@ -4,12 +4,13 @@ ...@@ -4,12 +4,13 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert' show JSON; import 'dart:convert' show JSON;
import 'dart:io'; import 'dart:io' as io;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../application_package.dart'; import '../application_package.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
import '../build_info.dart'; import '../build_info.dart';
...@@ -40,7 +41,7 @@ class XCode { ...@@ -40,7 +41,7 @@ class XCode {
} else { } else {
try { try {
printTrace('xcrun clang'); printTrace('xcrun clang');
ProcessResult result = processManager.runSync('/usr/bin/xcrun', <String>['clang']); io.ProcessResult result = processManager.runSync('/usr/bin/xcrun', <String>['clang']);
if (result.stdout != null && result.stdout.contains('license')) if (result.stdout != null && result.stdout.contains('license'))
_eulaSigned = false; _eulaSigned = false;
...@@ -107,7 +108,7 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -107,7 +108,7 @@ Future<XcodeBuildResult> buildXcodeProject({
bool buildForDevice, bool buildForDevice,
bool codesign: true bool codesign: true
}) async { }) async {
String flutterProjectPath = Directory.current.path; String flutterProjectPath = fs.currentDirectory.path;
updateXcodeGeneratedProperties(flutterProjectPath, mode, target); updateXcodeGeneratedProperties(flutterProjectPath, mode, target);
if (!_checkXcodeVersion()) if (!_checkXcodeVersion())
...@@ -116,7 +117,7 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -116,7 +117,7 @@ Future<XcodeBuildResult> buildXcodeProject({
// Before the build, all service definitions must be updated and the dylibs // Before the build, all service definitions must be updated and the dylibs
// copied over to a location that is suitable for Xcodebuild to find them. // copied over to a location that is suitable for Xcodebuild to find them.
await _addServicesToBundle(new Directory(app.appDirectory)); await _addServicesToBundle(fs.directory(app.appDirectory));
List<String> commands = <String>[ List<String> commands = <String>[
'/usr/bin/env', '/usr/bin/env',
...@@ -128,7 +129,7 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -128,7 +129,7 @@ Future<XcodeBuildResult> buildXcodeProject({
'ONLY_ACTIVE_ARCH=YES', 'ONLY_ACTIVE_ARCH=YES',
]; ];
List<FileSystemEntity> contents = new Directory(app.appDirectory).listSync(); List<FileSystemEntity> contents = fs.directory(app.appDirectory).listSync();
for (FileSystemEntity entity in contents) { for (FileSystemEntity entity in contents) {
if (path.extension(entity.path) == '.xcworkspace') { if (path.extension(entity.path) == '.xcworkspace') {
commands.addAll(<String>[ commands.addAll(<String>[
...@@ -180,7 +181,7 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -180,7 +181,7 @@ Future<XcodeBuildResult> buildXcodeProject({
} }
void diagnoseXcodeBuildFailure(XcodeBuildResult result) { void diagnoseXcodeBuildFailure(XcodeBuildResult result) {
File plistFile = new File('ios/Runner/Info.plist'); File plistFile = fs.file('ios/Runner/Info.plist');
if (plistFile.existsSync()) { if (plistFile.existsSync()) {
String plistContent = plistFile.readAsStringSync(); String plistContent = plistFile.readAsStringSync();
if (plistContent.contains('com.yourcompany')) { if (plistContent.contains('com.yourcompany')) {
...@@ -219,7 +220,7 @@ final RegExp _xcodeVersionRegExp = new RegExp(r'Xcode (\d+)\..*'); ...@@ -219,7 +220,7 @@ final RegExp _xcodeVersionRegExp = new RegExp(r'Xcode (\d+)\..*');
final String _xcodeRequirement = 'Xcode 7.0 or greater is required to develop for iOS.'; final String _xcodeRequirement = 'Xcode 7.0 or greater is required to develop for iOS.';
bool _checkXcodeVersion() { bool _checkXcodeVersion() {
if (!Platform.isMacOS) if (!io.Platform.isMacOS)
return false; return false;
try { try {
String version = runCheckedSync(<String>['xcodebuild', '-version']); String version = runCheckedSync(<String>['xcodebuild', '-version']);
...@@ -245,12 +246,12 @@ Future<Null> _addServicesToBundle(Directory bundle) async { ...@@ -245,12 +246,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 = new Directory(path.join(bundle.path, "Frameworks")); Directory frameworksDirectory = fs.directory(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 = new File(path.join(bundle.path, "ServiceDefinitions.json")); File manifestFile = fs.file(path.join(bundle.path, "ServiceDefinitions.json"));
_copyServiceDefinitionsManifest(services, manifestFile); _copyServiceDefinitionsManifest(services, manifestFile);
} }
...@@ -259,7 +260,7 @@ Future<Null> _copyServiceFrameworks(List<Map<String, String>> services, Director ...@@ -259,7 +260,7 @@ Future<Null> _copyServiceFrameworks(List<Map<String, String>> services, Director
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']); String dylibPath = await getServiceFromUrl(service['ios-framework'], service['root'], service['name']);
File dylib = new File(dylibPath); 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.");
......
...@@ -2,10 +2,9 @@ ...@@ -2,10 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/file_system.dart';
import '../base/process.dart'; import '../base/process.dart';
const String kCFBundleIdentifierKey = "CFBundleIdentifier"; const String kCFBundleIdentifierKey = "CFBundleIdentifier";
...@@ -18,7 +17,7 @@ String getValueFromFile(String plistFilePath, String key) { ...@@ -18,7 +17,7 @@ String getValueFromFile(String plistFilePath, String key) {
// 'defaults' requires the path to be absolute and without the 'plist' // 'defaults' requires the path to be absolute and without the 'plist'
// extension. // extension.
if (!FileSystemEntity.isFileSync(plistFilePath)) if (!fs.isFileSync(plistFilePath))
return null; return null;
String normalizedPlistPath = path.withoutExtension(path.absolute(plistFilePath)); String normalizedPlistPath = path.withoutExtension(path.absolute(plistFilePath));
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'dart:math' as math; import 'dart:math' as math;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
...@@ -12,6 +12,7 @@ import 'package:path/path.dart' as path; ...@@ -12,6 +12,7 @@ import 'package:path/path.dart' as path;
import '../application_package.dart'; import '../application_package.dart';
import '../base/common.dart'; import '../base/common.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
import '../build_info.dart'; import '../build_info.dart';
...@@ -30,7 +31,7 @@ class IOSSimulators extends PollingDeviceDiscovery { ...@@ -30,7 +31,7 @@ class IOSSimulators extends PollingDeviceDiscovery {
IOSSimulators() : super('IOSSimulators'); IOSSimulators() : super('IOSSimulators');
@override @override
bool get supportsPlatform => Platform.isMacOS; bool get supportsPlatform => io.Platform.isMacOS;
@override @override
List<Device> pollingGetDevices() => IOSSimulatorUtils.instance.getAttachedDevices(); List<Device> pollingGetDevices() => IOSSimulatorUtils.instance.getAttachedDevices();
...@@ -191,7 +192,7 @@ class SimControl { ...@@ -191,7 +192,7 @@ class SimControl {
List<String> args = <String>['simctl', 'list', '--json', section.name]; List<String> args = <String>['simctl', 'list', '--json', section.name];
printTrace('$_xcrunPath ${args.join(' ')}'); printTrace('$_xcrunPath ${args.join(' ')}');
ProcessResult results = processManager.runSync(_xcrunPath, args); io.ProcessResult results = processManager.runSync(_xcrunPath, args);
if (results.exitCode != 0) { if (results.exitCode != 0) {
printError('Error executing simctl: ${results.exitCode}\n${results.stderr}'); printError('Error executing simctl: ${results.exitCode}\n${results.stderr}');
return <String, Map<String, dynamic>>{}; return <String, Map<String, dynamic>>{};
...@@ -358,7 +359,7 @@ class IOSSimulator extends Device { ...@@ -358,7 +359,7 @@ class IOSSimulator extends Device {
@override @override
bool isSupported() { bool isSupported() {
if (!Platform.isMacOS) { if (!io.Platform.isMacOS) {
_supportMessage = "Not supported on a non Mac host"; _supportMessage = "Not supported on a non Mac host";
return false; return false;
} }
...@@ -510,7 +511,7 @@ class IOSSimulator extends Device { ...@@ -510,7 +511,7 @@ class IOSSimulator extends Device {
// Step 2: Assert that the Xcode project was successfully built. // Step 2: Assert that the Xcode project was successfully built.
IOSApp iosApp = app; IOSApp iosApp = app;
Directory bundle = new Directory(iosApp.simulatorBundlePath); Directory bundle = fs.directory(iosApp.simulatorBundlePath);
bool bundleExists = bundle.existsSync(); bool bundleExists = bundle.existsSync();
if (!bundleExists) if (!bundleExists)
throwToolExit('Could not find the built application bundle at ${bundle.path}.'); throwToolExit('Could not find the built application bundle at ${bundle.path}.');
...@@ -530,7 +531,7 @@ class IOSSimulator extends Device { ...@@ -530,7 +531,7 @@ class IOSSimulator extends Device {
Future<bool> pushFile( Future<bool> pushFile(
ApplicationPackage app, String localFile, String targetFile) async { ApplicationPackage app, String localFile, String targetFile) async {
if (Platform.isMacOS) { if (io.Platform.isMacOS) {
String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app); String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app);
runCheckedSync(<String>['cp', localFile, path.join(simulatorHomeDirectory, targetFile)]); runCheckedSync(<String>['cp', localFile, path.join(simulatorHomeDirectory, targetFile)]);
return true; return true;
...@@ -564,7 +565,7 @@ class IOSSimulator extends Device { ...@@ -564,7 +565,7 @@ class IOSSimulator extends Device {
@override @override
void clearLogs() { void clearLogs() {
File logFile = new File(logFilePath); File logFile = fs.file(logFilePath);
if (logFile.existsSync()) { if (logFile.existsSync()) {
RandomAccessFile randomFile = logFile.openSync(mode: FileMode.WRITE); RandomAccessFile randomFile = logFile.openSync(mode: FileMode.WRITE);
randomFile.truncateSync(0); randomFile.truncateSync(0);
...@@ -573,7 +574,7 @@ class IOSSimulator extends Device { ...@@ -573,7 +574,7 @@ class IOSSimulator extends Device {
} }
void ensureLogsExists() { void ensureLogsExists() {
File logFile = new File(logFilePath); File logFile = fs.file(logFilePath);
if (!logFile.existsSync()) if (!logFile.existsSync())
logFile.writeAsBytesSync(<int>[]); logFile.writeAsBytesSync(<int>[]);
} }
...@@ -583,7 +584,7 @@ class IOSSimulator extends Device { ...@@ -583,7 +584,7 @@ class IOSSimulator extends Device {
@override @override
Future<bool> takeScreenshot(File outputFile) async { Future<bool> takeScreenshot(File outputFile) async {
Directory desktopDir = new Directory(path.join(homeDirPath, 'Desktop')); Directory desktopDir = fs.directory(path.join(homeDirPath, 'Desktop'));
// 'Simulator Screen Shot Mar 25, 2016, 2.59.43 PM.png' // 'Simulator Screen Shot Mar 25, 2016, 2.59.43 PM.png'
...@@ -639,8 +640,8 @@ class _IOSSimulatorLogReader extends DeviceLogReader { ...@@ -639,8 +640,8 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
StreamController<String> _linesController; StreamController<String> _linesController;
// We log from two files: the device and the system log. // We log from two files: the device and the system log.
Process _deviceProcess; io.Process _deviceProcess;
Process _systemProcess; io.Process _systemProcess;
@override @override
Stream<String> get logLines => _linesController.stream; Stream<String> get logLines => _linesController.stream;
......
...@@ -2,10 +2,9 @@ ...@@ -2,10 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import '../base/file_system.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../cache.dart'; import '../cache.dart';
...@@ -23,7 +22,7 @@ void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String t ...@@ -23,7 +22,7 @@ void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String t
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
String applicationRoot = path.normalize(Directory.current.path); String applicationRoot = path.normalize(fs.currentDirectory.path);
localsBuffer.writeln('FLUTTER_APPLICATION_PATH=$applicationRoot'); localsBuffer.writeln('FLUTTER_APPLICATION_PATH=$applicationRoot');
// Relative to FLUTTER_APPLICATION_PATH, which is [Directory.current]. // Relative to FLUTTER_APPLICATION_PATH, which is [Directory.current].
...@@ -43,7 +42,7 @@ void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String t ...@@ -43,7 +42,7 @@ void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String t
if (tools.isLocalEngine) if (tools.isLocalEngine)
localsBuffer.writeln('LOCAL_ENGINE=${tools.engineBuildPath}'); localsBuffer.writeln('LOCAL_ENGINE=${tools.engineBuildPath}');
File localsFile = new File(path.join(projectPath, 'ios', 'Flutter', 'Generated.xcconfig')); File localsFile = fs.file(path.join(projectPath, 'ios', 'Flutter', 'Generated.xcconfig'));
localsFile.createSync(recursive: true); localsFile.createSync(recursive: true);
localsFile.writeAsStringSync(localsBuffer.toString()); localsFile.writeAsStringSync(localsBuffer.toString());
} }
......
...@@ -3,12 +3,13 @@ ...@@ -3,12 +3,13 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'application_package.dart'; import 'application_package.dart';
import 'base/file_system.dart';
import 'base/logger.dart'; import 'base/logger.dart';
import 'build_info.dart'; import 'build_info.dart';
import 'device.dart'; import 'device.dart';
...@@ -77,12 +78,12 @@ abstract class ResidentRunner { ...@@ -77,12 +78,12 @@ abstract class ResidentRunner {
} }
void registerSignalHandlers() { void registerSignalHandlers() {
ProcessSignal.SIGINT.watch().listen((ProcessSignal signal) async { io.ProcessSignal.SIGINT.watch().listen((io.ProcessSignal signal) async {
_resetTerminal(); _resetTerminal();
await cleanupAfterSignal(); await cleanupAfterSignal();
exit(0); exit(0);
}); });
ProcessSignal.SIGTERM.watch().listen((ProcessSignal signal) async { io.ProcessSignal.SIGTERM.watch().listen((io.ProcessSignal signal) async {
_resetTerminal(); _resetTerminal();
await cleanupAfterSignal(); await cleanupAfterSignal();
exit(0); exit(0);
...@@ -91,19 +92,19 @@ abstract class ResidentRunner { ...@@ -91,19 +92,19 @@ abstract class ResidentRunner {
return; return;
if (!supportsRestart) if (!supportsRestart)
return; return;
ProcessSignal.SIGUSR1.watch().listen(_handleSignal); io.ProcessSignal.SIGUSR1.watch().listen(_handleSignal);
ProcessSignal.SIGUSR2.watch().listen(_handleSignal); io.ProcessSignal.SIGUSR2.watch().listen(_handleSignal);
} }
bool _processingSignal = false; bool _processingSignal = false;
Future<Null> _handleSignal(ProcessSignal signal) async { Future<Null> _handleSignal(io.ProcessSignal signal) async {
if (_processingSignal) { if (_processingSignal) {
printTrace('Ignoring signal: "$signal" because we are busy.'); printTrace('Ignoring signal: "$signal" because we are busy.');
return; return;
} }
_processingSignal = true; _processingSignal = true;
final bool fullRestart = signal == ProcessSignal.SIGUSR2; final bool fullRestart = signal == io.ProcessSignal.SIGUSR2;
try { try {
await restart(fullRestart: fullRestart); await restart(fullRestart: fullRestart);
...@@ -279,7 +280,7 @@ String findMainDartFile([String target]) { ...@@ -279,7 +280,7 @@ String findMainDartFile([String target]) {
if (target == null) if (target == null)
target = ''; target = '';
String targetPath = path.absolute(target); String targetPath = path.absolute(target);
if (FileSystemEntity.isDirectorySync(targetPath)) if (fs.isDirectorySync(targetPath))
return path.join(targetPath, 'lib', 'main.dart'); return path.join(targetPath, 'lib', 'main.dart');
else else
return targetPath; return targetPath;
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:stack_trace/stack_trace.dart'; import 'package:stack_trace/stack_trace.dart';
import 'application_package.dart'; import 'application_package.dart';
import 'base/file_system.dart';
import 'base/utils.dart'; import 'base/utils.dart';
import 'build_info.dart'; import 'build_info.dart';
import 'commands/trace.dart'; import 'commands/trace.dart';
...@@ -68,7 +68,7 @@ class RunAndStayResident extends ResidentRunner { ...@@ -68,7 +68,7 @@ class RunAndStayResident extends ResidentRunner {
}) async { }) async {
if (!prebuiltMode) { if (!prebuiltMode) {
_mainPath = findMainDartFile(target); _mainPath = findMainDartFile(target);
if (!FileSystemEntity.isFileSync(_mainPath)) { if (!fs.isFileSync(_mainPath)) {
String message = 'Tried to run $_mainPath, but that file does not exist.'; String message = 'Tried to run $_mainPath, but that file does not exist.';
if (target == null) if (target == null)
message += '\nConsider using the -t option to specify the Dart file to start.'; message += '\nConsider using the -t option to specify the Dart file to start.';
......
...@@ -3,13 +3,13 @@ ...@@ -3,13 +3,13 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:args/command_runner.dart'; import 'package:args/command_runner.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import '../application_package.dart'; import '../application_package.dart';
import '../base/common.dart'; import '../base/common.dart';
import '../base/file_system.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../dart/package_map.dart'; import '../dart/package_map.dart';
import '../dart/pub.dart'; import '../dart/pub.dart';
...@@ -207,7 +207,7 @@ abstract class FlutterCommand extends Command<Null> { ...@@ -207,7 +207,7 @@ abstract class FlutterCommand extends Command<Null> {
void commonCommandValidator() { void commonCommandValidator() {
if (!PackageMap.isUsingCustomPackagesPath) { if (!PackageMap.isUsingCustomPackagesPath) {
// Don't expect a pubspec.yaml file if the user passed in an explicit .packages file path. // Don't expect a pubspec.yaml file if the user passed in an explicit .packages file path.
if (!FileSystemEntity.isFileSync('pubspec.yaml')) { if (!fs.isFileSync('pubspec.yaml')) {
throw new ToolExit('Error: No pubspec.yaml file found.\n' throw new ToolExit('Error: No pubspec.yaml file found.\n'
'This command should be run from the root of your Flutter project.\n' 'This command should be run from the root of your Flutter project.\n'
'Do not run this command from the root of your git clone of Flutter.'); 'Do not run this command from the root of your git clone of Flutter.');
...@@ -216,7 +216,7 @@ abstract class FlutterCommand extends Command<Null> { ...@@ -216,7 +216,7 @@ abstract class FlutterCommand extends Command<Null> {
if (_usesTargetOption) { if (_usesTargetOption) {
String targetPath = targetFile; String targetPath = targetFile;
if (!FileSystemEntity.isFileSync(targetPath)) if (!fs.isFileSync(targetPath))
throw new ToolExit('Target file "$targetPath" not found.'); throw new ToolExit('Target file "$targetPath" not found.');
} }
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:args/args.dart'; import 'package:args/args.dart';
import 'package:args/command_runner.dart'; import 'package:args/command_runner.dart';
...@@ -12,6 +12,7 @@ import 'package:path/path.dart' as path; ...@@ -12,6 +12,7 @@ import 'package:path/path.dart' as path;
import '../android/android_sdk.dart'; import '../android/android_sdk.dart';
import '../base/common.dart'; import '../base/common.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
...@@ -67,7 +68,7 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -67,7 +68,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
help: 'Suppress analytics reporting when this command runs.'); help: 'Suppress analytics reporting when this command runs.');
String packagesHelp; String packagesHelp;
if (FileSystemEntity.isFileSync(kPackagesFileName)) if (fs.isFileSync(kPackagesFileName))
packagesHelp = '\n(defaults to "$kPackagesFileName")'; packagesHelp = '\n(defaults to "$kPackagesFileName")';
else else
packagesHelp = '\n(required, since the current directory does not contain a "$kPackagesFileName" file)'; packagesHelp = '\n(required, since the current directory does not contain a "$kPackagesFileName" file)';
...@@ -117,12 +118,12 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -117,12 +118,12 @@ class FlutterCommandRunner extends CommandRunner<Null> {
} }
static String get _defaultFlutterRoot { static String get _defaultFlutterRoot {
if (Platform.environment.containsKey(kFlutterRootEnvironmentVariableName)) if (io.Platform.environment.containsKey(kFlutterRootEnvironmentVariableName))
return Platform.environment[kFlutterRootEnvironmentVariableName]; return io.Platform.environment[kFlutterRootEnvironmentVariableName];
try { try {
if (Platform.script.scheme == 'data') if (io.Platform.script.scheme == 'data')
return '../..'; // we're running as a test return '../..'; // we're running as a test
String script = Platform.script.toFilePath(); String script = io.Platform.script.toFilePath();
if (path.basename(script) == kSnapshotFileName) if (path.basename(script) == kSnapshotFileName)
return path.dirname(path.dirname(path.dirname(script))); return path.dirname(path.dirname(path.dirname(script)));
if (path.basename(script) == kFlutterToolsScriptFileName) if (path.basename(script) == kFlutterToolsScriptFileName)
...@@ -191,7 +192,7 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -191,7 +192,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
// enginePath's initialiser uses it). // enginePath's initialiser uses it).
Cache.flutterRoot = path.normalize(path.absolute(globalResults['flutter-root'])); Cache.flutterRoot = path.normalize(path.absolute(globalResults['flutter-root']));
if (Platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') if (io.Platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true')
await Cache.lock(); await Cache.lock();
if (globalResults['suppress-analytics']) if (globalResults['suppress-analytics'])
...@@ -225,20 +226,20 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -225,20 +226,20 @@ class FlutterCommandRunner extends CommandRunner<Null> {
} }
String _tryEnginePath(String enginePath) { String _tryEnginePath(String enginePath) {
if (FileSystemEntity.isDirectorySync(path.join(enginePath, 'out'))) if (fs.isDirectorySync(path.join(enginePath, 'out')))
return enginePath; return enginePath;
return null; return null;
} }
String _findEnginePath(ArgResults globalResults) { String _findEnginePath(ArgResults globalResults) {
String engineSourcePath = globalResults['local-engine-src-path'] ?? Platform.environment[kFlutterEngineEnvironmentVariableName]; String engineSourcePath = globalResults['local-engine-src-path'] ?? io.Platform.environment[kFlutterEngineEnvironmentVariableName];
if (engineSourcePath == null && globalResults['local-engine'] != null) { if (engineSourcePath == null && globalResults['local-engine'] != null) {
try { try {
Uri engineUri = new PackageMap(PackageMap.globalPackagesPath).map[kFlutterEnginePackageName]; Uri engineUri = new PackageMap(PackageMap.globalPackagesPath).map[kFlutterEnginePackageName];
if (engineUri != null) { if (engineUri != null) {
engineSourcePath = path.dirname(path.dirname(path.dirname(path.dirname(engineUri.path)))); engineSourcePath = path.dirname(path.dirname(path.dirname(path.dirname(engineUri.path))));
bool dirExists = FileSystemEntity.isDirectorySync(path.join(engineSourcePath, 'out')); bool dirExists = fs.isDirectorySync(path.join(engineSourcePath, 'out'));
if (engineSourcePath == '/' || engineSourcePath.isEmpty || !dirExists) if (engineSourcePath == '/' || engineSourcePath.isEmpty || !dirExists)
engineSourcePath = null; engineSourcePath = null;
} }
...@@ -276,7 +277,7 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -276,7 +277,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
} }
String engineBuildPath = path.normalize(path.join(enginePath, 'out', localEngine)); String engineBuildPath = path.normalize(path.join(enginePath, 'out', localEngine));
if (!FileSystemEntity.isDirectorySync(engineBuildPath)) { if (!fs.isDirectorySync(engineBuildPath)) {
printError('No Flutter engine build found at $engineBuildPath.'); printError('No Flutter engine build found at $engineBuildPath.');
throw new ProcessExit(2); throw new ProcessExit(2);
} }
...@@ -292,18 +293,18 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -292,18 +293,18 @@ class FlutterCommandRunner extends CommandRunner<Null> {
/// Get all pub packages in the Flutter repo. /// Get all pub packages in the Flutter repo.
List<Directory> getRepoPackages() { List<Directory> getRepoPackages() {
return _gatherProjectPaths(path.absolute(Cache.flutterRoot)) return _gatherProjectPaths(path.absolute(Cache.flutterRoot))
.map((String dir) => new Directory(dir)) .map((String dir) => fs.directory(dir))
.toList(); .toList();
} }
static List<String> _gatherProjectPaths(String rootPath) { static List<String> _gatherProjectPaths(String rootPath) {
if (FileSystemEntity.isFileSync(path.join(rootPath, '.dartignore'))) if (fs.isFileSync(path.join(rootPath, '.dartignore')))
return <String>[]; return <String>[];
if (FileSystemEntity.isFileSync(path.join(rootPath, 'pubspec.yaml'))) if (fs.isFileSync(path.join(rootPath, 'pubspec.yaml')))
return <String>[rootPath]; return <String>[rootPath];
return new Directory(rootPath) return fs.directory(rootPath)
.listSync(followLinks: false) .listSync(followLinks: false)
.expand((FileSystemEntity entity) { .expand((FileSystemEntity entity) {
return entity is Directory ? _gatherProjectPaths(entity.path) : <String>[]; return entity is Directory ? _gatherProjectPaths(entity.path) : <String>[];
...@@ -316,13 +317,13 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -316,13 +317,13 @@ class FlutterCommandRunner extends CommandRunner<Null> {
final String rootPath = path.absolute(Cache.flutterRoot); final String rootPath = path.absolute(Cache.flutterRoot);
final List<Directory> result = <Directory>[ final List<Directory> result = <Directory>[
// not bin, and not the root // not bin, and not the root
new Directory(path.join(rootPath, 'dev')), fs.directory(path.join(rootPath, 'dev')),
new Directory(path.join(rootPath, 'examples')), fs.directory(path.join(rootPath, 'examples')),
]; ];
// And since analyzer refuses to look at paths that end in "packages/": // And since analyzer refuses to look at paths that end in "packages/":
result.addAll( result.addAll(
_gatherProjectPaths(path.join(rootPath, 'packages')) _gatherProjectPaths(path.join(rootPath, 'packages'))
.map/*<Directory>*/((String path) => new Directory(path)) .map/*<Directory>*/((String path) => fs.directory(path))
); );
return result; return result;
} }
...@@ -330,7 +331,7 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -330,7 +331,7 @@ class FlutterCommandRunner extends CommandRunner<Null> {
void _checkFlutterCopy() { void _checkFlutterCopy() {
// If the current directory is contained by a flutter repo, check that it's // If the current directory is contained by a flutter repo, check that it's
// the same flutter that is currently running. // the same flutter that is currently running.
String directory = path.normalize(path.absolute(Directory.current.path)); String directory = path.normalize(path.absolute(fs.currentDirectory.path));
// Check if the cwd is a flutter dir. // Check if the cwd is a flutter dir.
while (directory.isNotEmpty) { while (directory.isNotEmpty) {
...@@ -355,14 +356,14 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -355,14 +356,14 @@ class FlutterCommandRunner extends CommandRunner<Null> {
} }
// Check that the flutter running is that same as the one referenced in the pubspec. // Check that the flutter running is that same as the one referenced in the pubspec.
if (FileSystemEntity.isFileSync(kPackagesFileName)) { if (fs.isFileSync(kPackagesFileName)) {
PackageMap packageMap = new PackageMap(kPackagesFileName); PackageMap packageMap = new PackageMap(kPackagesFileName);
Uri flutterUri = packageMap.map['flutter']; Uri flutterUri = packageMap.map['flutter'];
if (flutterUri != null && (flutterUri.scheme == 'file' || flutterUri.scheme == '')) { if (flutterUri != null && (flutterUri.scheme == 'file' || flutterUri.scheme == '')) {
// .../flutter/packages/flutter/lib // .../flutter/packages/flutter/lib
Uri rootUri = flutterUri.resolve('../../..'); Uri rootUri = flutterUri.resolve('../../..');
String flutterPath = path.normalize(new File.fromUri(rootUri).absolute.path); String flutterPath = path.normalize(fs.file(rootUri).absolute.path);
if (!_compareResolvedPaths(flutterPath, Cache.flutterRoot)) { if (!_compareResolvedPaths(flutterPath, Cache.flutterRoot)) {
printError( printError(
...@@ -381,14 +382,14 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -381,14 +382,14 @@ class FlutterCommandRunner extends CommandRunner<Null> {
// Check if `bin/flutter` and `bin/cache/engine.stamp` exist. // Check if `bin/flutter` and `bin/cache/engine.stamp` exist.
bool _isDirectoryFlutterRepo(String directory) { bool _isDirectoryFlutterRepo(String directory) {
return return
FileSystemEntity.isFileSync(path.join(directory, 'bin/flutter')) && fs.isFileSync(path.join(directory, 'bin/flutter')) &&
FileSystemEntity.isFileSync(path.join(directory, 'bin/cache/engine.stamp')); fs.isFileSync(path.join(directory, 'bin/cache/engine.stamp'));
} }
} }
bool _compareResolvedPaths(String path1, String path2) { bool _compareResolvedPaths(String path1, String path2) {
path1 = new Directory(path.absolute(path1)).resolveSymbolicLinksSync(); path1 = fs.directory(path.absolute(path1)).resolveSymbolicLinksSync();
path2 = new Directory(path.absolute(path2)).resolveSymbolicLinksSync(); path2 = fs.directory(path.absolute(path2)).resolveSymbolicLinksSync();
return path1 == path2; return path1 == path2;
} }
...@@ -4,11 +4,11 @@ ...@@ -4,11 +4,11 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart'; import 'package:yaml/yaml.dart';
import 'base/file_system.dart';
import 'dart/package_map.dart'; import 'dart/package_map.dart';
import 'android/android_sdk.dart'; import 'android/android_sdk.dart';
import 'globals.dart'; import 'globals.dart';
...@@ -18,9 +18,9 @@ const String _kFlutterServicesManifestPath = 'flutter_services.yaml'; ...@@ -18,9 +18,9 @@ const String _kFlutterServicesManifestPath = 'flutter_services.yaml';
dynamic _loadYamlFile(String path) { dynamic _loadYamlFile(String path) {
printTrace("Looking for YAML at '$path'"); printTrace("Looking for YAML at '$path'");
if (!FileSystemEntity.isFileSync(path)) if (!fs.isFileSync(path))
return null; return null;
String manifestString = new File(path).readAsStringSync(); String manifestString = fs.file(path).readAsStringSync();
return loadYaml(manifestString); return loadYaml(manifestString);
} }
...@@ -69,7 +69,7 @@ Future<Null> parseServiceConfigs( ...@@ -69,7 +69,7 @@ Future<Null> parseServiceConfigs(
if (jars != null && serviceConfig['jars'] is Iterable) { if (jars != null && serviceConfig['jars'] is Iterable) {
for (String jar in serviceConfig['jars']) for (String jar in serviceConfig['jars'])
jars.add(new File(await getServiceFromUrl(jar, serviceRoot, service, unzip: false))); jars.add(fs.file(await getServiceFromUrl(jar, serviceRoot, service, unzip: false)));
} }
} }
} }
...@@ -106,7 +106,7 @@ File generateServiceDefinitions( ...@@ -106,7 +106,7 @@ File generateServiceDefinitions(
}).toList(); }).toList();
Map<String, dynamic> json = <String, dynamic>{ 'services': services }; Map<String, dynamic> json = <String, dynamic>{ 'services': services };
File servicesFile = new File(path.join(dir, 'services.json')); File servicesFile = fs.file(path.join(dir, 'services.json'));
servicesFile.writeAsStringSync(JSON.encode(json), mode: FileMode.WRITE, flush: true); servicesFile.writeAsStringSync(JSON.encode(json), mode: FileMode.WRITE, flush: true);
return servicesFile; return servicesFile;
} }
...@@ -2,11 +2,10 @@ ...@@ -2,11 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:mustache/mustache.dart' as mustache; import 'package:mustache/mustache.dart' as mustache;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'base/file_system.dart';
import 'cache.dart'; import 'cache.dart';
import 'globals.dart'; import 'globals.dart';
...@@ -78,7 +77,7 @@ class Template { ...@@ -78,7 +77,7 @@ class Template {
.replaceAll(_kTemplateExtension, ''); .replaceAll(_kTemplateExtension, '');
if (projectName != null) if (projectName != null)
finalDestinationPath = finalDestinationPath.replaceAll('projectName', projectName); finalDestinationPath = finalDestinationPath.replaceAll('projectName', projectName);
File finalDestinationFile = new File(finalDestinationPath); File finalDestinationFile = fs.file(finalDestinationPath);
String relativePathForLogging = path.relative(finalDestinationFile.path); String relativePathForLogging = path.relative(finalDestinationFile.path);
// Step 1: Check if the file needs to be overwritten. // Step 1: Check if the file needs to be overwritten.
...@@ -99,7 +98,7 @@ class Template { ...@@ -99,7 +98,7 @@ class Template {
fileCount++; fileCount++;
finalDestinationFile.createSync(recursive: true); finalDestinationFile.createSync(recursive: true);
File sourceFile = new File(absoluteSrcPath); File sourceFile = fs.file(absoluteSrcPath);
// Step 2: If the absolute paths ends with a 'copy.tmpl', this file does // Step 2: If the absolute paths ends with a 'copy.tmpl', this file does
// not need mustache rendering but needs to be directly copied. // not need mustache rendering but needs to be directly copied.
...@@ -135,5 +134,5 @@ class Template { ...@@ -135,5 +134,5 @@ class Template {
Directory _templateDirectoryInPackage(String name) { Directory _templateDirectoryInPackage(String name) {
String templatesDir = path.join(Cache.flutterRoot, String templatesDir = path.join(Cache.flutterRoot,
'packages', 'flutter_tools', 'templates'); 'packages', 'flutter_tools', 'templates');
return new Directory(path.join(templatesDir, name)); return fs.directory(path.join(templatesDir, name));
} }
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'dart:math' as math; import 'dart:math' as math;
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
...@@ -14,13 +14,14 @@ import 'package:test/src/backend/test_platform.dart'; // ignore: implementation_ ...@@ -14,13 +14,14 @@ import 'package:test/src/backend/test_platform.dart'; // ignore: implementation_
import 'package:test/src/runner/plugin/platform.dart'; // ignore: implementation_imports import 'package:test/src/runner/plugin/platform.dart'; // ignore: implementation_imports
import 'package:test/src/runner/plugin/hack_register_platform.dart' as hack; // ignore: implementation_imports import 'package:test/src/runner/plugin/hack_register_platform.dart' as hack; // ignore: implementation_imports
import '../base/file_system.dart';
import '../base/process_manager.dart'; import '../base/process_manager.dart';
import '../dart/package_map.dart'; import '../dart/package_map.dart';
import '../globals.dart'; import '../globals.dart';
import 'coverage_collector.dart'; import 'coverage_collector.dart';
const Duration _kTestStartupTimeout = const Duration(seconds: 5); const Duration _kTestStartupTimeout = const Duration(seconds: 5);
final InternetAddress _kHost = InternetAddress.LOOPBACK_IP_V4; final io.InternetAddress _kHost = io.InternetAddress.LOOPBACK_IP_V4;
void installHook({ String shellPath }) { void installHook({ String shellPath }) {
hack.registerPlatformPlugin(<TestPlatform>[TestPlatform.vm], () => new FlutterPlatform(shellPath: shellPath)); hack.registerPlatformPlugin(<TestPlatform>[TestPlatform.vm], () => new FlutterPlatform(shellPath: shellPath));
...@@ -61,19 +62,19 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -61,19 +62,19 @@ class FlutterPlatform extends PlatformPlugin {
controller.sink.done.then((_) { controllerSinkClosed = true; }); controller.sink.done.then((_) { controllerSinkClosed = true; });
// Prepare our WebSocket server to talk to the engine subproces. // Prepare our WebSocket server to talk to the engine subproces.
HttpServer server = await HttpServer.bind(_kHost, 0); io.HttpServer server = await io.HttpServer.bind(_kHost, 0);
finalizers.add(() async { await server.close(force: true); }); finalizers.add(() async { await server.close(force: true); });
Completer<WebSocket> webSocket = new Completer<WebSocket>(); Completer<io.WebSocket> webSocket = new Completer<io.WebSocket>();
server.listen((HttpRequest request) { server.listen((io.HttpRequest request) {
webSocket.complete(WebSocketTransformer.upgrade(request)); webSocket.complete(io.WebSocketTransformer.upgrade(request));
}); });
// Prepare a temporary directory to store the Dart file that will talk to us. // Prepare a temporary directory to store the Dart file that will talk to us.
Directory temporaryDirectory = Directory.systemTemp.createTempSync('dart_test_listener'); Directory temporaryDirectory = fs.systemTempDirectory.createTempSync('dart_test_listener');
finalizers.add(() async { temporaryDirectory.deleteSync(recursive: true); }); finalizers.add(() async { temporaryDirectory.deleteSync(recursive: true); });
// Prepare the Dart file that will talk to us and start the test. // Prepare the Dart file that will talk to us and start the test.
File listenerFile = new File('${temporaryDirectory.path}/listener.dart'); File listenerFile = fs.file('${temporaryDirectory.path}/listener.dart');
listenerFile.createSync(); listenerFile.createSync();
listenerFile.writeAsStringSync(_generateTestMain( listenerFile.writeAsStringSync(_generateTestMain(
testUrl: path.toUri(path.absolute(testPath)).toString(), testUrl: path.toUri(path.absolute(testPath)).toString(),
...@@ -90,7 +91,7 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -90,7 +91,7 @@ class FlutterPlatform extends PlatformPlugin {
} }
// Start the engine subprocess. // Start the engine subprocess.
Process process = await _startProcess( io.Process process = await _startProcess(
shellPath, shellPath,
listenerFile.path, listenerFile.path,
packages: PackageMap.globalPackagesPath, packages: PackageMap.globalPackagesPath,
...@@ -119,7 +120,7 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -119,7 +120,7 @@ class FlutterPlatform extends PlatformPlugin {
_InitialResult initialResult = await Future.any(<Future<_InitialResult>>[ _InitialResult initialResult = await Future.any(<Future<_InitialResult>>[
process.exitCode.then<_InitialResult>((int exitCode) { return _InitialResult.crashed; }), process.exitCode.then<_InitialResult>((int exitCode) { return _InitialResult.crashed; }),
new Future<_InitialResult>.delayed(_kTestStartupTimeout, () { return _InitialResult.timedOut; }), new Future<_InitialResult>.delayed(_kTestStartupTimeout, () { return _InitialResult.timedOut; }),
webSocket.future.then<_InitialResult>((WebSocket webSocket) { return _InitialResult.connected; }), webSocket.future.then<_InitialResult>((io.WebSocket webSocket) { return _InitialResult.connected; }),
]); ]);
switch (initialResult) { switch (initialResult) {
...@@ -137,7 +138,7 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -137,7 +138,7 @@ class FlutterPlatform extends PlatformPlugin {
await controller.sink.done; await controller.sink.done;
break; break;
case _InitialResult.connected: case _InitialResult.connected:
WebSocket testSocket = await webSocket.future; io.WebSocket testSocket = await webSocket.future;
Completer<Null> harnessDone = new Completer<Null>(); Completer<Null> harnessDone = new Completer<Null>();
StreamSubscription<dynamic> harnessToTest = controller.stream.listen( StreamSubscription<dynamic> harnessToTest = controller.stream.listen(
...@@ -248,15 +249,15 @@ void main() { ...@@ -248,15 +249,15 @@ void main() {
sb.writeln(' <cachedir>/var/cache/fontconfig</cachedir>'); sb.writeln(' <cachedir>/var/cache/fontconfig</cachedir>');
sb.writeln('</fontconfig>'); sb.writeln('</fontconfig>');
Directory fontsDir = Directory.systemTemp.createTempSync('flutter_fonts'); Directory fontsDir = fs.systemTempDirectory.createTempSync('flutter_fonts');
_cachedFontConfig = new File('${fontsDir.path}/fonts.conf'); _cachedFontConfig = fs.file('${fontsDir.path}/fonts.conf');
_cachedFontConfig.createSync(); _cachedFontConfig.createSync();
_cachedFontConfig.writeAsStringSync(sb.toString()); _cachedFontConfig.writeAsStringSync(sb.toString());
return _cachedFontConfig; return _cachedFontConfig;
} }
Future<Process> _startProcess(String executable, String testPath, { String packages, int observatoryPort }) { Future<io.Process> _startProcess(String executable, String testPath, { String packages, int observatoryPort }) {
assert(executable != null); // Please provide the path to the shell in the SKY_SHELL environment variable. assert(executable != null); // Please provide the path to the shell in the SKY_SHELL environment variable.
List<String> arguments = <String>[]; List<String> arguments = <String>[];
if (observatoryPort != null) { if (observatoryPort != null) {
...@@ -279,7 +280,7 @@ void main() { ...@@ -279,7 +280,7 @@ void main() {
return processManager.start(executable, arguments, environment: environment); return processManager.start(executable, arguments, environment: environment);
} }
void _pipeStandardStreamsToConsole(Process process) { void _pipeStandardStreamsToConsole(io.Process process) {
for (Stream<List<int>> stream in for (Stream<List<int>> stream in
<Stream<List<int>>>[process.stderr, process.stdout]) { <Stream<List<int>>>[process.stderr, process.stdout]) {
stream.transform(UTF8.decoder) stream.transform(UTF8.decoder)
......
...@@ -2,11 +2,10 @@ ...@@ -2,11 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'base/context.dart'; import 'base/context.dart';
import 'base/file_system.dart';
import 'build_info.dart'; import 'build_info.dart';
import 'cache.dart'; import 'cache.dart';
import 'globals.dart'; import 'globals.dart';
...@@ -50,14 +49,14 @@ class ToolConfiguration { ...@@ -50,14 +49,14 @@ class ToolConfiguration {
Directory _getEngineArtifactsDirectory(TargetPlatform platform, BuildMode mode) { Directory _getEngineArtifactsDirectory(TargetPlatform platform, BuildMode mode) {
if (engineBuildPath != null) { if (engineBuildPath != null) {
return new Directory(engineBuildPath); return fs.directory(engineBuildPath);
} else { } else {
String suffix = mode != BuildMode.debug ? '-${getModeName(mode)}' : ''; String suffix = mode != BuildMode.debug ? '-${getModeName(mode)}' : '';
// Create something like `android-arm` or `android-arm-release`. // Create something like `android-arm` or `android-arm-release`.
String dirName = getNameForTargetPlatform(platform) + suffix; String dirName = getNameForTargetPlatform(platform) + suffix;
Directory engineDir = cache.getArtifactDirectory('engine'); Directory engineDir = cache.getArtifactDirectory('engine');
return new Directory(path.join(engineDir.path, dirName)); return fs.directory(path.join(engineDir.path, dirName));
} }
} }
...@@ -70,7 +69,7 @@ class ToolConfiguration { ...@@ -70,7 +69,7 @@ class ToolConfiguration {
if (tool == HostTool.SkySnapshot) { if (tool == HostTool.SkySnapshot) {
String clangPath = path.join(engineBuildPath, 'clang_x64', 'sky_snapshot'); String clangPath = path.join(engineBuildPath, 'clang_x64', 'sky_snapshot');
if (FileSystemEntity.isFileSync(clangPath)) if (fs.isFileSync(clangPath))
return clangPath; return clangPath;
return path.join(engineBuildPath, 'sky_snapshot'); return path.join(engineBuildPath, 'sky_snapshot');
} else if (tool == HostTool.SkyShell) { } else if (tool == HostTool.SkyShell) {
......
...@@ -2,12 +2,11 @@ ...@@ -2,12 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:archive/archive.dart'; import 'package:archive/archive.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'asset.dart'; import 'asset.dart';
import 'base/file_system.dart';
import 'base/process.dart'; import 'base/process.dart';
abstract class ZipBuilder { abstract class ZipBuilder {
...@@ -66,7 +65,7 @@ class _ZipToolBuilder extends ZipBuilder { ...@@ -66,7 +65,7 @@ class _ZipToolBuilder extends ZipBuilder {
for (AssetBundleEntry entry in entries) { for (AssetBundleEntry entry in entries) {
List<int> data = entry.contentsAsBytes(); List<int> data = entry.contentsAsBytes();
File file = new File(path.join(zipBuildDir.path, entry.archivePath)); File file = fs.file(path.join(zipBuildDir.path, entry.archivePath));
file.parent.createSync(recursive: true); file.parent.createSync(recursive: true);
file.writeAsBytesSync(data); file.writeAsBytesSync(data);
} }
......
...@@ -12,7 +12,7 @@ dependencies: ...@@ -12,7 +12,7 @@ dependencies:
args: ^0.13.4 args: ^0.13.4
coverage: ^0.8.0 coverage: ^0.8.0
crypto: '>=1.1.1 <3.0.0' crypto: '>=1.1.1 <3.0.0'
file: ^1.0.0 file: '^1.0.1'
http: ^0.11.3 http: ^0.11.3
intl: '>=0.14.0 <0.15.0' intl: '>=0.14.0 <0.15.0'
json_rpc_2: ^2.0.0 json_rpc_2: ^2.0.0
......
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/os.dart';
import 'package:flutter_tools/src/commands/analyze_continuously.dart'; import 'package:flutter_tools/src/commands/analyze_continuously.dart';
import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/dart/pub.dart';
...@@ -21,7 +21,7 @@ void main() { ...@@ -21,7 +21,7 @@ void main() {
setUp(() { setUp(() {
FlutterCommandRunner.initFlutterRoot(); FlutterCommandRunner.initFlutterRoot();
tempDir = Directory.systemTemp.createTempSync('analysis_test'); tempDir = fs.systemTempDirectory.createTempSync('analysis_test');
}); });
tearDown(() { tearDown(() {
...@@ -71,12 +71,12 @@ void main() { ...@@ -71,12 +71,12 @@ void main() {
} }
void _createSampleProject(Directory directory, { bool brokenCode: false }) { void _createSampleProject(Directory directory, { bool brokenCode: false }) {
File pubspecFile = new File(path.join(directory.path, 'pubspec.yaml')); File pubspecFile = fs.file(path.join(directory.path, 'pubspec.yaml'));
pubspecFile.writeAsStringSync(''' pubspecFile.writeAsStringSync('''
name: foo_project name: foo_project
'''); ''');
File dartFile = new File(path.join(directory.path, 'lib', 'main.dart')); File dartFile = fs.file(path.join(directory.path, 'lib', 'main.dart'));
dartFile.parent.createSync(); dartFile.parent.createSync();
dartFile.writeAsStringSync(''' dartFile.writeAsStringSync('''
void main() { void main() {
......
...@@ -2,8 +2,7 @@ ...@@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io'; import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/commands/analyze.dart'; import 'package:flutter_tools/src/commands/analyze.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:test/test.dart'; import 'package:test/test.dart';
...@@ -16,7 +15,7 @@ void main() { ...@@ -16,7 +15,7 @@ void main() {
Directory tempDir; Directory tempDir;
setUp(() { setUp(() {
tempDir = Directory.systemTemp.createTempSync('analysis_duplicate_names_test'); tempDir = fs.systemTempDirectory.createTempSync('analysis_duplicate_names_test');
}); });
tearDown(() { tearDown(() {
...@@ -25,10 +24,10 @@ void main() { ...@@ -25,10 +24,10 @@ void main() {
group('analyze', () { group('analyze', () {
testUsingContext('flutter analyze with two files with the same name', () async { testUsingContext('flutter analyze with two files with the same name', () async {
File dartFileA = new File(path.join(tempDir.path, 'a.dart')); File dartFileA = fs.file(path.join(tempDir.path, 'a.dart'));
dartFileA.parent.createSync(); dartFileA.parent.createSync();
dartFileA.writeAsStringSync('library test;'); dartFileA.writeAsStringSync('library test;');
File dartFileB = new File(path.join(tempDir.path, 'b.dart')); File dartFileB = fs.file(path.join(tempDir.path, 'b.dart'));
dartFileB.writeAsStringSync('library test;'); dartFileB.writeAsStringSync('library test;');
AnalyzeCommand command = new AnalyzeCommand(); AnalyzeCommand command = new AnalyzeCommand();
......
...@@ -2,9 +2,8 @@ ...@@ -2,9 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:flutter_tools/src/android/android_sdk.dart'; import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:test/test.dart'; import 'package:test/test.dart';
...@@ -53,7 +52,7 @@ void main() { ...@@ -53,7 +52,7 @@ void main() {
} }
Directory _createSdkDirectory({ bool withAndroidN: false }) { Directory _createSdkDirectory({ bool withAndroidN: false }) {
Directory dir = Directory.systemTemp.createTempSync('android-sdk'); Directory dir = fs.systemTempDirectory.createTempSync('android-sdk');
_createSdkFile(dir, 'platform-tools/adb'); _createSdkFile(dir, 'platform-tools/adb');
...@@ -72,6 +71,6 @@ Directory _createSdkDirectory({ bool withAndroidN: false }) { ...@@ -72,6 +71,6 @@ Directory _createSdkDirectory({ bool withAndroidN: false }) {
} }
void _createSdkFile(Directory dir, String filePath) { void _createSdkFile(Directory dir, String filePath) {
File file = new File(path.join(dir.path, filePath)); File file = fs.file(path.join(dir.path, filePath));
file.createSync(recursive: true); file.createSync(recursive: true);
} }
...@@ -2,19 +2,20 @@ ...@@ -2,19 +2,20 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'dart:convert'; import 'dart:convert';
import 'package:flutter_tools/src/asset.dart'; import 'package:flutter_tools/src/asset.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
// Create a temporary directory and write a single file into it. // Create a temporary directory and write a single file into it.
Directory tempDir = Directory.systemTemp.createTempSync(); FileSystem fs = new LocalFileSystem();
Directory tempDir = fs.systemTempDirectory.createTempSync();
String projectRoot = tempDir.path; String projectRoot = tempDir.path;
String assetPath = 'banana.txt'; String assetPath = 'banana.txt';
String assetContents = 'banana'; String assetContents = 'banana';
File tempFile = new File(path.join(projectRoot, assetPath)); File tempFile = fs.file(path.join(projectRoot, assetPath));
tempFile.parent.createSync(recursive: true); tempFile.parent.createSync(recursive: true);
tempFile.writeAsBytesSync(UTF8.encode(assetContents)); tempFile.writeAsBytesSync(UTF8.encode(assetContents));
......
...@@ -2,9 +2,8 @@ ...@@ -2,9 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:flutter_tools/src/base/config.dart'; import 'package:flutter_tools/src/base/config.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:test/test.dart'; import 'package:test/test.dart';
...@@ -12,8 +11,8 @@ void main() { ...@@ -12,8 +11,8 @@ void main() {
Config config; Config config;
setUp(() { setUp(() {
Directory tempDiretory = Directory.systemTemp.createTempSync('flutter_test'); Directory tempDiretory = fs.systemTempDirectory.createTempSync('flutter_test');
File file = new File(path.join(tempDiretory.path, '.settings')); File file = fs.file(path.join(tempDiretory.path, '.settings'));
config = new Config(file); config = new Config(file);
}); });
......
...@@ -4,10 +4,11 @@ ...@@ -4,10 +4,11 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'package:args/command_runner.dart'; import 'package:args/command_runner.dart';
import 'package:flutter_tools/src/base/common.dart'; import 'package:flutter_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/create.dart'; import 'package:flutter_tools/src/commands/create.dart';
import 'package:flutter_tools/src/dart/sdk.dart'; import 'package:flutter_tools/src/dart/sdk.dart';
...@@ -22,7 +23,7 @@ void main() { ...@@ -22,7 +23,7 @@ void main() {
Directory temp; Directory temp;
setUp(() { setUp(() {
temp = Directory.systemTemp.createTempSync('flutter_tools'); temp = fs.systemTempDirectory.createTempSync('flutter_tools');
}); });
tearDown(() { tearDown(() {
...@@ -48,14 +49,14 @@ void main() { ...@@ -48,14 +49,14 @@ void main() {
await runner.run(<String>['create', '--no-pub', temp.path]); await runner.run(<String>['create', '--no-pub', temp.path]);
void expectExists(String relPath) { void expectExists(String relPath) {
expect(FileSystemEntity.isFileSync('${temp.path}/$relPath'), true); expect(fs.isFileSync('${temp.path}/$relPath'), true);
} }
expectExists('lib/main.dart'); expectExists('lib/main.dart');
for (FileSystemEntity file in temp.listSync(recursive: true)) { for (FileSystemEntity file in temp.listSync(recursive: true)) {
if (file is File && file.path.endsWith('.dart')) { if (file is File && file.path.endsWith('.dart')) {
String original= file.readAsStringSync(); String original= file.readAsStringSync();
Process process = await Process.start( io.Process process = await io.Process.start(
sdkBinaryName('dartfmt'), sdkBinaryName('dartfmt'),
<String>[file.path], <String>[file.path],
workingDirectory: temp.path, workingDirectory: temp.path,
...@@ -101,7 +102,7 @@ void main() { ...@@ -101,7 +102,7 @@ void main() {
Cache.flutterRoot = '../..'; Cache.flutterRoot = '../..';
CreateCommand command = new CreateCommand(); CreateCommand command = new CreateCommand();
CommandRunner<Null> runner = createTestCommandRunner(command); CommandRunner<Null> runner = createTestCommandRunner(command);
File existingFile = new File("${temp.path.toString()}/bad"); File existingFile = fs.file("${temp.path.toString()}/bad");
if (!existingFile.existsSync()) existingFile.createSync(); if (!existingFile.existsSync()) existingFile.createSync();
try { try {
await runner.run(<String>['create', existingFile.path]); await runner.run(<String>['create', existingFile.path]);
...@@ -123,9 +124,9 @@ Future<Null> _createAndAnalyzeProject(Directory dir, List<String> createArgs) as ...@@ -123,9 +124,9 @@ Future<Null> _createAndAnalyzeProject(Directory dir, List<String> createArgs) as
await runner.run(args); await runner.run(args);
String mainPath = path.join(dir.path, 'lib', 'main.dart'); String mainPath = path.join(dir.path, 'lib', 'main.dart');
expect(new File(mainPath).existsSync(), true); expect(fs.file(mainPath).existsSync(), true);
String flutterToolsPath = path.absolute(path.join('bin', 'flutter_tools.dart')); String flutterToolsPath = path.absolute(path.join('bin', 'flutter_tools.dart'));
ProcessResult exec = Process.runSync( io.ProcessResult exec = io.Process.runSync(
'$dartSdkPath/bin/dart', <String>[flutterToolsPath, 'analyze'], '$dartSdkPath/bin/dart', <String>[flutterToolsPath, 'analyze'],
workingDirectory: dir.path workingDirectory: dir.path
); );
......
...@@ -2,11 +2,10 @@ ...@@ -2,11 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:flutter_tools/src/asset.dart'; import 'package:flutter_tools/src/asset.dart';
import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:test/test.dart'; import 'package:test/test.dart';
...@@ -25,9 +24,9 @@ void main() { ...@@ -25,9 +24,9 @@ void main() {
assetBundle.entries.add(new AssetBundleEntry.fromString('a.txt', '')); assetBundle.entries.add(new AssetBundleEntry.fromString('a.txt', ''));
group('devfs', () { group('devfs', () {
testUsingContext('create local file system', () async { testUsingContext('create local file system', () async {
tempDir = Directory.systemTemp.createTempSync(); tempDir = fs.systemTempDirectory.createTempSync();
basePath = tempDir.path; basePath = tempDir.path;
File file = new File(path.join(basePath, filePath)); File file = fs.file(path.join(basePath, filePath));
await file.parent.create(recursive: true); await file.parent.create(recursive: true);
file.writeAsBytesSync(<int>[1, 2, 3]); file.writeAsBytesSync(<int>[1, 2, 3]);
}); });
...@@ -41,14 +40,14 @@ void main() { ...@@ -41,14 +40,14 @@ void main() {
expect(devFSOperations.contains('writeFile test bar/foo.txt'), isTrue); expect(devFSOperations.contains('writeFile test bar/foo.txt'), isTrue);
}); });
testUsingContext('add new file to local file system', () async { testUsingContext('add new file to local file system', () async {
File file = new File(path.join(basePath, filePath2)); File file = fs.file(path.join(basePath, filePath2));
await file.parent.create(recursive: true); await file.parent.create(recursive: true);
file.writeAsBytesSync(<int>[1, 2, 3, 4, 5, 6, 7]); file.writeAsBytesSync(<int>[1, 2, 3, 4, 5, 6, 7]);
await devFS.update(); await devFS.update();
expect(devFSOperations.contains('writeFile test foo/bar.txt'), isTrue); expect(devFSOperations.contains('writeFile test foo/bar.txt'), isTrue);
}); });
testUsingContext('modify existing file on local file system', () async { testUsingContext('modify existing file on local file system', () async {
File file = new File(path.join(basePath, filePath)); File file = fs.file(path.join(basePath, filePath));
// Set the last modified time to 5 seconds in the past. // Set the last modified time to 5 seconds in the past.
updateFileModificationTime(file.path, new DateTime.now(), -5); updateFileModificationTime(file.path, new DateTime.now(), -5);
await devFS.update(); await devFS.update();
...@@ -57,7 +56,7 @@ void main() { ...@@ -57,7 +56,7 @@ void main() {
expect(devFSOperations.contains('writeFile test bar/foo.txt'), isTrue); expect(devFSOperations.contains('writeFile test bar/foo.txt'), isTrue);
}); });
testUsingContext('delete a file from the local file system', () async { testUsingContext('delete a file from the local file system', () async {
File file = new File(path.join(basePath, filePath)); File file = fs.file(path.join(basePath, filePath));
await file.delete(); await file.delete();
await devFS.update(); await devFS.update();
expect(devFSOperations.contains('deleteFile test bar/foo.txt'), isTrue); expect(devFSOperations.contains('deleteFile test bar/foo.txt'), isTrue);
......
...@@ -23,6 +23,7 @@ void main() { ...@@ -23,6 +23,7 @@ void main() {
group('drive', () { group('drive', () {
DriveCommand command; DriveCommand command;
Device mockDevice; Device mockDevice;
MemoryFileSystem memoryFileSystem;
void withMockDevice([Device mock]) { void withMockDevice([Device mock]) {
mockDevice = mock ?? new MockDevice(); mockDevice = mock ?? new MockDevice();
...@@ -33,9 +34,15 @@ void main() { ...@@ -33,9 +34,15 @@ void main() {
setUp(() { setUp(() {
command = new DriveCommand(); command = new DriveCommand();
applyMocksToCommand(command); applyMocksToCommand(command);
useInMemoryFileSystem(cwd: '/some/app'); memoryFileSystem = new MemoryFileSystem();
fs.directory('test').createSync(); String cwd = '/some/app';
fs.directory('test_driver').createSync(); memoryFileSystem.directory(cwd).createSync(recursive: true);
memoryFileSystem.currentDirectory = cwd;
memoryFileSystem.directory('test').createSync();
memoryFileSystem.directory('test_driver').createSync();
memoryFileSystem.file('pubspec.yaml').createSync();
memoryFileSystem.file('.packages').createSync();
setExitFunctionForTests();
targetDeviceFinder = () { targetDeviceFinder = () {
throw 'Unexpected call to targetDeviceFinder'; throw 'Unexpected call to targetDeviceFinder';
}; };
...@@ -52,7 +59,7 @@ void main() { ...@@ -52,7 +59,7 @@ void main() {
tearDown(() { tearDown(() {
command = null; command = null;
restoreFileSystem(); restoreExitFunction();
restoreAppStarter(); restoreAppStarter();
restoreAppStopper(); restoreAppStopper();
restoreTestRunner(); restoreTestRunner();
...@@ -72,6 +79,8 @@ void main() { ...@@ -72,6 +79,8 @@ void main() {
expect(e.exitCode ?? 1, 1); expect(e.exitCode ?? 1, 1);
expect(e.message, contains('Test file not found: /some/app/test_driver/e2e_test.dart')); expect(e.message, contains('Test file not found: /some/app/test_driver/e2e_test.dart'));
} }
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('returns 1 when app fails to run', () async { testUsingContext('returns 1 when app fails to run', () async {
...@@ -81,7 +90,7 @@ void main() { ...@@ -81,7 +90,7 @@ void main() {
String testApp = '/some/app/test_driver/e2e.dart'; String testApp = '/some/app/test_driver/e2e.dart';
String testFile = '/some/app/test_driver/e2e_test.dart'; String testFile = '/some/app/test_driver/e2e_test.dart';
MemoryFileSystem memFs = fs; MemoryFileSystem memFs = memoryFileSystem;
await memFs.file(testApp).writeAsString('main() {}'); await memFs.file(testApp).writeAsString('main() {}');
await memFs.file(testFile).writeAsString('main() {}'); await memFs.file(testFile).writeAsString('main() {}');
...@@ -96,12 +105,11 @@ void main() { ...@@ -96,12 +105,11 @@ void main() {
expect(e.exitCode, 1); expect(e.exitCode, 1);
expect(e.message, contains('Application failed to start (1). Will not run test. Quitting.')); expect(e.message, contains('Application failed to start (1). Will not run test. Quitting.'));
} }
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('returns 1 when app file is outside package', () async { testUsingContext('returns 1 when app file is outside package', () async {
String packageDir = '/my/app';
useInMemoryFileSystem(cwd: packageDir);
String appFile = '/not/in/my/app.dart'; String appFile = '/not/in/my/app.dart';
List<String> args = <String>[ List<String> args = <String>[
'drive', 'drive',
...@@ -113,16 +121,15 @@ void main() { ...@@ -113,16 +121,15 @@ void main() {
} on ToolExit catch (e) { } on ToolExit catch (e) {
expect(e.exitCode ?? 1, 1); expect(e.exitCode ?? 1, 1);
expect(testLogger.errorText, contains( expect(testLogger.errorText, contains(
'Application file $appFile is outside the package directory $packageDir', 'Application file $appFile is outside the package directory /some/app',
)); ));
} }
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('returns 1 when app file is in the root dir', () async { testUsingContext('returns 1 when app file is in the root dir', () async {
String packageDir = '/my/app'; String appFile = '/some/app/main.dart';
useInMemoryFileSystem(cwd: packageDir);
String appFile = '/my/app/main.dart';
List<String> args = <String>[ List<String> args = <String>[
'drive', 'drive',
'--target=$appFile', '--target=$appFile',
...@@ -137,6 +144,8 @@ void main() { ...@@ -137,6 +144,8 @@ void main() {
'sub-directories of the package structure, not in the root directory.', 'sub-directories of the package structure, not in the root directory.',
)); ));
} }
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('returns 0 when test ends successfully', () async { testUsingContext('returns 0 when test ends successfully', () async {
...@@ -156,7 +165,7 @@ void main() { ...@@ -156,7 +165,7 @@ void main() {
return new Future<int>.value(0); return new Future<int>.value(0);
}); });
MemoryFileSystem memFs = fs; MemoryFileSystem memFs = memoryFileSystem;
await memFs.file(testApp).writeAsString('main() {}'); await memFs.file(testApp).writeAsString('main() {}');
await memFs.file(testFile).writeAsString('main() {}'); await memFs.file(testFile).writeAsString('main() {}');
...@@ -166,6 +175,8 @@ void main() { ...@@ -166,6 +175,8 @@ void main() {
]; ];
await createTestCommandRunner(command).run(args); await createTestCommandRunner(command).run(args);
expect(testLogger.errorText, isEmpty); expect(testLogger.errorText, isEmpty);
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('returns exitCode set by test runner', () async { testUsingContext('returns exitCode set by test runner', () async {
...@@ -184,7 +195,7 @@ void main() { ...@@ -184,7 +195,7 @@ void main() {
return new Future<int>.value(0); return new Future<int>.value(0);
}); });
MemoryFileSystem memFs = fs; MemoryFileSystem memFs = memoryFileSystem;
await memFs.file(testApp).writeAsString('main() {}'); await memFs.file(testApp).writeAsString('main() {}');
await memFs.file(testFile).writeAsString('main() {}'); await memFs.file(testFile).writeAsString('main() {}');
...@@ -199,6 +210,8 @@ void main() { ...@@ -199,6 +210,8 @@ void main() {
expect(e.exitCode ?? 1, 123); expect(e.exitCode ?? 1, 123);
expect(e.message, isNull); expect(e.message, isNull);
} }
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
group('findTargetDevice', () { group('findTargetDevice', () {
...@@ -210,6 +223,8 @@ void main() { ...@@ -210,6 +223,8 @@ void main() {
Device device = await findTargetDevice(); Device device = await findTargetDevice();
expect(device.name, 'specified-device'); expect(device.name, 'specified-device');
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
}); });
...@@ -227,6 +242,8 @@ void main() { ...@@ -227,6 +242,8 @@ void main() {
Device device = await findTargetDevice(); Device device = await findTargetDevice();
expect(device.name, 'mock-simulator'); expect(device.name, 'mock-simulator');
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('uses existing Android device if and there are no simulators', () async { testUsingContext('uses existing Android device if and there are no simulators', () async {
...@@ -238,6 +255,8 @@ void main() { ...@@ -238,6 +255,8 @@ void main() {
Device device = await findTargetDevice(); Device device = await findTargetDevice();
expect(device.name, 'mock-android-device'); expect(device.name, 'mock-android-device');
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('launches emulator', () async { testUsingContext('launches emulator', () async {
...@@ -250,6 +269,8 @@ void main() { ...@@ -250,6 +269,8 @@ void main() {
Device device = await findTargetDevice(); Device device = await findTargetDevice();
expect(device.name, 'new-simulator'); expect(device.name, 'new-simulator');
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
}); });
...@@ -262,6 +283,8 @@ void main() { ...@@ -262,6 +283,8 @@ void main() {
testUsingContext('returns null if no devices found', () async { testUsingContext('returns null if no devices found', () async {
setOs(); setOs();
expect(await findTargetDevice(), isNull); expect(await findTargetDevice(), isNull);
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
testUsingContext('uses existing Android device', () async { testUsingContext('uses existing Android device', () async {
...@@ -272,6 +295,8 @@ void main() { ...@@ -272,6 +295,8 @@ void main() {
Device device = await findTargetDevice(); Device device = await findTargetDevice();
expect(device.name, 'mock-android-device'); expect(device.name, 'mock-android-device');
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
}); });
}); });
}); });
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:args/command_runner.dart'; import 'package:args/command_runner.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/create.dart'; import 'package:flutter_tools/src/commands/create.dart';
import 'package:flutter_tools/src/commands/format.dart'; import 'package:flutter_tools/src/commands/format.dart';
...@@ -21,7 +21,7 @@ void main() { ...@@ -21,7 +21,7 @@ void main() {
setUp(() { setUp(() {
Cache.disableLocking(); Cache.disableLocking();
temp = Directory.systemTemp.createTempSync('flutter_tools'); temp = fs.systemTempDirectory.createTempSync('flutter_tools');
}); });
tearDown(() { tearDown(() {
...@@ -38,7 +38,7 @@ void main() { ...@@ -38,7 +38,7 @@ void main() {
testUsingContext('a file', () async { testUsingContext('a file', () async {
await createProject(); await createProject();
File srcFile = new File(path.join(temp.path, 'lib', 'main.dart')); File srcFile = fs.file(path.join(temp.path, 'lib', 'main.dart'));
String original = srcFile.readAsStringSync(); String original = srcFile.readAsStringSync();
srcFile.writeAsStringSync(original.replaceFirst('main()', 'main( )')); srcFile.writeAsStringSync(original.replaceFirst('main()', 'main( )'));
......
...@@ -2,20 +2,21 @@ ...@@ -2,20 +2,21 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io'; import 'dart:io' as io;
import 'src/context.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/os.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'src/context.dart';
void main() { void main() {
group('OperatingSystemUtils', () { group('OperatingSystemUtils', () {
Directory temp; Directory temp;
setUp(() { setUp(() {
temp = Directory.systemTemp.createTempSync('flutter_tools'); temp = fs.systemTempDirectory.createTempSync('flutter_tools');
}); });
tearDown(() { tearDown(() {
...@@ -23,12 +24,12 @@ void main() { ...@@ -23,12 +24,12 @@ void main() {
}); });
testUsingContext('makeExecutable', () async { testUsingContext('makeExecutable', () async {
File file = new File(path.join(temp.path, 'foo.script')); File file = fs.file(path.join(temp.path, 'foo.script'));
file.writeAsStringSync('hello world'); file.writeAsStringSync('hello world');
os.makeExecutable(file); os.makeExecutable(file);
// Skip this test on windows. // Skip this test on windows.
if (!Platform.isWindows) { if (!io.Platform.isWindows) {
String mode = file.statSync().modeString(); String mode = file.statSync().modeString();
// rwxr--r-- // rwxr--r--
expect(mode.substring(0, 3), endsWith('x')); expect(mode.substring(0, 3), endsWith('x'));
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:args/command_runner.dart'; import 'package:args/command_runner.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/commands/create.dart'; import 'package:flutter_tools/src/commands/create.dart';
import 'package:flutter_tools/src/commands/packages.dart'; import 'package:flutter_tools/src/commands/packages.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
...@@ -18,7 +18,7 @@ void main() { ...@@ -18,7 +18,7 @@ void main() {
Directory temp; Directory temp;
setUp(() { setUp(() {
temp = Directory.systemTemp.createTempSync('flutter_tools'); temp = fs.systemTempDirectory.createTempSync('flutter_tools');
}); });
tearDown(() { tearDown(() {
...@@ -42,7 +42,7 @@ void main() { ...@@ -42,7 +42,7 @@ void main() {
} }
void expectExists(String relPath) { void expectExists(String relPath) {
expect(FileSystemEntity.isFileSync('${temp.path}/$relPath'), true); expect(fs.isFileSync('${temp.path}/$relPath'), true);
} }
// Verify that we create a project that is well-formed. // Verify that we create a project that is well-formed.
......
...@@ -4,10 +4,11 @@ ...@@ -4,10 +4,11 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io' as io;
import 'package:archive/archive.dart'; import 'package:archive/archive.dart';
import 'package:flutter_tools/src/base/context.dart'; import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/os.dart';
import 'package:flutter_tools/src/base/process.dart'; import 'package:flutter_tools/src/base/process.dart';
...@@ -32,7 +33,7 @@ void main() { ...@@ -32,7 +33,7 @@ void main() {
ProcessManager manager; ProcessManager manager;
setUp(() { setUp(() {
tmp = Directory.systemTemp.createTempSync('flutter_tools_'); tmp = fs.systemTempDirectory.createTempSync('flutter_tools_');
manager = new RecordingProcessManager(tmp.path); manager = new RecordingProcessManager(tmp.path);
}); });
...@@ -41,7 +42,7 @@ void main() { ...@@ -41,7 +42,7 @@ void main() {
}); });
test('start', () async { test('start', () async {
Process process = await manager.start('echo', <String>['foo']); io.Process process = await manager.start('echo', <String>['foo']);
int pid = process.pid; int pid = process.pid;
int exitCode = await process.exitCode; int exitCode = await process.exitCode;
List<int> stdout = await _consume(process.stdout); List<int> stdout = await _consume(process.stdout);
...@@ -63,7 +64,7 @@ void main() { ...@@ -63,7 +64,7 @@ void main() {
}); });
test('run', () async { test('run', () async {
ProcessResult result = await manager.run('echo', <String>['bar']); io.ProcessResult result = await manager.run('echo', <String>['bar']);
int pid = result.pid; int pid = result.pid;
int exitCode = result.exitCode; int exitCode = result.exitCode;
String stdout = result.stdout; String stdout = result.stdout;
...@@ -85,7 +86,7 @@ void main() { ...@@ -85,7 +86,7 @@ void main() {
}); });
test('runSync', () async { test('runSync', () async {
ProcessResult result = manager.runSync('echo', <String>['baz']); io.ProcessResult result = manager.runSync('echo', <String>['baz']);
int pid = result.pid; int pid = result.pid;
int exitCode = result.exitCode; int exitCode = result.exitCode;
String stdout = result.stdout; String stdout = result.stdout;
...@@ -112,7 +113,7 @@ void main() { ...@@ -112,7 +113,7 @@ void main() {
setUp(() async { setUp(() async {
await runInMinimalContext(() async { await runInMinimalContext(() async {
Directory dir = new Directory('test/data/process_manager/replay'); Directory dir = fs.directory('test/data/process_manager/replay');
manager = await ReplayProcessManager.create(dir.path); manager = await ReplayProcessManager.create(dir.path);
}); });
}); });
...@@ -123,7 +124,7 @@ void main() { ...@@ -123,7 +124,7 @@ void main() {
}); });
test('start', () async { test('start', () async {
Process process = await manager.start('sing', <String>['ppap']); io.Process process = await manager.start('sing', <String>['ppap']);
int exitCode = await process.exitCode; int exitCode = await process.exitCode;
List<int> stdout = await _consume(process.stdout); List<int> stdout = await _consume(process.stdout);
List<int> stderr = await _consume(process.stderr); List<int> stderr = await _consume(process.stderr);
...@@ -134,7 +135,7 @@ void main() { ...@@ -134,7 +135,7 @@ void main() {
}); });
test('run', () async { test('run', () async {
ProcessResult result = await manager.run('dance', <String>['gangnam-style']); io.ProcessResult result = await manager.run('dance', <String>['gangnam-style']);
expect(result.pid, 101); expect(result.pid, 101);
expect(result.exitCode, 2); expect(result.exitCode, 2);
expect(result.stdout, ''); expect(result.stdout, '');
...@@ -142,7 +143,7 @@ void main() { ...@@ -142,7 +143,7 @@ void main() {
}); });
test('runSync', () { test('runSync', () {
ProcessResult result = manager.runSync('dance', <String>['gangnam-style']); io.ProcessResult result = manager.runSync('dance', <String>['gangnam-style']);
expect(result.pid, 101); expect(result.pid, 101);
expect(result.exitCode, 2); expect(result.exitCode, 2);
expect(result.stdout, ''); expect(result.stdout, '');
...@@ -153,6 +154,7 @@ void main() { ...@@ -153,6 +154,7 @@ void main() {
Future<Null> runInMinimalContext(Future<dynamic> method()) async { Future<Null> runInMinimalContext(Future<dynamic> method()) async {
AppContext context = new AppContext(); AppContext context = new AppContext();
context.putIfAbsent(FileSystem, () => new LocalFileSystem());
context.putIfAbsent(ProcessManager, () => new ProcessManager()); context.putIfAbsent(ProcessManager, () => new ProcessManager());
context.putIfAbsent(Logger, () => new BufferLogger()); context.putIfAbsent(Logger, () => new BufferLogger());
context.putIfAbsent(OperatingSystemUtils, () => new OperatingSystemUtils()); context.putIfAbsent(OperatingSystemUtils, () => new OperatingSystemUtils());
...@@ -167,7 +169,7 @@ class _Recording { ...@@ -167,7 +169,7 @@ class _Recording {
_Recording(this.file, this._archive); _Recording(this.file, this._archive);
static _Recording readFrom(Directory dir) { static _Recording readFrom(Directory dir) {
File file = new File(path.join( File file = fs.file(path.join(
dir.path, RecordingProcessManager.kDefaultRecordTo)); dir.path, RecordingProcessManager.kDefaultRecordTo));
Archive archive = new ZipDecoder().decodeBytes(file.readAsBytesSync()); Archive archive = new ZipDecoder().decodeBytes(file.readAsBytesSync());
return new _Recording(file, archive); return new _Recording(file, archive);
...@@ -194,7 +196,7 @@ class _Recording { ...@@ -194,7 +196,7 @@ class _Recording {
Encoding encoding; Encoding encoding;
if (encodingName != null) if (encodingName != null)
encoding = encodingName == 'system' encoding = encodingName == 'system'
? const SystemEncoding() ? const io.SystemEncoding()
: Encoding.getByName(encodingName); : Encoding.getByName(encodingName);
return _getFileContent('$basename.$type', encoding); return _getFileContent('$basename.$type', encoding);
} }
......
...@@ -7,6 +7,7 @@ import 'dart:io'; ...@@ -7,6 +7,7 @@ import 'dart:io';
import 'package:flutter_tools/src/base/config.dart'; import 'package:flutter_tools/src/base/config.dart';
import 'package:flutter_tools/src/base/context.dart'; import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/os.dart';
import 'package:flutter_tools/src/base/process_manager.dart'; import 'package:flutter_tools/src/base/process_manager.dart';
...@@ -41,6 +42,7 @@ void testUsingContext(String description, dynamic testMethod(), { ...@@ -41,6 +42,7 @@ void testUsingContext(String description, dynamic testMethod(), {
// Initialize the test context with some default mocks. // Initialize the test context with some default mocks.
// Seed these context entries first since others depend on them // Seed these context entries first since others depend on them
testContext.putIfAbsent(FileSystem, () => new LocalFileSystem());
testContext.putIfAbsent(ProcessManager, () => new ProcessManager()); testContext.putIfAbsent(ProcessManager, () => new ProcessManager());
testContext.putIfAbsent(Logger, () => new BufferLogger()); testContext.putIfAbsent(Logger, () => new BufferLogger());
......
...@@ -3,8 +3,9 @@ ...@@ -3,8 +3,9 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io' as io;
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/dart/sdk.dart'; import 'package:flutter_tools/src/dart/sdk.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
...@@ -30,12 +31,12 @@ void main() { ...@@ -30,12 +31,12 @@ void main() {
Future<Null> _testFile(String testName, int wantedExitCode) async { Future<Null> _testFile(String testName, int wantedExitCode) async {
final String manualTestsDirectory = path.join('..', '..', 'dev', 'automated_tests'); final String manualTestsDirectory = path.join('..', '..', 'dev', 'automated_tests');
final String fullTestName = path.join(manualTestsDirectory, 'flutter_test', '${testName}_test.dart'); final String fullTestName = path.join(manualTestsDirectory, 'flutter_test', '${testName}_test.dart');
final File testFile = new File(fullTestName); final File testFile = fs.file(fullTestName);
expect(testFile.existsSync(), true); expect(testFile.existsSync(), true);
final String fullTestExpectation = path.join(manualTestsDirectory, 'flutter_test', '${testName}_expectation.txt'); final String fullTestExpectation = path.join(manualTestsDirectory, 'flutter_test', '${testName}_expectation.txt');
final File expectationFile = new File(fullTestExpectation); final File expectationFile = fs.file(fullTestExpectation);
expect(expectationFile.existsSync(), true); expect(expectationFile.existsSync(), true);
final ProcessResult exec = await Process.run( final io.ProcessResult exec = await io.Process.run(
path.join(dartSdkPath, 'bin', 'dart'), path.join(dartSdkPath, 'bin', 'dart'),
<String>[ <String>[
path.absolute(path.join('bin', 'flutter_tools.dart')), path.absolute(path.join('bin', 'flutter_tools.dart')),
...@@ -47,7 +48,7 @@ Future<Null> _testFile(String testName, int wantedExitCode) async { ...@@ -47,7 +48,7 @@ Future<Null> _testFile(String testName, int wantedExitCode) async {
); );
expect(exec.exitCode, wantedExitCode); expect(exec.exitCode, wantedExitCode);
final List<String> output = exec.stdout.split('\n'); final List<String> output = exec.stdout.split('\n');
final List<String> expectations = new File(fullTestExpectation).readAsLinesSync(); final List<String> expectations = fs.file(fullTestExpectation).readAsLinesSync();
bool allowSkip = false; bool allowSkip = false;
int expectationLineNumber = 0; int expectationLineNumber = 0;
int outputLineNumber = 0; int outputLineNumber = 0;
......
...@@ -2,8 +2,7 @@ ...@@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io'; import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/toolchain.dart'; import 'package:flutter_tools/src/toolchain.dart';
...@@ -14,7 +13,7 @@ import 'src/context.dart'; ...@@ -14,7 +13,7 @@ import 'src/context.dart';
void main() { void main() {
group('ToolConfiguration', () { group('ToolConfiguration', () {
Directory tempDir; Directory tempDir;
tempDir = Directory.systemTemp.createTempSync('flutter_temp'); tempDir = fs.systemTempDirectory.createTempSync('flutter_temp');
testUsingContext('using cache', () { testUsingContext('using cache', () {
ToolConfiguration toolConfig = new ToolConfiguration(); ToolConfiguration toolConfig = new ToolConfiguration();
......
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